2016-08-24 105 views
1

我已經有了使用VBA宏在Microsoft Word中進行搜索和替換的代碼,但此刻,我的代碼正在複製和粘貼多次相同的函數。搜索並替換多個詞

我希望做的是有一個需要更換的話的詞典,所以例如:

old_word:new_word

然後,我必須通過VBA腳本中循環,並進行必要的文檔中的更改。

我現在的代碼是,並重復每個新的單詞對。

Sub change_words() 

    With Selection.Find 
     .Text = "optimize" 
     .Replacement.Text = "optimise" 
     .Forward = True 
     .Wrap = wdFindContinue 
     .MatchWholeWord = True 
    End With 

    Selection.Find.Execute Replace:=wdReplaceAll 

    With Selection.Find 
     .Text = "utilized" 
     .Replacement.Text = "utilised" 
     .Forward = True 
     .Wrap = wdFindContinue 
     .MatchWholeWord = True 
    End With 

    Selection.Find.Execute Replace:=wdReplaceAll 

End Sub 

提前感謝

回答

1
Sub change_words(ByVal findWord, byVal replaceWord) 

    With Selection.Find 
     .Text = findWord 
     .Replacement.Text = replaceWord 
     .Forward = True 
     .Wrap = wdFindContinue 
     .MatchWholeWord = True 
    End With 
    Selection.Find.Execute Replace:=wdReplaceAll 
End Sub 

如果你改變你的函數接受參數如圖所示,你可以把它在一個循環,(例如)在你想要像這樣的值傳遞:

Dim myDict : Set myDict = CreateObject("Scripting.Dictionary") 
myDict("optimize") = "optimise" 
myDict("utilized") = "utilised" 
For myLoop = 0 to myDict.Count - 1 
    change_words myDict.Keys()(myLoop), myDict.Items()(myLoop) 
Next 

這應該允許您重複使用代碼而不重複它。