Получение ошибки записи из Excel в документ Word - PullRequest
0 голосов
/ 01 декабря 2018

Таблица находится в диапазоне 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 голосов
/ 01 декабря 2018
    For lRows = 1 To 2
        For lCols = 1 To 4
            wdDoc.Tables(1).Cell(lRows, lCols).Range.Text = vaData(lRows, lCols)
        Next
    Next
...