I'm new to vba, but have cobbled together some ideas from the forum for code to search a document for specific words and prompt the user to replace with a different word in case the first word was mistaken. For example, I write about statutes very often but sometimes type the word statue by mistake. Spell check obviously won't catch this, so I have a list of words and replacements that I often, but not always mistype.
I want to go through the document and find the uncommon word, like statue, then while I can see where the found text is on screen, I want to ask the user if he wants to replace this instance with statute instead. If so, replace it and continue the search. If not, continue searching for others until the end of the document.
Code:
Sub PromptReplace()
Dim Rng As Range, i As Long
Dim strFnd As String, strRpl As String
Dim fnd As String, rpl As String, choice As Integer
'find string
strFnd = "tot;tow;trail;contact;delivery;fist;form;latter;diffused;singed;sing;asset;tortuous;emotion;owning;statue;conversion"
'replace string in same order as strFnd
strRpl = "to;two;trial;contract;deliver;first;from;later;defused;signed;sign;assert;tortious;motion;owing;statute;conversation"
Selection.HomeKey Unit:=wdStory
For Each Rng In ActiveDocument.StoryRanges
Set Rng = ActiveDocument.Range
For i = 0 To UBound(Split(strFnd, ";"))
fnd = Split(strFnd, ";")(i)
rpl = Split(strRpl, ";")(i)
With Rng.Find
.ClearFormatting
.Text = fnd
.Replacement.ClearFormatting
.Forward = True
.Wrap = wdFindStop
.Execute
End With
While Rng.Find.Found
choice = MsgBox("Replace " + fnd + " with " + rpl + "?", _
vbYesNoCancel + vbDefaultButton1, "Replace")
If choice = vbYes Then
Rng.Text = rpl
Rng.Collapse wdCollapseEnd
ElseIf choice = vbCancel Then
GoTo endit
Else
Rng.Collapse wdCollapseEnd
End If
Rng.Find.Execute
Wend
Next i
Next Rng
endit:
Set Rng = Nothing
End Sub
This does most of what I want except I can't see the found text when the MsgBox pops up, so I can't tell the context in which I used the word. I'm also not sure that it is continue to search if I select No in response to the prompt. It also didn't find text in footnotes even though I was trying to loop through all storyRanges in the active document.
I would appreciate any comments about this code or possible suggestions for different ways to do this. Thanks.