Excel VBA – RegExp – “testing”操作起作用,但“执行”操作不起作用

请看下面的代码:

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 

出于某种原因,testing操作按预期工作,但执行操作不。

如果你认为它与for循环有关,我检查,而不是 – 执行操作不能按预期工作,即使只在一个单元格上的焦点。

我究竟做错了什么? 我对VBA一般和RegExp都不是很有经验。

提前致谢,

Kurkum

我build议将这两行添加到variables声明中:

 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