2016-09-28 26 views
1

スプレッドシートの選択領域に条件付き書式を設定するExcel 2010 VBAマクロがあります。例として次のコードを検索し、その後色セルテキストパターンを:条件付き書式設定のRegExを使用する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の後に数字が続く単純な一致。

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

私はSelectionにこれを適用する方法を考え出したていないが:

私は、RegExp obectを作成しました。

いつもよろしくお願いします。

+0

マクロ内これをやっている場合は、選択中のセルを反復し、正規表現マッチ_if_各セルのためにあなたのFormatConditionsを設定することができますか? –

+0

なぜ正規表現ですか?あなたは 'Cell.Value Like" TN# "'で同じことを達成できます –

答えて

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には、UDFをプルーフするために入力された=myCFR(A2)が含まれています。

cfr_udf

関連する問題