2015-04-30 47 views
1

VBA新手,下面是我的word vba代码,尝试在中读取所有表格在word文档中分离excel工作表(每个表格一个)。我在行得到一个错误:如何导出Word文档中的所有表格以分开excel工作表

WS.Cells(i, j) = myTable.Cell(i, j) 

说:

集合的请求的成员不存在

经过一番排查问题似乎与myTable.Cell (我,j),但每个表的大小应该处理...?想法,建议?谢谢!

Sub ReadTablesToExcel() 
Dim myTable As Table 
Dim RowsCount As Integer 
Dim ColumnsCount As Integer 
Dim oExcel As Object 
Set oExcel = CreateObject("Excel.Application") 
Dim oExcel1 As Object 
Set oExcel1 = oExcel.Workbooks.Open("C:\Users\Mike\Desktop\Book3.xlsx") 
    For Each myTable In ActiveDocument.Tables 
    Dim WS As Object 
    Set WS = oExcel1.Activesheet 
     RowsCount = myTable.Rows.Count 
     ColumnsCount = myTable.Columns.Count 
     For i = 1 To RowsCount 
      For j = 1 To ColumnsCount 
       WS.Cells(i, j) = myTable.Cell(i, j) 
      Next j 
     Next i 
    Next myTable 
ActiveDocument.Repaginate 
End Sub 

回答

1

您的代码可能已经运行而不会出现错误。我添加了只为每个表添加新工作表的代码。

这工作:(Windows XP中,Office 2007中)

Sub ReadTablesToExcel() 
    Dim myTable As Table 
    Dim RowsCount As Integer 
    Dim ColumnsCount As Integer 
    Dim oExcel As Object 
    Set oExcel = CreateObject("Excel.Application") 
    Dim oExcel1 As Object 
    Set oExcel1 = oExcel.Workbooks.Open("C:\Users\Mike\Desktop\Book3.xlsx") 

    For Each myTable In ActiveDocument.Tables 

     Dim WS As Object 
     oExcel1.Sheets.Add 
     Set WS = oExcel1.ActiveSheet 

     RowsCount = myTable.Rows.Count 
     ColumnsCount = myTable.Columns.Count 

     For i = 1 To RowsCount 
      For j = 1 To ColumnsCount 
       WS.Cells(i, j) = myTable.Cell(i, j) 
      Next j 
     Next i 

    Next myTable 

    oExcel1.Close (True) 'Closes the workbook by saving changes. 
    Set oExcel1 = Nothing 
    ActiveDocument.Repaginate 

End Sub 
+0

谢谢!伟大的作品:) –

相关问题