Log in

View Full Version : replace words one by one



hiaim
08-15-2010, 02:41 PM
Hi,

if a word repeated several times in a word document following macro should ask to change before every occurrence/word. suppose word "facet" has to replace with "subject area" and "facet" is repeated 3 times in a document. it should ask to change at every word. i tried wdReplaceOne as well but it is not working ... any solution , any other way to acheive this ???


Dim a As Integer, myRange As Range
mySearch = InputBox("Enter string to search for:", "Searchstring", "")
myReplace = InputBox("Enter string to replace " & mySearch & " with:", "Replacestring", "")

Selection.HomeKey Unit:=wdStory
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
With Selection.Find
.Text = mySearch
.Replacement.Text = myReplace
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = True
.MatchWholeWord = True
.MatchByte = False
.CorrectHangulEndings = True
.MatchAllWordForms = False
.MatchSoundsLike = False
.MatchWildcards = False
.MatchFuzzy = False
End With
' Selection.Find.Execute
Do While Selection.Find.Found = True

' If Selection.Find.Found = True Then
a = MsgBox("Do you want to change?", vbYesNo, "Confirmation")

If a = 6 Then
Selection.Find.Execute Replace:=wdReplaceOne
Selection.EndKey Unit:=wdStory
End If
Selection.Find.Execute
'End If
Loop

Thanks

HiAim

fumei
08-15-2010, 05:49 PM
Sub AskMe()
Dim r As Range
Dim MySearchWord As String
Dim MyrReplaceWord As String

Set r = ActiveDocument.Range
MySearchWord = InputBox("Enter string to search for:")
MyrReplaceWord = InputBox("and replace with what????")
With r.Find
Do While .Execute(FindText:=MySearchWord, Forward:=True) = True
r.Select
If MsgBox("Replace this instance?", vbYesNo) = vbYes Then
r.Text = myReplaceWord
r.Collapse 0
End If
Loop
End With
End Sub
For every found instance of MySearchWord, the code asks "Replace this instance?" If yes is clicked, the found instance is replaced. if No clicked, it continues on to the next found instance.

Normally I would not use Select, but in this case I imagine you want to beable to SEE which instance so you canmake your choice (Yes or No)

hiaim
08-16-2010, 12:03 AM
Thanks gerry, it really helped me a lot ...

HiAim