PDA

View Full Version : Best Find/Replace



jo15765
07-01-2014, 12:29 PM
I recorde a macro and this is the syntax it gave me...I know often the macro recorder will give you overly cumbersome code. Is there a way to condense/shorten this or is this truly what is needed? This is what the macro recorder gave me -- also I am going to be running it in conjunction with this code http://www.vbaexpress.com/kb/getarticle.php?kb_id=13 Thank you @Steiner but will be searching for 4 different variations. I.E. the example shows ID but it could be eID, or empID or employeeID. Thanks in advance!

With Selection.Find
.Text = "ID"
.Replacement.Text = "Employee ID"
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Selection.Find.Execute Replace:=wdReplaceAll

macropod
07-01-2014, 04:40 PM
The Find/replace code recorded by the macro recorder is actually one of the more efficient recorder products, but you've omitted the important first two lines! For what you've indicated, you could use either of:

Sub Demo1()
Application.ScreenUpdating = False
With ActiveDocument.Range.Find
.ClearFormatting
.Replacement.ClearFormatting
.Forward = True
.MatchCase = False
.MatchWholeWord = True
.MatchWildcards = False
.Wrap = wdFindContinue
.Replacement.Text = "Employee ID"
.Text = "ID"
.Execute Replace:=wdReplaceAll
.Text = "eID"
.Execute Replace:=wdReplaceAll
.Text = "empID"
.Execute Replace:=wdReplaceAll
.Text = "employeeID"
.Execute Replace:=wdReplaceAll
End With
Application.ScreenUpdating = True
End Sub
or

Sub Demo2()
Application.ScreenUpdating = False
Dim StrFnd(), i As Long
StrFnd() = Array("ID", "eID", "empID", "employeeID")
With ActiveDocument.Range.Find
.ClearFormatting
.Replacement.ClearFormatting
.Forward = True
.MatchCase = False
.MatchWholeWord = True
.MatchWildcards = False
.Wrap = wdFindContinue
.Replacement.Text = "Employee ID"
For i = 0 To UBound(StrFnd)
.Text = StrFnd(i)
.Execute Replace:=wdReplaceAll
Next
End With
Application.ScreenUpdating = True
End Sub