【发布时间】:2018-12-21 20:02:40
【问题描述】:
我正在尝试使用书签在现有 Word 文件模板中插入多个 Word 文件。
下面在现有 word 文件中搜索特定书签,并将另一个 word 文件的内容插入到现有 word 文件中。
除了Selection.InsertFile FileName:=BookmarkValue 行之外,其余代码工作正常。
这行代码在 Word VBA 中有效,但在 Excel VBA 中无效。
你能帮我弄清楚我哪里错了吗?
为了您的方便,我在下面提供了代码的简化版本。
Sub CreateWordDocuments3()
Dim LastRow As Long
Dim DocLoc, BookmarkName, BookmarkValue, FileName As String
Dim WordDoc, WordApp As Object
Dim WordContent As Word.Range
With Sheet3
'Open Word Template
On Error Resume Next 'If Word is already running
Set WordApp = GetObject("Word.Application")
If Err.Number <> 0 Then
'Launch a new instance of Word
Err.Clear
'On Error GoTo Error_Handler
Set WordApp = CreateObject("Word.Application")
WordApp.Visible = True 'Make the application visible to the user
End If
DocLoc = "C:\Users\DKC\Desktop\Basetemplate.docx"
Set WordDoc = WordApp.Documents.Open(FileName:=DocLoc, ReadOnly:=False) 'Open Template
BookmarkName = .Cells(4, 2).Value 'BookmarkName is IndustryAnlysis in the word file (DocLoc)
BookmarkValue = .Cells(4, 3).Value 'BookmarkValue is link to the word file to be inserted = "C:\Users\DKC\Desktop\Industry Analysis.docx"
WordDoc.Bookmarks(BookmarkName).Select
Selection.InsertFile FileName:=BookmarkValue ' Line code working in word VBA but not in excel VBA
FileName = ThisWorkbook.Path & "\" & "NewDoc" & ".docx"
WordDoc.SaveAs FileName
WordApp.Quit
End With
End Sub
【问题讨论】:
-
你试过把
WordDoc.Bookmarks(BookmarkName).InsertFile FileName:=BookmarkValue这两行合并吗? -
另外,您还有一个名为
FileName的变量,FileName也是InsertFile方法的参数 - 尝试重命名该变量,这样 VBA 就不会混淆您的意思。 -
感谢达伦的编辑。我需要重新发布问题吗?是的,我也尝试过重命名,但没有成功。
-
不,不需要转发。恐怕我无法提供太多帮助 - 还没有真正完成任何 Word 编码。
-
感谢您的宝贵时间。对此,我真的非常感激。 :)