我在MS Word中创建了一个查找和替换宏,用B替换了单词A.好的,但现在我有50个需要替换的单词。这意味着我将不得不为每个单词创建一个新条目,这将永远。再加上几个星期后,我将不得不添加更多要替换的单词。
有没有办法通过excel链接单词列表,比如说第1列中的单词是否需要用第2列中的匹配单词替换?
这是我到目前为止所拥有的。
Sub Macro5()
'
' Macro5 Macro
'
'
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
With Selection.Find
.Text = "apples"
.Replacement.Text = "all the apples"
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Selection.Find.Execute Replace:=wdReplaceAll
Selection.Find.Execute
End Sub
答案 0 :(得分:2)
答案 1 :(得分:2)
这样的事情应该让你开始。将Excel绑定到Word,打开包含列表的文件,然后遍历列表,按顺序调用宏(修改为接受两个字符串参数findText
和replaceText
)。
Sub Main()
Dim xl as Object 'Excel.Application
Dim wb as Object 'Excel.Workbook
Dim ws as Object 'Excel.Worksheet
Dim rng as Object 'Excel.Range
Dim cl as Object 'Excel.Range
Set xl = CreateObject("Excel.Application")
Set wb = xl.Workbooks.Open("c:\folder\file.xlsx") '## Modify as needed
Set ws = wb.Sheets(1) '##Modify as needed
Set rng = ws.Range("A1", ws.Range("A1").End(xlDown))
For each cl in rng
Call Macro5(cl.Value, cl.offset(0,1).Value)
Next
End Sub
您可以自行确认Macro5
的内容在上述循环中按预期工作。
Sub Macro5(findText$, replaceText$)
'
' Macro5 Macro
'
'
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
With Selection.Find
.Text = findText
.Replacement.Text = replaceText
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Selection.Find.Execute Replace:=wdReplaceAll
Selection.Find.Execute
End Sub