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

我有一种情况,在这种情况下,我需要一些文本序列中的几个字符来显示红色。

例如。 文本序列 – AAA 20.2%, BBB 23.3%, CCC 32.7%等。 在文本序列中,我只需要红色的百分比值,即红色的AAA“20.2%”,红色的BBB“23.3%”,红色的CCC“32.7%”

这个序列是通过做查找得到的,即单元格H4有一个查找公式,通过它我已经获得了这个序列。
我试图改变使用下面的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