vba regEx不同列的多个模式

时间:2017-10-10 13:23:00

标签: excel-vba vba excel

我需要在两列中执行两个不同的验证。在“C”栏中,我需要检查特殊字符,在“D”栏中,我需要检查是否有数字。

无论如何,我可以在VBA中使用regEx实现这一目标吗?

感谢您的提前帮助

Dim strPattern As String: strPattern = "[^a-z]"
Dim regEx As Object
Set regEx = CreateObject("VBScript.RegExp")
regEx.Global = True
regEx.IgnoreCase = True
regEx.Pattern = strPattern

For Each cell In ActiveSheet.Range("C:C") ' 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

1 个答案:

答案 0 :(得分:0)

代码

使用您的代码,结果如下:

Dim strPattern As String
Dim regEx As Object
Dim ncellc As Long, ncelld As Long, i As Long
Dim rng As Range

Set regEx = CreateObject("VBScript.RegExp")
regEx.Global = True
regEx.IgnoreCase = True

ncellc = ActiveSheet.Cells(ActiveSheet.Rows.Count, "C").End(xlUp).Row
ncelld = ActiveSheet.Cells(ActiveSheet.Rows.Count, "D").End(xlUp).Row

For i = 1 To 2
    If i = 1 Then
        strPattern = "[^a-z]"
        Set rng = Range("C1:C" & ncellc)
    ElseIf i = 2 Then
        strPattern = "[^\d]"
        Set rng = Range("D1:D" & ncelld)
    End If
    regEx.Pattern = strPattern

    For Each cell In rng                     ' Define your own range here
        If strPattern <> "" And cell <> "" Then ' If the cell is not empty and there is pattern
            If regEx.test(cell.Value) Then   ' Check if there is a match
                cell.Interior.ColorIndex = 3 ' If yes, change the background color
            Else
                cell.Interior.ColorIndex = 4
            End If
        End If
    Next
Next i

正则表达式

使用简单的负匹配正则表达式代码。

[^a-z]拒绝字母和[^\d]拒绝数字