2015-04-30 49 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

謝謝!偉大的作品:) –

相關問題