我创建了下面的简单代码,将表格从word文档导出到excel文件。我希望将这个概念应用于更大的项目。代码在初始时间运行正常,但每隔一段时间运行时错误1004。调试取消后再次运行正常。任何帮助将不胜感激。
错误显示对象'_Global失败的方法'单元'
Sub tableexport()
Dim oExcel As Excel.Application
Dim Word As Document
Set Word = Documents("Comps extraction from reports")
Dim i As Long
Dim j As Long
Dim RowWord As Long
Dim ColWord As Long
Dim oWB As Workbook
Set oExcel = New Excel.Application
Set oWB = oExcel.Workbooks.Open("C:\Users\chris\Desktop\TABLE EXPORT.xlsx")
oExcel.Visible = True
RowWord = Word.Tables(1).Rows.Count
ColWord = Word.Tables(1).Columns.Count
With Word.Tables(1)
'copy cell contents from Word table cells to Excel cells
For i = 1 To RowWord
For j = 1 To ColWord
Cells(i, j) = WorksheetFunction.Clean(.Cell(i, j).Range.Text)
Next j
Next i
End With
End Sub
答案 0 :(得分:3)
如果您使用的是Word VBA,则需要正确限定对Excel对象模型的任何引用。特别是,行
Cells(i, j) = WorksheetFunction.Clean(.Cell(i, j).Range.Text)
应该是
oWb.Sheets(1).Cells(i, j) = oExcel.WorksheetFunction.Clean(.Cell(i, j).Range.Text)
另外,我怀疑
Dim oWB As Workbook
应该是
Dim oWB As Object
Word VBA不了解WorkBook Objects(虽然你可能已经包含了一个引用?)