【发布时间】:2018-12-01 04:00:11
【问题描述】:
表格位于 A15:D16 范围内。 word文档包含一个预先存在的表格,信息将被传输到该表格中。到目前为止,它在单元格 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
【问题讨论】:
-
表格中的行数是否超过 2 行?