使用RegEx进行条件格式化的Excel VBA

我有一个Excel 2010 VBAmacros,它在电子表格的选定区域上执行一些条件格式。 作为一个例子,下面的代码片段search一个文本模式然后着色单元格:

Selection.FormatConditions.Add Type:=xlTextString, String:="TextToMatch", _ TextOperator:=xlContains Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority With Selection.FormatConditions(1).Interior .PatternColorIndex = xlAutomatic .ColorIndex = 36 .TintAndShade = 0 End With Selection.FormatConditions(1).StopIfTrue = False 

我想补充的是匹配正则expression式TN[0-9] 。 stringTN跟一个数字的简单匹配。

我创build了RegExp:

 Dim regEx As Object Set regEx = CreateObject("VBScript.RegExp") With regEx .Pattern = "TN[0-9]" End With 

但是我还没有想出如何将这个应用到Selection

一如既往,感谢您的帮助。

我会build议使用您的VBScript.RegExp对象的静态types的对象。

将传递给函数的范围向下切换到Worksheet.UsedRange属性 。 这允许select全列而不计算空行/列。

 Option Explicit Sub createCFR() With Selection 'cut Selection down to the .UsedRange so that full row or full 'column references do not use undue calculation With Intersect(.Cells, .Cells.Parent.UsedRange) .FormatConditions.Delete With .FormatConditions.Add(Type:=xlExpression, Formula1:="=myCFR(" & .Cells(1).Address(0, 0) & ")") .SetFirstPriority With .Interior .PatternColorIndex = xlAutomatic .ColorIndex = 36 .TintAndShade = 0 End With .StopIfTrue = False End With End With End With End Sub Function myCFR(rng As Range) Static rgx As Object 'with rgx as static, it only has to be created once 'this is beneficial when filling a long column with this UDF If rgx Is Nothing Then Set rgx = CreateObject("VBScript.RegExp") End If 'make sure rng is a single cell Set rng = rng.Cells(1, 1) With rgx .Global = True .MultiLine = True .Pattern = "TN[0-9]" myCFR = .Test(rng.Value2) End With End Function 

根据您的select ,您可能需要修改用于创buildCFR的Range.Address属性的参数; 例如$A1就是.Address(1, 0)

在下图中,B2:B7包含=myCFR(A2) ,用于certificateUDF。

cfr_udf