合并Word文档

时间:2019-03-18 10:14:39

标签: excel vba ms-word word-vba

我正在尝试将6个文档(在文件夹中)粘贴/合并到新文档中,其中包含所有这些文档。 VBA代码应该从Excel模板运行,在该模板中创建所有文档,然后通过宏将其合并在一起。

但是,我得到了

  

运行时错误438:对象不支持此属性或方法

每次我尝试运行InsertFile行。我猜问题出在从Excel到Word VBA(?)

的过渡中

有什么想法或想法吗?

  Sub MergeALL()
       Dim objWord
       Dim objDoc
       Set objWord = CreateObject("Word.Application")
       Set objDoc = objWord.Documents.Add
       objWord.Visible = True

'opens a new word document
Documents.Add
Dir "\\rz_sixt\user\Home\Pictures" 'change to OutputFilePath ?
MyName = Dir("*.docx")
While MyName <> ""
 With Selection
 .InsertFile Filename:=MyName, ConfirmConversions:=False, Link:=False, Attachment:=False
 .InsertParagraphAfter
 .InsertBreak Type:=wdSectionBreakNextPage
 .Collapse Direction:=wdCollapseEnd
 End With
 MyName = Dir()
Wend
End Sub

1 个答案:

答案 0 :(得分:0)

当您通过Dir遍历所有找到的文档时,
InsertFile每个文件时,您都必须再次添加文件路径:

Sub MergeALL()
    Dim objWord As Object
    Dim objDoc As Object
    Dim myPath As String, myFile As String

    Set objWord = CreateObject("Word.Application")
    objWord.Visible = True

    Set objDoc = objWord.Documents.Add
    myPath = "\\rz_sixt\user\Home\Pictures\"
    myFile = Dir(myPath & "*.docx", vbNormal + vbReadOnly + vbHidden)
    While myFile <> ""
        With objDoc.Bookmarks("\StartOfDoc").Range
            .InsertFile Filename:=myPath & myFile, _
                ConfirmConversions:=False, Link:=False, Attachment:=False
            .InsertBreak Type:=2    ' wdSectionBreakNextPage = 2
        End With
        myFile = Dir()
    Wend
    objDoc.Characters(1).Delete
End Sub

如果为早期绑定添加对“ Microsoft Word x.x对象库”的引用,则可以使用wdCollapseEnd之类的ENUM值,否则使用其对应的值。