Excel高亮部分字符串

Sub subHighLightKeyText(ByRef objRg As Range, ByVal key$, ByRef colorValue&)
    Dim sh As Worksheet, str$, startPos%, setLen%, nextFindStart%, rg As Range

    setLen = VBA.Len(key)
    For Each rg In objRg
        str = rg.Text
        nextFindStart = 1
        startPos = VBA.InStr(nextFindStart, str, key, vbTextCompare)

        While startPos > 0
            rg.Characters(Start:=startPos, Length:=setLen).Font.Color = colorValue
            nextFindStart = startPos + setLen
            startPos = VBA.InStr(nextFindStart, str, key, vbTextCompare)
        Wend
    Next
End Sub

Sub setHighLightKeyText()
    Dim key$, ibRet, arr() As String, lColor&, rg As Range
    Dim str$

    str = "format:key,[highlightColor],[atRange]" & VBA.Chr(13) & VBA.Chr(10)
    str = str & "highlightColor:r->red, g->green, b->blue" & VBA.Chr(13) & VBA.Chr(10)
    str = str & "atRange:u->used range on current sheet, s->selected range on current sheet" & VBA.Chr(13) & VBA.Chr(10)
    str = str & "[highlightColor][atRange] can be omitted. Default value is used when omitted." & VBA.Chr(13) & VBA.Chr(10)
    str = str & "highlightColor default:r, atRange default:u" & VBA.Chr(13) & VBA.Chr(10) & VBA.Chr(13) & VBA.Chr(10)
    
    str = str & "example:mykey" & VBA.Chr(13) & VBA.Chr(10)
    str = str & "example:mykey,rb" & VBA.Chr(13) & VBA.Chr(10)
    str = str & "example:mykey,rb,s" & VBA.Chr(13) & VBA.Chr(10)
    str = str & "example:mykey,,s" & VBA.Chr(13) & VBA.Chr(10)
    
    'set default value
    Set rg = ActiveSheet.UsedRange
    lColor = VBA.RGB(255, 0, 0) 'red
    
    ibRet = VBA.InputBox(str, "input param", "")
    If ibRet = "" Then MsgBox "param err", vbCritical + vbOKOnly, "Error": Exit Sub
    arr = VBA.Split(ibRet, ",")

    If UBound(arr) >= 3 Then
        MsgBox "param count > 3", vbCritical + vbOKOnly, "Error": Exit Sub
    End If
    
    key = arr(0)
    If UBound(arr) >= 1 Then
        lColor = 0
        If VBA.InStr(1, arr(1), "r", vbTextCompare) > 0 Then
            lColor = lColor + VBA.RGB(255, 0, 0)
        End If
        If VBA.InStr(1, arr(1), "g", vbTextCompare) > 0 Then
            lColor = lColor + VBA.RGB(0, 255, 0)
        End If
        If VBA.InStr(1, arr(1), "b", vbTextCompare) > 0 Then
            lColor = lColor + VBA.RGB(0, 0, 255)
        End If
    End If
    If UBound(arr) >= 2 Then
        If arr(2) = "s" Then
            Set rg = Selection
        End If
    End If
    Call subHighLightKeyText(rg, key, lColor)
End Sub

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值