简体   繁体   English

如何使用vba将一个word文档的内容复制到另一个word文档的末尾?

[英]How do I copy the contents of one word document to the end of another using vba?

Goal for my project: 我的项目目标:

I want to be able to copy the contents of one document and append that selection to the end of another document. 我希望能够复制一个文档的内容并将该选择附加到另一个文档的末尾。

What it does ... (this is just background info so you understand why I am trying to do this): 它的作用 ...... (这只是背景信息,所以你理解我为什么要这样做):

I am trying to dynamically produce a document which quotes a variety of information regarding different parts and materials involved for a product. 我正在尝试动态生成一个文档,该文档引用了有关产品所涉及的不同部件和材料的各种信息。

The document itself has a consistent format which I have broken down and separated into two documents. 文档本身具有一致的格式,我将其分解为两个文档。 The first contains a bunch of data that needs to be entered manually, and is where I want to append all additional content. 第一个包含需要手动输入的一堆数据,并且是我想要附加所有其他内容的地方。 The second contains roughly a dozen custom fields which are updated from an excel spreadsheet in VBA. 第二个包含大约十几个自定义字段,这些字段是从VBA中的Excel电子表格更新的。 For a single part and as a single doc this works as I want it (my base case). 对于单个部分和单个文档,这可以按我的意愿工作(我的基本情况)。 However my issue is when there are multiple parts for a project. 但是我的问题是当项目有多个部分时。

The Problem: 问题:

For multiple parts I have to store information in an array which changes in size dynamically as each additional part is added. 对于多个部分,我必须将信息存储在一个数组中,该数组随着每个附加部分的添加而动态变化。 When someone has added all the necessary parts they can select a button called "Create Quote". 当有人添加了所有必要的部件后,他们可以选择一个名为“创建报价”的按钮。

Create quote runs a procedure which creates/opens separate copies of the two template documents mentioned above (saved on my computer). 创建报价运行一个过程,该过程创建/打开上述两个模板文档的单独副本(保存在我的计算机上)。 It then iterates through the array of parts and updates all the custom field in the 2nd document (no problems). 然后,它遍历部件数组并更新第二个文档中的所有自定义字段(没有问题)。 Now I just need the contents of the 2nd document appended to the end of the first which is my problem. 现在我只需要将第二个文档的内容添加到第一个文档的末尾,这是我的问题。

What I want: 我想要的是:

Ideally, my procedure will continue to iterate through every part in the array - updating custom fields, copy then paste the updated text, repeat... Until every part is included in the newly generated quote. 理想情况下,我的过程将继续遍历数组中的每个部分 - 更新自定义字段,复制然后粘贴更新的文本,重复...直到每个部分都包含在新生成的引用中。

What I Tried - this code can be found in my generate quote procedure 我尝试了什么 - 这个代码可以在我的生成报价程序中找到

I have tried many of the examples and suggestions provided by people who had similar question, but I don't know if its because I am operating from an excel doc, but many of their solution have not worked for me. 我已经尝试了许多有类似问题的人提供的示例和建议,但我不知道是不是因为我是在excel doc上运行,但他们的许多解决方案对我没有用。

This is my most recent attempt and occurs after each iteration of the for loop 这是我最近的尝试,发生在for循环的每次迭代之后

        wrdDoc2.Fields.Update 'Update all the fields in the format document
        wrdDoc2.Activate

        Selection.WholeStory ' I want to select the entire document
        Selection.Copy ' Copy the doc

        wrdDoc1.Activate ' Set focus to the target document

        Selection.EndKey wdStory ' I want the selection to be pasted to the end of the document
        Selection.PasteAndFormat wdPasteDefault

QUOTE PROCEDURE - I am only including a handful of the fields I am updating because its not necessary to show them all 引用程序 - 我只包括一些我正在更新的字段,因为没有必要全部显示它们

Private Sub quote_button_Click()

On Error GoTo RunError

    Dim wrdApp1, wrdApp2 As Word.Application
    Dim wrdDoc1, wrdDoc2 As Word.Document

    Set wrdApp1 = CreateObject("Word.Application")
    Set wrdApp2 = CreateObject("Word.Application")

    wrdApp1.Visible = True
    wrdApp2.Visible = True

    Set wrdDoc1 = wrdApp1.Documents.Add(Template:="C:\MWES\AQT_v1.1(start).docm", NewTemplate:=False, DocumentType:=0)
    Set wrdDoc2 = wrdApp2.Documents.Add(Template:="C:\MWES\AQT_v2.1(format).docm", NewTemplate:=False, DocumentType:=0)

    Dim propName As String

    For i = LBound(part_array, 1) To UBound(part_array, 1)
        For Each prop In wrdDoc2.CustomDocumentProperties

            propName = prop.name

            ' Looks for and sets the property name to custom values of select properties
            With wrdDoc2.CustomDocumentProperties(propName)
                Select Case propName
                    Case "EST_Quantity"
                        .value = part_array(i, 0) ' "QTY" ' Sheet1.Cells(1, 3) 'NA

                    Case "EST_Metal_Number"
                        .value = part_array(i, 1) ' "METAL_#" ' Sheet1.Cells(2, 3) 'NA"

                    Case "EST_Metal_Name"
                        .value = part_array(i, 2) ' "METAL_N" ' Sheet1.Cells(5, 2)

                End Select

            End With

        Next prop ' Iterates until all the custom properties are set

        wrdDoc2.Fields.Update 'Update all the fields in the format document
        wrdDoc2.Activate

        Selection.WholeStory ' I want to select the entire document
        Selection.Copy ' Copy the doc

        wrdDoc1.Activate ' Set focus to the target document

        Selection.EndKey wdStory ' I want the selection to be pasted to the end of the document
        Selection.PasteAndFormat wdPasteDefault

    Next i ' update the document for the next part

RunError: ' Reportd any errors that might occur in the system

    If Err.Number = 0 Then
        Debug.Print "IGNORE ERROR 0!"

    Else
        Dim strError As String
        strError = "ERROR: " & Err.Number & vbCrLf & Err.Description & vbCrLf & Erl
        MsgBox strError
        Debug.Print strError & " LINE: " & Erl

    End If

End Sub

I apologize this was so long winded. 我道歉这是如此漫长的啰嗦。 Let me know if there is anything confusing or you may want clarified. 如果有任何令人困惑的事情或者您可能需要澄清,请告诉我。 I think I included everything though. 我想我包括了一切。

I think you're close, so here are a couple of comments and an example. 我认为你很接近,所以这里有几条评论和一个例子。

First of all, you're opening two separate MS Word Application objects. 首先,您将打开两个单独的MS Word应用程序对象。 You only need one. 你只需要一个。 In fact, it's possible that the copy/paste is failing because you're trying to copy from one Word app to a document opened in the other. 实际上,复制/粘贴可能会失败,因为您尝试从一个Word应用程序复制到另一个Word应用程序中打开的文档。 (Trust me, I've seen weird things like this.) My example below shows how to do this by only opening a single application instance. (相信我,我见过这样奇怪的事情。)我的下面的例子显示了如何通过只打开一个应用程序实例来做到这一点。

Dim mswApp As Word.Application
Set mswApp = AttachToMSWordApplication()   'more on this function below...

Dim doc1 As Word.Document
Dim doc2 As Word.Document
Set doc1 = mswApp.Documents.Open("C:\Temp\combined.docx")
Set doc2 = mswApp.Documents.Open("C:\Temp\control.docx")

While I don't often write code for Word, I've found that there are so many different ways to get at the same content using different objects or properties. 虽然我不经常为Word编写代码,但我发现有很多不同的方法可以使用不同的对象或属性来获取相同的内容。 This is always a source of confusion. 这始终是混乱的根源。

Based on this answer , which has worked well for me in the past, I then set up the source and destination ranges to perform the "copy": 基于这个过去对我有用的答案 ,然后我设置源和目标范围来执行“复制”:

Dim destination As Word.Range
Dim source As Word.Range
Set source = doc1.Content
Set destination = doc2.Content
destination.Collapse Direction:=Word.wdCollapseEnd
destination.FormattedText = source

Here is the whole module for reference: 以下是整个模块供参考:

Option Explicit

Sub AddDocs()
    Dim wordWasRunning As Boolean
    wordWasRunning = IsMSWordRunning()

    Dim mswApp As Word.Application
    Set mswApp = AttachToMSWordApplication()

    Dim doc1 As Word.Document
    Dim doc2 As Word.Document
    Set doc1 = mswApp.Documents.Open("C:\Temp\combined.docx")
    Set doc2 = mswApp.Documents.Open("C:\Temp\control.docx")

    Dim destination As Word.Range
    Dim source As Word.Range
    Set source = doc1.Content
    Set destination = doc2.Content
    destination.Collapse Direction:=Word.wdCollapseEnd
    destination.FormattedText = source

    doc2.Close SaveChanges:=True
    doc1.Close

    If Not wordWasRunning Then
        mswApp.Quit
    End If
End Sub

Here's the promised note on a couple functions I use in the sample. 这是我在样本中使用的几个函数的承诺说明。 I've built up a set of library functions, several of which help me access other Office applications. 我已经构建了一组库函数,其中一些函数可以帮助我访问其他Office应用程序。 I save these modules as .bas files (by using the Export function in the VBA Editor) and import them as needed. 我将这些模块保存为.bas文件(通过使用VBA编辑器中的导出功能)并根据需要导入它们。 So if you'd like to use it, just save the code below in using a plain text editor (NOT in the VBA Editor!), then import that file into your project. 因此,如果您想使用它,只需使用纯文本编辑器(不在VBA编辑器中)保存下面的代码,然后将该文件导入到项目中。

Suggested filename is Lib_MSWordSupport.bas : 建议的文件名是Lib_MSWordSupport.bas

Attribute VB_Name = "Lib_MSWordSupport"
Attribute VB_Description = "Variety of support functions operating on MS Word"
Option Explicit

Public Function IsMSWordRunning() As Boolean
Attribute IsMSWordRunning.VB_Description = "quick check to see if an instance of MS Word is running"
    '--- quick check to see if an instance of MS Word is running
    Dim msApp As Object
    On Error Resume Next
    Set msApp = GetObject(, "Word.Application")
    If Err > 0 Then
        '--- not running
        IsMSWordRunning = False
    Else
        '--- running
        IsMSWordRunning = True
    End If
End Function

Public Function AttachToMSWordApplication() As Word.Application
Attribute AttachToMSWordApplication.VB_Description = "finds an existing and running instance of MS Word, or starts the application if one is not already running"
    '--- finds an existing and running instance of MS Word, or starts
    '    the application if one is not already running
    Dim msApp As Word.Application
    On Error Resume Next
    Set msApp = GetObject(, "Word.Application")
    If Err > 0 Then
        '--- we have to start one
        '    an exception will be raised if the application is not installed
        Set msApp = CreateObject("Word.Application")
    End If
    Set AttachToMSWordApplication = msApp
End Function

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从Xcel Vba中从一个Word文档中选择一系列文本,然后复制到另一个Word文档中 - from Xcel Vba select a range of text from one Word document and copy into another Word document 如何使用 VBA 将遵循特定字符串的动态数据范围从一张纸复制到另一张纸? - How do I copy a dynamic range of data that follows a specific string from one sheet to another using VBA? 在Word文档的全部内容上使用VBA Regex - Using VBA Regex on the entire contents of a word document VBA - 替换为在特定单元格中查找一个词有效,我如何找到一个词或另一个词? - VBA - Replace with find one word in a specific cell works, how do I find one word or another? VBA从嵌入式Word文档复制内容并保留格式 - VBA to Copy Contents from Embedded Word document and retain formatting 使用vba从xls文档复制到word - copy from xls document into word using vba 如何使用 VBA 在多列的文本末尾自动添加单词? - How do I auto add word to end of text in multiple columns using VBA? VBA:在Excel中如何将Word文档另存为PDF? - VBA: Within Excel how do I save a word document as a PDF? 使用VBA将活动的Word文档复制并粘贴到活动的Excel文档中 - Copy and Paste active Word document to active Excel document using VBA 如何使用Excel VBA删除word文档中的特定页面? - How do delete an specific page in a word document using Excel VBA?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM