【发布时间】:2020-09-04 00:29:01
【问题描述】:
我需要一个可以将本地 html 表格数据提取到 Excel 工作表的 VBA 脚本。我有一些使用 URL 链接工作的代码(在网络上的某个地方找到),但我想要的是能够使用我本地存储的 html 文件来完成它。我得到的错误是'app defined or object defined error'。
Sub HTML_Table_To_Excel()
Dim htm As Object
Dim Tr As Object
Dim Td As Object
Dim Tab1 As Object
'Replace the URL of the webpage that you want to download
Web_URL = "http://espn.go.com/nba/"
'Create HTMLFile Object
Set HTML_Content = CreateObject("htmlfile")
'Get the WebPage Content to HTMLFile Object
With CreateObject("msxml2.xmlhttp")
.Open "GET", Web_URL, False
.send
HTML_Content.body.innerHTML = .responseText 'this is the highlighted part for the error
End With
Column_Num_To_Start = 1
iRow = 2
iCol = Column_Num_To_Start
iTable = 0
'Loop Through Each Table and Download it to Excel in Proper Format
For Each Tab1 In HTML_Content.getElementsByTagName("table")
With HTML_Content.getElementsByTagName("table")(iTable)
For Each Tr In .Rows
For Each Td In Tr.Cells
Sheets(1).Cells(iRow, iCol).Select
Sheets(1).Cells(iRow, iCol) = Td.innerText
iCol = iCol + 1
Next Td
iCol = Column_Num_To_Start
iRow = iRow + 1
Next Tr
End With
iTable = iTable + 1
iCol = Column_Num_To_Start
iRow = iRow + 1
Next Tab1
MsgBox "Process Completed"
End Sub
【问题讨论】:
-
您尝试将
file://换成WEB_URL吗?例如,如果您的文件存储在 ~/User/abc.html 中,您可以尝试:WEB_URL = "file:///Users/abc.html" -
是的。我试过
WEB_URL = "file://C:/users/folder/test.html"。那没起效。得到同样的错误。 -
要使用正确的 URL 制作 XHR,连接前缀
file:///和文件的编码路径(使用EncodeUriComponent()函数,如 in this answer)。