识别特殊字符VBA

时间:2016-10-28 18:35:16

标签: regex vba excel-vba macros excel

我需要知道如何识别具有特定特征的单元格(例如:!,。=] \')该列只能包含数字(0-9),字母(az),作为大写字母(AZ)并将其标记为颜色。

实施例:enter image description here

我想自动将其作为代码。

感谢您的时间。

2 个答案:

答案 0 :(得分:4)

您可以使用正则表达式执行此任务。

这里有用的正则表达式构造是negated character class:您使用[^...]并在那里插入您不想匹配的范围。因此,要匹配ASCII字母,数字和连字符以外的字符,请使用[^a-zA-Z0-9-]

并像

一样使用它
Dim strPattern As String: strPattern = "[^a-z0-9-]"
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 :(得分:2)

没有正则表达式:

此宏处理列 B

Sub marine()
    Dim r As Range, rng As Range, s As String
    Dim i As Long, L As Long

    Set rng = Intersect(Range("B:B"), ActiveSheet.UsedRange)

    For Each r In rng
        If r.Value <> "" Then
            s = Replace(r.Text, "-", "")
            L = Len(s)
            For i = 1 To L
                If Not Mid(s, i, 1) Like "[0-9a-zA-Z]" Then
                    r.Interior.Color = vbYellow
                End If
            Next i
        End If
    Next r
End Sub

它只接受数字,大写和小写字母以及破折号。

相关问题