除了在 Google 上寻找解决方案外,我已经解决了这个问题几个星期。
场景:我正在寻找从特定 Excel 单元格(范围“B2”)复制文本字符串(ABC 公司)并在 Word 中多次替换文本(公司名称)。考虑将此字符串存储在变量 (Coy_name) 中并运行“全部替换”指令。代码如下:
Sub CopyDataToWord()
Dim appWd As Word.Application
Dim wdFind As Object
Dim docWD As Word.Document
Dim CoyName As String
Set appWd = CreateObject("Word.Application")
appWd.Visible = True
Set docWD = appWd.Documents.Open("D:\Dropbox\ClassSheet.docx")
sheet1.Range("B2").Copy
'Some code which will input the string from "B2" into variable Coy_name
appWd.Selection.Find.ClearFormatting
appWd.Selection.Find.Replacement.ClearFormatting
With wdFind
.Text = "Company_name"
.Replacement.Text = Coy_name
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchByte = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
appWd.Selection.Find.Execute Replace:=wdReplaceAll
Set appWd = Nothing
Set docWD = Nothing
Set appXL = Nothing
Set wbXL = Nothing
End Sub
代码的一些来源来自我拼凑的其他材料,因此它们可能看起来不合适。如果我在解释我想要达到的目标时可能不小心,请向我提问。