2016-05-04 5 views
0

ん:何らかの理由でエクセルVBA - 正規表現 - 「テスト」操作は動作しますが、「実行」操作は、次のコードを参照してくださいしませ

Sub CountAndHighlightProblematicCells() 

Dim RegExpo As New RegExp 
Dim strPattern As String: strPattern = "[^\u0020-\u007E]" 
Dim specialCharactersFound As Object 


Dim strInput As String 
Dim counter As Long 

RegExpo.Global = True 
RegExpo.MultiLine = True 
RegExpo.IgnoreCase = False 
RegExpo.Pattern = strPattern 

counter = 0 

For Each cell In Worksheets(1).Range("A1:A100") 
    strInput = Worksheets(1).Range(cell.Address).Value 
    If (RegExpo.Test(strInput)) Then 
     Worksheets(1).Range(cell.Address).Interior.ColorIndex = 20 
     counter = counter + 1 
    End If 
    Set specialCharactersFound = RegExpo.Execute(strInput) 

Next 

MsgBox ("Number of affected cells: " & counter) 
MsgBox ("Number of special characters found: " & specialCharactersFound.Count) 

End Sub 

を期待通りに、テスト動作は動作しますが、実行する動作を行いますない。

もしそれがforループと関係していると思うなら、私はチェックしましたが、そうではありません - フォーカスが1つのセルのみであっても実行操作が期待通りに機能しません。

私は間違っていますか?私はVBAやRegExp の経験はあまりありません。予め

おかげで、

Kurkum

+0

テストするサンプル文字列は何ですか? Unicodeシンボルを使用していますか?私はreproできません、 'Execute'はUnicode文字にマッチします。 –

+0

あなたのコードは、特殊な文字が含まれているかどうかに関係なく、チェックされた最後のセルからのカウントだけを返します。 – Rory

+0

実際には、「specialCharactersFound」には常に最後の「特殊」文字が含まれます。 –

答えて

1

Iが変数宣言に、これらの2行追加することをお勧め:次いで

Dim specialCharactersFound As New Collection 
Dim mtch As Object 

とを、代わりcounter = 0Next間のコードの使用

counter = 0 
Set specialCharactersFound = New Collection ' Initialize the collection for special chars 

For Each cell In Worksheets(1).Range("A1:A100") 
    strInput = Worksheets(1).Range(cell.Address).Value 
    Set mtch = RegExpo.Execute(strInput) ' Find the matches 
    For Each objMatch In mtch    ' Iterate throug the match collection 
     specialCharactersFound.Add (mtch(0).Value) ' Add the char found to the collection 
    Next 
    Worksheets(1).Range(cell.Address).Interior.ColorIndex = 20 
    counter = counter + 1 ' Increment the affected cell count 
Next 
関連する問題