0
votes

This is my first VBA attempt in Word. I want to Find multiple word matches and Replace All of them with the string I specify, preferably from an outside document. I have 1000 different words I want to replace with their 1000 different translations in a 200 page document. Now I'm stuck, because I can't get this function to work on my Word 2010 text. Is this code correct and how can I implement it?

Function R(StrFind As String, StrReplace As String)
  Application.ScreenUpdating = False
  With Selection.Find
    .ClearFormatting
    .Replacement.ClearFormatting
    .Text = StrFind
    .Replacement.Text = StrReplace
    .Forward = True
    .Wrap = wdFindContinue
    .Format = False
    .MatchCase = False
    .MatchWholeWord = True
    .MatchWildcards = False
    .MatchSoundsLike = False
    .MatchAllWordForms = False
    .Execute Replace:=wdReplaceAll
  End With
  MsgBox R("q", "a")
  MsgBox R("w", "a")
  MsgBox R("e", "a")
  MsgBox R("r", "a")
  MsgBox R("t", "a")
  MsgBox R("y", "a")
  ActiveDocument.UndoClear
  Application.ScreenUpdating = True
End Function
1
Why are you using... a function...?K.Dᴀᴠɪs
show the code you want to insert the shown one intoDisplayName
@DisplayName I have 200 page documents in English and I want to replace the most common English words with their translations in Bulgarian.Stray
@K.Dᴀᴠɪs I can make it with an if else as well. Is my function the problem for it not working as a macro? The replace all "q","w","e","r","t","y" with "a" is just an example.Stray
But why not a Sub?Foxfire And Burns And Burns

1 Answers

0
votes

You need to restructure your code to make it work. First, a method containing all the calls, and second a method executing the replace. Something like this:

Sub En2Bu
  R "q", "a"
  R "w", "a"
  R "e", "a"
  R "r", "a"
  R "t", "a"
  R "y", "a"
  ActiveDocument.UndoClear
  Application.ScreenUpdating = True
End Sub

Sub R(StrFind As String, StrReplace As String)
  Application.ScreenUpdating = False
  With Selection.Find ' Are you sure you want Selection here?
    .ClearFormatting
    .Replacement.ClearFormatting
    .Text = StrFind
    .Replacement.Text = StrReplace
    .Forward = True
    .Wrap = wdFindContinue
    .Format = False
    .MatchCase = False
    .MatchWholeWord = True
    .MatchWildcards = False
    .MatchSoundsLike = False
    .MatchAllWordForms = False
    .Execute Replace:=wdReplaceAll
  End With
End Sub

Selection.Find is perhaps a mistake? Do you want to do it only in the selected text?