2

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

Community
  • 1
  • 1
Deluq
  • 211
  • 1
  • 6
  • 22

2 Answers2

5

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
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
4

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.

Gary's Student
  • 95,722
  • 10
  • 59
  • 99