通过Excel 2010 VBA将表添加到Word文档

时间:2017-05-19 14:05:56

标签: excel vba excel-vba word-vba

我目前正在尝试比较两个Excel文档之间的数字,并将测试结果写入Word文档中的表。我已经能够建立与文档的连接,但我无法实际添加表格。

这就是我所拥有的:

{{1}}

我还尝试过将页面拆分为3列,但是我无法让程序在我想要的时候实际切换列(我尝试使用InsertBreak(wdColumnBreak))。因此,出于某种原因,添加列有效,但表不能

2 个答案:

答案 0 :(得分:0)

Tables.Add的问题在于你在错误的对象上调用它,加上它是word文档的方法,因此需要一个"字范围"无论那是什么。这是一段有效的代码,但它正在复制并粘贴表格:

Sub aaa()
    Dim wordObj As New Word.Application
    Dim outFile As Word.Document
    Dim s As Worksheet
    Dim r As Range

    wordObj.Visible = True
    Set outFile = wordObj.Documents.Add
    outFile.Activate

    Debug.Print "Here!"

    Set s = ActiveWorkbook.Sheets("Sheet1")
    Call s.Range("E4:J10").Copy
    ' Call outFile.Tables.Add(wordObj.ActiveDocument.Range(0, 0), NumRows:=3, NumColumns:=3)
    Call wordObj.ActiveDocument.Range(0, 0).Paste
End Sub

答案 1 :(得分:0)

您的代码缺乏精确度。您应该尝试更有条理地构建它,例如,首先创建Word应用程序的实例。然后让该应用程序创建一个文档。然后将表放入该文档。然后在该表中查找单元格。并立即向该单元格添加文本。

相比之下,您创建Word应用程序,不创建任何文档,向不存在的文档添加表,以及 - 可能是绝望 - 然后尝试向应用程序添加文本。 Word应用程序没有选择(您的wordObj.Selection),只有文档。

以下代码可以满足您的需求。我写这篇文章是因为你易于理解。不要以为它是“婴儿语言”,因为它不是。它只是不偷工减料。你可以学习如何在你更熟练之后偷工减料 - 如果你还想要的话。请记住,削减的角落越多,代码的稳定性就越低。

Sub WriteToWordTable()

    ' declarations for the Excel application:
    Dim Ws As Worksheet

    ' declarations for the Word application:
    Dim wordObj As Word.Application
    Dim outFile As Word.Document
    Dim outTable As Word.Table
    Dim wdRng As Word.Range

    Set Ws = ActiveSheet
    Ws.Cells(2, "A").value = "Test1"

    On Error Resume Next
    Set wordObj = GetObject(, "Word.Application")

    If wordObj Is Nothing Then
        Set wordObj = CreateObject("Word.Application")
    End If

    Set outFile = wordObj.Documents.Add
    With outFile
        Set wdRng = .Range(0, 0)
        Set outTable = .Tables.Add(Range:=wdRng, _
                                   NumRows:=1, NumColumns:=3)
    End With

    With outTable
        .Cell(1, 1).Range.Text = Ws.Cells(2, "A").value
        .Rows.Add
        .Cell(2, 1).Range.Text = "Test2"
    End With

    With wordObj.ActiveWindow
        .Visible = True
        .Activate
    End With

'    outFile.Close
'    wordObj.Quit
End Sub

顺便说一句,您无需随时显示Word文档。您可以安静地关闭Word应用程序并继续在Excel中工作。但是,出于此目的,您需要在关闭它之前保存outFile,然后关闭Word。