【问题标题】:vba regEx multiple patterns for different columns不同列的vba regEx多种模式
【发布时间】:2018-03-21 22:19:04
【问题描述】:

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

有没有我可以在 VBA 中使用正则表达式来实现这一点?

提前感谢您的帮助

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

【问题讨论】:

  • 您可以使用WildCardsLike Operator
  • Is there anyway I can achieve this using regEx in VBA? - 是的。如需更多帮助,请阅读how to ask
  • Dim strPattern As String: strPattern = "[^az]" 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") ' 在这里定义自己的范围 If strPattern "" Then ' 如果单元格不为空 If regEx.Test(cell.Value) Then ' 检查是否有a match cell.Interior.ColorIndex = 6 ' 如果是,则更改背景颜色 End If End If Next
  • 这是我当前代码的外观,仅取自本网站。现在我需要在 D 列上申请以验证同一脚本验证中的数字。
  • @Rick 如果你使用负匹配[^A-Za-z0-9],它可以检测特殊字符,但是,它会检测`´​​~çÇàáé,你能指定特殊字符吗?或者一定是all of them

标签: excel vba


【解决方案1】:

代码

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

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]拒绝数字

【讨论】:

  • 非常感谢。它奏效了,我需要稍微修改一下这段代码以适应我的情况。如果我需要任何帮助,我会与您联系。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-03
  • 2021-09-07
  • 1970-01-01
相关资源
最近更新 更多