除了在Google上寻找解决方案之外,我已经解决了这个问题几周了。
场景:我希望从特定的Excel单元格(范围“B2”)复制一串文本(ABC公司),并在Word中多次替换文本(Company_name)。考虑将此字符串存储在变量(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
代码的一些起源来自我拼凑在一起的其他材料,所以它们可能看起来不合适。如果我可能不小心解释我想要实现的目标,请向我提出问题。
答案 0 :(得分:0)
而不是:
sheet1.Range("B2").Copy
这样做:
Coy_name = sheet1.Range("B2").Value