从Excel写入Word文档时出错

时间:2018-12-01 04:00:11

标签: excel vba outlook ms-word

该表在范围A15:D16中。单词文档包含一个现有表,信息将被传输到该表。到目前为止,它已在单元格A15 / A16中传输数据,但此后它说lineCount超出范围。我已经注释了代码中发生错误的位置。

Sub Export_Table_Data_Word()

    'Name of the existing Word document
    Const stWordDocument As String = "Report.docx"

    'Variables for the files we're using to make it easy to reference later
    Dim wdApp As Word.Application
    Dim wdDoc As Word.Document
    Dim wdCell As Word.Cell
    Dim wbBook As Workbook
    Dim wsSheet As Worksheet
    Dim lineCount As Long
    Dim vaData As Variant

    'Set the excel files / range where our data is
    Set wbBook = ThisWorkbook
    Set wsSheet = wbBook.Worksheets("Sheet1")
    vaData = wsSheet.Range("A15:D16").Value

    'Do the same for the word files
    Set wdApp = New Word.Application
    Set wdDoc = wdApp.Documents.Open(wbBook.Path & "\" & stWordDocument)

    lineCount = 1

    'Write the data from excel into the word document in a pre-existing table
    For Each wdCell In wdDoc.Tables(1).Columns(1).Cells
        wdCell.Range.Text = vaData(lineCount, 1) // ****problem occurs here
        lineCount = lineCount + 1
    Next wdCell

    'Save and close the Word doc.
    With wdDoc
        .Save
        .Close
    End With

    wdApp.Quit

    Set wdCell = Nothing
    Set wdDoc = Nothing
    Set wdApp = Nothing

    'Alert the user that the document has been updated succesfully
    MsgBox "The " & stWordDocument & "'s table has succcessfully " & vbNewLine & _
           "been updated!", vbInformation

End Sub

1 个答案:

答案 0 :(得分:-1)

    For lRows = 1 To 2
        For lCols = 1 To 4
            wdDoc.Tables(1).Cell(lRows, lCols).Range.Text = vaData(lRows, lCols)
        Next
    Next