1
您好,我正在尝试使用此代码将数据从excel导出到预先存在的单词表中。但是,一旦代码到达wdDoc.Tables中的每个wdCell循环,运行时错误'91'对象变量或With块变量未设置出现。有没有更好的方法可以让我的代码将数据传输到7列?将数据从excel传输到预先存在的Word表格?
Sub ExportDataWordTable()
Const stWordDocument As String = "C:\Users\jfournier\Desktop\VBA Macro Files\TESTQUOTE.docm"
Dim wdApp As Word.Application
Dim wdDoc As Word.Document
Dim wdCell As Word.Cell
Dim i As Long
Dim j As Long
Dim wbBook As Workbook
Dim wsSheet As Worksheet
Dim vaData As Variant
Set wbBook = ThisWorkbook
Set wsSheet = wbBook.Worksheets("Sheet2")
ReDim vaData(1 To 10, 1 To 5)
With wsSheet
vaData = .Range("B3:H20")
End With
'Here we instantiate the new object.
Set wdApp = New Word.Application
'Here the target document resides in the same folder as the workbook.
Set wdDoc = wdApp.Documents.Open(wbBook.Path & "\" & stWordDocument)
'Import data to the first table and in the first column of a table in Microsoft Word.
For j = 1 To 5
i = 0
For Each wdCell In wdDoc.Tables(2).Columns(j).Cells
i = i + 1
wdCell.Range.Text = vaData(i, j)
Next wdCell
Next j
'Save and close the document.
With wdDoc
.Save
.Close
End With
'Close the hidden instance of Microsoft Word.
wdApp.Quit
'Release the external variables from the memory
Set wdDoc = Nothing
Set wdApp = Nothing
MsgBox "The data has been transferred to Test.doc", vbInformation
End Sub
Skkakkar,我很欣赏你的布局。我能够将数据传输到TESTQUOTE单词文档。如果每次运行报价时,我的Excel表中的范围都有所不同,那该怎么办?例如,它可以从18个项目到5个项目(总是7个)。有没有办法可以运行循环将数据导出到word文档中,而不管我有多少行? –
@Rey泰诺我不认为会有任何问题。您可以随时写出更少的可变数量的行。如果您可以通过在下面的三角形下面的答案左侧打勾来接受我的答案,因为它可以广泛地满足您的要求,我将不胜感激。我同时也验证了它正确写入5行没有任何问题 – skkakkar
我的歉意。接受答案。感谢您的帮助。 –