合并VBA EXCEL中的单词文档(问题:颠倒顺序)

时间:2016-06-23 19:17:37

标签: excel wordpress vba

在EXCEL中,我使用VBA组合了一些word文档。我的工作流程是:

  1. 打开模板并删除所有现有文本(仅保留格式_
  2. 通过复制要合并的每个单词文档开始循环(我将从每个文件的第13行复制)
  3. 粘贴到合并文件
  4. 到目前为止,大多数步骤都很好,只是合并文件的顺序是反向的,这意味着组合文档的最后一页实际上是第一个打开的文档。有没有办法按正常顺序粘贴文本?谢谢!

    Set newDoc = objWord.Documents.Open(path to template)
    'clear template text in this template
    objWord.Selection.WholeStory
    objWord.Selection.Delete
    
    For i = 1 To NoOfFiles
            Set objDoc = objWord.Documents.Open(Folderpath to output files)
            ' goto line 13
            Set r = objDoc.Goto(what:=3, which:=wdGoToNext, Count:=13)
            r.End = objDoc.Range.End
            r.Copy
            newDoc.Content.InsertBreak Type:=wdSectionBreakNextPage
            newDoc.Range(newDoc.Content.Start, newDoc.Content.Start).Paste
    
        End If
    Next
    

1 个答案:

答案 0 :(得分:0)

此脚本会将所有Word文件合并为一个。

Sub MergeAllWordDocs1()
    Dim i As Long
    Dim MyName As String, MyPath As String
    Application.ScreenUpdating = False
    Documents.Add
    MyPath = "C:\Users\your_path_here\" ' <= change this as necessary
    MyName = Dir$(MyPath & "*.do*") ' not *.* if you just want doc files
    Do While MyName <> ""
        If InStr(MyName, "~") = 0 Then
            Selection.InsertFile _
    FileName:="""" & MyPath & MyName & """",
            ConfirmConversions:=False, Link:=False,
            Attachment:=False
    Selection.InsertBreak Type:=wdPageBreak
  End If
        MyName = Dir() ' gets the next doc file in the directory
    Loop
End Sub