代码之家  ›  专栏  ›  技术社区  ›  Dori

从Excel文档在Word中自动创建表

  •  6
  • Dori  · 技术社区  · 16 年前

    我在Excel中有一组数据,如下所示(csv格式)

    heading1, heading2, heading3, index
    A , randomdata1, randomdata2, 1
    A , randomdata1, randomdata2, 2
    A , randomdata1, randomdata2, 3
    B , randomdata1, randomdata2, 4
    C , randomdata1, randomdata2, 5
    

    我希望能够自动构建一个Word文档,将这些数据(按标题1分组的信息)显示到单独的表中。所以Word文档应该是

    Table A
    heading1, heading2, heading3, index
    A , randomdata1, randomdata2, 1
    A , randomdata1, randomdata2, 2
    A , randomdata1, randomdata2, 3
    
    Table B 
    heading1, heading2, heading3, index
    B , randomdata1, randomdata2, 4
    
    Table C 
    heading1, heading2, heading3, index
    C , randomdata1, randomdata2, 5
    

    请有人帮我一下,这样可以节省20个小时的非常无聊的复制粘贴和格式化时间!

    谢谢你的帮助

    1 回复  |  直到 12 年前
        1
  •  9
  •   Doug Glancy    16 年前

    Dori

    希望这是及时的帮助。

    为此,您需要设置对Word的引用-在VBA编辑器中,选择“工具”>“引用”,并向下滚动到Microsoft Word,其中对于Excel'07为12.0,对于Excel'03为11.0等。此外,运行此操作时不应筛选工作表,尽管您不需要按标题1排序,但我假定您已经筛选了。

    代码假定列表以单元格A1中的标题开头。如果那不是真的,你应该这样做。它还假定您在D中的最后一列。您可以将该列调整到以“.copy”开头的末尾。

    Sub CopyExcelDataToWord()
    
    Dim wsSource As Excel.Worksheet
    Dim cell As Excel.Range
    Dim collUniqueHeadings As Collection
    Dim lngLastRow As Long
    Dim i As Long
    Dim appWord As Word.Application
    Dim docWordTarget As Word.Document
    
    Set wsSource = ThisWorkbook.Worksheets(1)
    With wsSource
        lngLastRow = .Range("A" & Rows.Count).End(xlUp).Row
        Set collUniqueHeadings = New Collection
        For Each cell In .Range("A2:A" & lngLastRow)
            On Error Resume Next
            collUniqueHeadings.Add Item:=cell.Value, Key:=cell.Value
            On Error GoTo 0
        Next cell
    End With
    Set appWord = CreateObject("Word.Application")
    With appWord
        .Visible = True
        Set docWordTarget = .Documents.Add
        .ActiveDocument.Select
    End With
    For i = 1 To collUniqueHeadings.Count
        With wsSource
            .Range("A1").AutoFilter Field:=1, Criteria1:=collUniqueHeadings(i)
            .Range("A1:D" & lngLastRow).Copy
        End With
        With appWord.Selection
            .PasteExcelTable linkedtoexcel:=False, wordformatting:=True, RTF:=False
            .TypeParagraph
        End With
    Next i
    
    For i = 1 To collUniqueHeadings.Count
        collUniqueHeadings.Remove 1
    Next i
    Set docWordTarget = Nothing
    Set appWord = Nothing
    
    End Sub