我已经有了使用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
非常感谢提前
答案 0 :(得分:3)
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
这应该允许您重复使用代码而不重复它。