2016-09-28 319 views
1

我有一个Excel 2010 VBA宏做了一些条件格式在电子表格的选择区域。作为一个例子文本模式下面的片段搜索,然后颜色的单元:Excel中使用VBA为正则表达式条件格式化

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 

我想补充的是要匹配的正则表达式TN[0-9]。字符串TN后跟一个数字的简单匹配。

我所创建的正则表达式obect:

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

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

和往常一样,感谢您的帮助。

+0

如果你是一个宏内这样做,你可以遍历在选择单元格,并设置条件格式为_if_正则表达式匹配的每个细胞? –

+0

为什么使用正则表达式?你可以用'Cell.Value Like'完成同样的事情 –

回答

0

我会建议使用一个静态对象为您VBScript.RegExp对象。

剪切范围内传递到函数下降到Worksheet.UsedRange property。这允许选择全列而不计算空行/列。

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 

根据您Selection,您可能需要修改用于创建CFR的Range.Address property的参数;例如$A1将是.Address(1, 0)

在下面的图像,B2:B7包含=myCFR(A2)向下填充校对的UDF。

cfr_udf