Identify Special Characters

17,641

Solution 1

You can use a regex for this task.

A useful regex construct here is a negated character class: you use [^...] and insert the ranges you do not want to match in there. So, to match a char other than ASCII letters, digits, and a hyphen, use [^a-zA-Z0-9-].

And use it like

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

Solution 2

Without regex:

This macro processes column 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

It will accept only numerals, upper and lower case letters, and the dash.

Share:
17,641

Related videos on Youtube

Deluq
Author by

Deluq

Updated on September 16, 2022

Comments

  • Deluq
    Deluq over 1 year

    I need to identify cells that have certain special characters (example: !,.=]\') and mark them with a color.

    The column can only contain numbers (0-9), letters (a-z), as caps (A-Z) and hyphen (-).

    Example:enter image description here

  • Slai
    Slai over 7 years
    The downvotes on your answers confuse me so I +1 as I don't see any issue. Downvoters please give any hint as to why this answer not useful.
  • Gary's Student
    Gary's Student over 7 years
    @Slai Thee may be a bug in there somewhere.............I will re-examine the answer.
  • Deluq
    Deluq over 7 years
    I did not downvote your answer, thanks for your time
  • Gary's Student
    Gary's Student over 7 years
    @Deluq I usually get downvotes if I post code with no explanation....thanks for the feedback!
  • Deluq
    Deluq over 7 years
    Yeah, actually I liked your answer without regex
  • Vinoth Narayan
    Vinoth Narayan almost 6 years
    The above code works fine.. I need the special characters count
  • Wiktor Stribiżew
    Wiktor Stribiżew almost 6 years
    @VinothNarayan Is it a new question? Actually, it is too easy: instead of the whole For Each block, just use Set ms = regEx.Execute(cell.Value) and then use ms.Count.