首页 > 解决方案 > 将多个word文档复制到一个新的word文档中

问题描述

我是 VBA 新手,想寻求帮助。

我在 B3:B40 范围内的 excel 中有一个 word 文档列表。我想复制列表中的文档并粘贴到新文档而不更改页面格式。

我已经尝试过下面的代码,它给了我“运行时错误 13”。任何人都可以帮助解决这种情况吗?提前感谢您的帮助。

Application.ScreenUpdating=false

set objword = createobject("Word.Application")
set objdoc = objword.Documents.Add
objword.visible = true

set objselection = objword.Selection
Folderpath = "C:\desktop"  'where I save the word document that would be combined

set objtempword = createobject("Word.Application")
set tempdoc = objword.documents.open (Folderpath & "\" & Sheet1.Range ("B3:B40")
set objtempselection = objtempword.selection
tempdoc.range.select
tempdoc.range.copy
objselection.typeparagraph
objselection.paste
tempdoc.close

 

标签: excelvbacopy-pasteword

解决方案


我认为这对你有用。缺少的是为每个文件(范围内的单元格)工作的循环。

Option Explicit

Sub JoinDocs()
    Application.ScreenUpdating = False
    Dim objword As Object, objdoc As Object, objselection   As Object
    Set objword = CreateObject("Word.Application")
    Set objdoc = objword.Documents.Add
    objword.Visible = True
    Dim Folderpath  As String
    Set objselection = objword.Selection
    Folderpath = "C:\desktop\"  'where I save the word document that would be combined
    Dim vDoc As Variant
    Dim objtempword As Object, tempdoc As Object, objtempselection As Object
    Set objtempword = CreateObject("Word.Application")
    For Each vDoc In Sheet1.Range("B3:B40").Value
        Set tempdoc = objword.Documents.Open(Folderpath & vDoc)
        Set objtempselection = objtempword.Selection
        tempdoc.Range.Select
        tempdoc.Range.Copy
        objselection.TypeParagraph
        objselection.Paste
        tempdoc.Close
    Next vDoc
End Sub

推荐阅读