【发布时间】:2018-11-11 16:09:21
【问题描述】:
我正在尝试根据 Excel 中的数据打开特定的 Word 模板(该部分正在运行)。然后,一旦打开模板,我就会尝试根据 Excel 文档中的标签进行查找并替换为同一列中的相应数据。当我运行宏时,它会打开模板并且只是旋转和旋转而不给我输出。代码如下:
` Sub New_Purification_SOP()
'
' New_Purification_SOP Macro
''Open an existing Word Document from Excel
Dim objWord As Object
Dim myValue As Variant
Dim PurCol As Variant
'open input box requesting line of the material to be made
myValue = InputBox("Select Row to create SOP")
Set objWord = CreateObject("Word.Application")
objWord.Visible = True
'Change the directory path and file name to the location
'of the document you want to open from Excel
If ActiveSheet.Cells(myValue, 10) = "Supe" And _
ActiveSheet.Cells(myValue, 12) = "IgG1" Then
objWord.Documents.Open "S:\generic filename"
With objWord
For PurCol = 3 To 13 'move through columns left to right
TagName = .Cells(10, PurCol).Value 'get tag name from row
TagValue = .Cells(myValue, PurCol).Value 'get tag name from row
With objWord.Content.Find
.Text = TagName
.Replacement.Text = TagValue
.Wrap = wdFindContinue
.Execute Replace:=wdReplaceAll 'Forward = True, Wrap = _
wdFindContinue
End With
Next PurCol
End With`
...
我对 VBA 很陌生,所以请尽可能多地批评。
【问题讨论】:
-
我假设
objWord是一个 Word 对象?你如何使用.Cells?如果你用F8单步执行你的代码,你能看到循环从哪里开始吗? -
首先从您的代码中删除
wdFindContinue。如果有的话,使用 wdFindStop 并且只使用一次(Execute命令看起来很奇怪 - 也应该注释掉那个断线)。 -
如果这没有帮助,请包括一个将运行的代码 sn-p,就目前而言。我们无法复制您拥有的内容,因为我们没有您的电子表格并且您没有包含代码的结尾 - 该过程不完整。
-
感谢大家的帮助。删除 wdFindContinue 是正确的。 BruceWayne 发现 .Cells 无法正常工作。
-
感谢您的确认 - 我已将其写为答案,因为在使用 Word 的查找/替换时这可能是一个令人讨厌的陷阱 :-)