使用vba格式化单元格中的特定文本序列



我有一种情况,需要文本序列中的几个字符才能具有红色。

例如。文本序列-AAA 20.2%, BBB 23.3%, CCC 32.7%等等。在文本序列中,我只需要百分比值为红色,即AAA红色"20.2%",BBB红色"23.3%",CCC红色"32.7%">

该序列是通过进行vlookup获得的,即单元H4具有vlookup公式,我通过该公式获得了该序列
我尝试使用以下VBA代码更改颜色,但它没有按预期工作。

Public Function red_color(text As Range) As String
Dim StartChar As Integer, LenColor As Integer
'Dim result As String
Dim regex As Object
Set regex = CreateObject("VBScript.RegExp")
Dim i As Integer
i = 1
With regex
.Pattern = "d?"
End With
While Mid(text, InStr(i, text, "%"), 1) = "%"
'Mid(text, instr(i, text, " ")+1, instr(i, text, ",")-1)
StartChar = InStr(i, text, regex.Execute(text))
LenColor = Len(Mid(text, InStr(i, text, " ") + 1, InStr(i, text, "%")))
text.Characters(StartChar, LenColor).Font.Color = RGB(255, 0, 0)
i = InStr(i, text, "%") + 1
Wend
'red_color = result
End Function

所以最终结果应该像red_color(vlookup())一样,它会给我所需要的输出。

如果单元格有公式,则不能像尝试那样为单元格中的文本上色。

这是regex代码的"固定"版本,但您需要添加一些代码来填充单元格。

Public Function red_color(c As Range) As String
Dim regex As Object, matches, match
Set regex = CreateObject("VBScript.RegExp")
'here you need to calculate the cell content....
c.Font.Color = vbBlack
With regex
.Global = True
.Pattern = "(d+.?d+%)"
End With
Set matches = regex.Execute(c.text)
For Each match In matches
c.Characters(match.firstindex + 1, match.Length).Font.Color = RGB(255, 0, 0)
Next match
End Function

最新更新