
我正在嘗試從一堆 Word 文件中獲取數據,並使用我在該網站上找到的以下程式碼將它們添加到 Excel 電子表格中。但是,在編輯程式碼以透過路徑選擇特定文件後,當我嘗試運行程式碼時,我繼續收到“需要物件”錯誤。您能解釋一下我哪裡出了問題以及如何解決嗎?抱歉,我對 VBA 還很陌生,因此我很迷失。
Sub Macro1()
Dim xl As Object
Set xl = CreateObject("excel.application")
xl.Workbooks.Add
xl.Visible = True
'Here put your path where you have your documents to read:
myPath = "C:\Users\arahmani\Desktop\march\" 'End with '\'
myFile = Dir(myPath & "*.docx")
xlRow = 1
Do While myFile <> ""
Documents.Open Filename:=myPath & myFile, ConfirmConversions:=False, _
ReadOnly:=False, AddToRecentFiles:=False, PasswordDocument:="", _
PasswordTemplate:="", Revert:=False, WritePasswordDocument:="", _
WritePasswordTemplate:="", Format:=wdOpenFormatAuto, XMLTransform:=""
xlCol = 0
Dim t As ListObject
For Each t In ActiveDocument.Tables
For Each Row In t.Rows
For Each c In r.Range.Cells
myText = c
myText = Replace(myText, Chr(13), "")
myText = Replace(myText, Chr(7), "")
xlCol = xlCol + 1
xl.ActiveWorkbook.ActiveSheet.Cells(xlRow, xlCol) = myText
Next c
xlRow = xlRow + 1
xlCol = 0
Next Row
Next t
ActiveWindow.Close False
myFile = Dir
Loop
xl.Visible = True
End Sub
答案1
很難確定,但作為一個起點
Dim t As ListObject
應該
Dim t As Table
如果這是 Mac Office,即使您嘗試執行初始 CreateObject,也很可能會遇到問題。
答案2
需要物件(錯誤 424)發生的原因是:
對屬性和方法的參考通常需要明確的物件限定符。
您試圖在未聲明的情況下使用 MS Word 文件。您應該先建立 Word 應用程式物件。
Set wrd = CreateObject("word.Application")
然後用它來開啟文件。
wrd.Documents.Open Filename:=myPath & myFile