2016-10-28 302 views
1

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

实施例:enter image description here

我想自动这作为代码。

谢谢你的时间。

+2

Regex - > http://stackoverflow.com/questions/22542834/how-to-use-regular-expressions-regex-in-microsoft-excel-both-in-cell-and-loops – DejaVuSansMono

+1

看来,旁边字母和数字,单元格也可以有'-',对吧? –

+0

它也可以没有VBA宏与条件形成公式http://stackoverflow.com/questions/29855647/check-if-cell-contains-non-alpha-characters-in-excel – Slai

回答

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

没有正则表达式:

这个宏流程列

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 

将只接受数字,大写和小写字母,和破折号。

+1

对你的答案downvotes困惑我,所以我+1,因为我没有看到任何问题。 Downvoters请给出任何暗示,为什么这个答案没有用。 – Slai

+0

@Slai Thee可能是某处的一个bug .............我将重新检查答案。 –

+0

我没有downvote你的答案,谢谢你的时间 – Deluq