2016-10-28 297 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