VBA Word - Highlight all non-basic latin characters

410 views Asked by At

I'm trying to write a code that will highlight all non basic latin characters in a Word document (e.g. all characters that are non-alphanumeric, as well as some characters like ".", "(", ")", "?", "/", etc.)

This code works but takes way too long for what i'm trying to achieve. It works by highlighting the whole document then removing the highlight from "good" characters found in the array leaving the non-basic latin characters highlighted.

Sub HighlightNonStandardCharacters()

  Application.ScreenUpdating = False

Dim MyRange As Range
Dim i As Long
Dim NormalCharacters

NormalCharacters = Array(" ", "!", Chr(34), "#", "$", "%", "&", "'", "(", ")", "*", "+", ",", "-", ".", "/", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", ":", ";", "<", "=", ">", "?", "@", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "[", "\", "]", "^", "_", "`", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "{", "|", "}", "~", Chr(13), "¶")

' highlights all document text 
ActiveDocument.Range.HighlightColorIndex = wdTurquoise

For i = 0 To UBound(NormalCharacters)
Set MyRange = ActiveDocument.Range
With MyRange.Find
.Text = NormalCharacters(i)
.Format = True
.MatchCase = True
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False

Do While .Execute(Forward:=True) = True
' removes highlighting from the “standard” characters leaving “non-standard” characters highlighted 
MyRange.HighlightColorIndex = wdAuto
Loop
End With
Next
  Application.ScreenUpdating = True

End Sub

I was wondering if there is a faster way to highlight all characters not in an array or another way to achieve the goal.

Any ideas would be appreciated.

1

There are 1 answers

0
BiblioPhillip On

Thanks KazimierzJawor

That's exactly what i needed. So much faster and simpler. I hadn't realised quite how powerful using the wildcards in a find search could be.

This is what i came up with:

Sub HighlightNonBasicLatinCharacters()
Options.DefaultHighlightColorIndex = wdTurquoise
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
Selection.Find.Replacement.Highlight = True
    With Selection.Find
    .Text = "[! -~¶]"
    .Replacement.Text = "^&"
    .Forward = True
    .Wrap = wdFindContinue
    .Format = True
    .MatchCase = False
    .MatchWholeWord = False
    .MatchAllWordForms = False
    .MatchSoundsLike = False
    .MatchWildcards = True
End With
Selection.Find.Execute Replace:=wdReplaceAll
End Sub