2016-09-28 320 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