僅供初學者使用,我的VBA體驗有限,而且我主要修改我在網上發佈的內容。我有一個Excel宏,可以從Word表格中的表格(或多個表格)中獲取數據。我的問題是,我擁有一千個Word文檔,所以我希望能找到一個解決方案,幫助您從用戶選擇的文件夾中的所有Word文檔複製數據。打開多個Word文檔
這裏是我當前的代碼:
Sub ImportWordTables()
'Imports cells from Word document Tables in multiple documents
Dim wdDoc As Object
Dim TableNo As Integer 'number of tables in Word doc
Dim iTable As Integer 'table number index
Dim iRow As Long 'row index in Excel
Dim iCol As Integer 'column index in Excel
Dim ix As Long
ix = ActiveSheet.UsedRange.Row - 1 + ActiveSheet.UsedRange.Rows.Count
LastRow = ix
wdFileName = Application.GetOpenFilename("Word files (*.doc*),*.doc*", MultiSelect = True, _
"Browse for files containing table to be imported")
If wdFileName = False Then Exit Sub '(user cancelled import file browser)
Set wdDoc = GetObject(wdFileName) 'open Word file
With wdDoc
TableNo = 1
If TableNo = 0 Then
MsgBox "This document contains no tables", _
vbExclamation, "Import Word Table"
End If
For iTable = 1 To TableNo
With .tables(iTable)
'copy cell contents from Word table cells to Excel cells in column A and B
Cells(ix + 1, "A") = WorksheetFunction.Clean(.Cell(1, 2))
Cells(ix + 1, "B") = WorksheetFunction.Clean(.Cell(2, 2))
Cells(ix + 1, "C") = WorksheetFunction.Clean(.Cell(3, 2))
Cells(ix + 1, "D") = WorksheetFunction.Clean(.Cell(4, 2))
Cells(ix + 1, "E") = WorksheetFunction.Clean(.Cell(5, 2))
Cells(ix + 1, "F") = WorksheetFunction.Clean(.Cell(6, 2))
Cells(ix + 1, "G") = WorksheetFunction.Clean(.Cell(6, 3))
Cells(ix + 1, "H") = WorksheetFunction.Clean(.Cell(7, 2))
Cells(ix + 1, "I") = WorksheetFunction.Clean(.Cell(8, 2))
Cells(ix + 1, "J") = WorksheetFunction.Clean(.Cell(9, 2))
Cells(ix + 1, "K") = WorksheetFunction.Clean(.Cell(10, 2))
Cells(ix + 1, "L") = WorksheetFunction.Clean(.Cell(13, 2))
End With
Next iTable
End With
Set wdDoc = Nothing
End Sub
我知道,我需要創建一個循環,但我不能改變任何的循環例子我類似的問題找到工作。
首先,非常感謝你對這個項目的幫助。我完全理解你對excel不是最好的解決方案意味着什麼。這就是說,我得到一個關於以下內容的編譯錯誤:Private Function GetCellValue(ByRef pTable As Word.Table,ByVal pRow As Long)As Variant說它沒有被定義。我會盡力弄清楚,但如果你在線,首先,謝謝,其次,我只需要在頂部定義它? 編輯:具體的錯誤是,「用戶定義的類型沒有定義」 –
任何機會,你沒有趕上subtl的意見,我把代碼放在設置引用到Word和Scripting庫。它在主子程序中。您需要設置對Microsoft Word#。#Object Library和Microsoft Scripting Runtime庫的引用。這應該照顧那個錯誤。 – dscarr
是的。 。 。該函數使用參數列表中的Word.Table對象。這需要對Word對象庫的引用。 – dscarr