I have a VBA script that I use to run across a word document to highlight any text that doesn't meet certain criteria. The problem is its too slow on large documents. This is the script:
Sub MarkManualFontFormatting()
On Error GoTo ErrorHandler
Dim objRange As Range
If Documents.Count > 0 Then
If vbOK = MsgBox("Please ensure this document is a copy and NOT the original/master document." & vbNewLine & vbNewLine & _
"Press CANCEL if you don't wish to continue.", vbExclamation + vbOKCancel, "Mark Manual Font Formatting - WARNING :") Then
'Disable screen updating to improve speed.
Application.ScreenUpdating = False
'Examine each word in the document and conditionally apply lavender shading.
For Each objRange In ActiveDocument.Range.Words
With objRange.Font
If .Name <> "Minion Pro" Then
.Shading.BackgroundPatternColor = wdColorLavender
ElseIf .Size <> 12.5 Then
.Shading.BackgroundPatternColor = wdColorLavender
ElseIf objRange.Font.Color = wdColorBlack Then
.Shading.BackgroundPatternColor = wdColorLavender
ElseIf objRange.Font.Color = -587137025 Then
.Shading.BackgroundPatternColor = wdColorLavender
End If
End With
Next objRange
MsgBox "Script has completed", vbOKOnly + vbInformation
End If
Else
MsgBox "Please open a document before using this command.", vbOKOnly + vbInformation
End If
ErrorHandler:
'Be sure to re-enable screen updating.
Word.Application.ScreenUpdating = True
Set objRange = Nothing
Select Case Err.Number
Case 0
Case Else
MsgBox Err.Description, vbExclamation + vbOKOnly, "Unexpected"
Error ""
End Select
End Sub
I have looked at instructions for optimising the code to run as quickly as possible and I think it is about as good as I can get it? I think the slowness is because it has to loop through every word in the document. I'm wondering if maybe I need to approach
it differently to speed it up? Most of the words in the document will end up not needing to be highlighted. Therefore I'm thinking maybe it would be faster to search for text that meet the above criteria (rather than not meet it) and then using selection.start
and .end markers to capture the range of any text outside the search results and then apply a highlight to these ranges??? I'm not sure if this would be faster or not, and not sure how I would do it??? Any thoughts?
Many thanks. HJ