我发现了一个使用RegEx
来确定列中是否有特殊字符的代码。我今天才发现有关RegEx
的信息,并尝试编辑此代码,但遇到了3个问题:
"ActiveSheet"
,但我已经读到它可能会引起问题。我希望它仅检查在For Each行中尝试过"Consolidated."
的名为Worksheets.("Consolidated").Range
的工作表,但是它不接受。 Dim strPattern As String: strPattern = "[^a-z0-9-]"
Dim regEx As Object
Dim Cell As Range
Set regEx = CreateObject("VBScript.RegExp")
regEx.Global = True
regEx.IgnoreCase = True
regEx.Pattern = strPattern
For Each Cell In ActiveSheet.Range("A:Z") ' Define your own range here
If strPattern <> "" Then ' If the cell is not empty
If regEx.Test(Cell.Value) Then ' Check if there is a match
Cell.Interior.ColorIndex = 6 ' If yes, change the background color
End If
End If
Next
答案 0 :(得分:1)
我进行了更改。
Find
函数查找列。为此使用了cnum Worksheets("Consolidated")
而不使用.
将找到的列号传递到循环范围
Dim strPattern As String: strPattern = "[^a-z0-9-]"
Dim regEx As Object
Dim Cell As Range
Dim cnum As Integer
Set regEx = CreateObject("VBScript.RegExp")
regEx.Global = True
regEx.IgnoreCase = True
regEx.Pattern = strPattern
cnum = Worksheets("Consolidated").Range("A1:Z1").Find("First Name").Column 'column number to search in
For Each Cell In Worksheets("Consolidated").Range(Cells(2, cnum), Cells(1000, cnum))
If strPattern <> "" Then ' If the cell is not empty
If regEx.Test(Cell.Value) Then ' Check if there is a match
Cell.Interior.ColorIndex = 6 ' If yes, change the background color
End If
End If
Next