我正在尝试使用我在此网站上找到的以下代码从一堆 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