简体   繁体   English

根据不同列的 ID 将单元格范围复制到 Word 文档

[英]Copy Range of Cells to a Word Document based on IDs from a different column

So we have this table we are using at the office.所以我们有这张在办公室使用的桌子。 I changed the Column Name and Content for confidentiality purposes.出于保密目的,我更改了列名称和内容。

在此处输入图片说明

We're trying create a Word Document for each ID consisting of all the Name's and Surnames for that ID only from our Excel file.我们正在尝试为每个 ID 创建一个 Word 文档,该文档仅从我们的 Excel 文件中包含该 ID 的所有姓名和姓氏。

ie A new Word Document is created for ID1.即为 ID1 创建一个新的 Word 文档。 The contents are all the Names and Surnames only for that ID1 excluding the Column Name.内容是仅针对该 ID1 的所有 Names 和 Surnames,不包括 Column Name。 Another Word Document will be created for the next ID available until all IDs have their own document,将为下一个可用的 ID 创建另一个 Word 文档,直到所有 ID 都有自己的文档,

So far this is what I got:到目前为止,这是我得到的:

Sub test()

Dim copyRng As Range
Dim lastrow As Long
lastrow = Cells(Rows.Count, "A").End(xlUp).Row

Set copyRng = Range("B2:C" & lastrow)

Range("B2:C" & copyRng.Rows.Count).Select
Selection.Copy
'Declare Word Variables
    Dim WrdApp As Word.Application
    Dim WrdDoc As Word.Document
'Create a new instance of Word
    Set WrdApp = New Word.Application
        WrdApp.Visible = True
        WrdApp.Activate
'Create a new Document in the Word Application
    Set WrdDoc = WrdApp.Documents.Add
        WrdDoc.Activate
        WrdDoc.Range(WrdDoc.Characters.Count - 1).Paste
End Sub

I can't seem to copy only the rows for a specific ID.我似乎不能只复制特定 ID 的行。 Can anyone suggest a better solution copy only the cells based on the IDs?任何人都可以提出更好的解决方案,仅根据 ID 复制单元格吗?

I simplified my problem in the meantime.同时我简化了我的问题。

First I select the cells I want to be copied over to a Word Document.首先,我选择要复制到 Word 文档的单元格。

Then I run this code:然后我运行这个代码:

Selection.Copy
'Declare Word Variables
    Dim WrdApp As Word.Application
    Dim WrdDoc As Word.Document
'Create a new instance of Word
    Set WrdApp = New Word.Application
        WrdApp.Visible = True
        WrdApp.Activate
'Create a new Document in the Word Application
    Set WrdDoc = WrdApp.Documents.Add
        WrdDoc.Activate
        With WrdDoc.Range(WrdDoc.Characters.Count - 1).Characters.Last
        .PasteExcelTable False, True False
             With .Tables(1)
                  .AutoFitBehavior wdAutoFitWindow
             End With
                  .InsertAfter Chr(1)
        End With

This way, I just have to highlight the cells I want to be copied over to Word and Run the Macro.这样,我只需要突出显示要复制到 Word 的单元格并运行宏。 The Macro will create a new Word Document for me.宏将为我创建一个新的 Word 文档。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM