在之前的回答中(vba - html 表格到 excel 工作表) 关于将 HTML 表格内容解析/粘贴到 Excel 工作表中,wbeard2 分享了这段非常有用且具有说明性的代码。他/她指出,它将表格数据植入 Excel,但不会植入标题。我想知道如何修改此代码以将分栏标题也包含在 Excel 工作表中。我想有一种循环遍历标题元素的方法,类似于循环遍历所有 和 行中的单元格的方法,但不确定是否有等效的标题循环元素——也许是 ?任何有关此的建议/指导都值得赞赏。
以下是上面引用的答案中的示例代码:
Private Sub Test()
Dim ie As Object, i As Long, strText As String
Dim doc As Object, hTable As Object, hBody As Object, hTR As Object, hTD As Object
Dim tb As Object, bb As Object, tr As Object, td As Object
Dim y As Long, z As Long, wb As Excel.Workbook, ws As Excel.Worksheet
Set wb = Excel.ActiveWorkbook
Set ws = wb.ActiveSheet
Set ie = CreateObject("InternetExplorer.Application")
ie.Visible = True
y = 1 'Column A in Excel
z = 1 'Row 1 in Excel
ie.navigate "http://", , , , "Content-Type: application/x-www-form-urlencoded" & vbCrLf
Do While ie.busy: DoEvents: Loop
Do While ie.ReadyState <> 4: DoEvents: Loop
Set doc = ie.document
Set hTable = doc.GetElementsByTagName("table")
For Each tb In hTable
Set hBody = tb.GetElementsByTagName("tbody")
For Each bb In hBody
Set hTR = bb.GetElementsByTagName("tr")
For Each tr In hTR
Set hTD = tr.GetElementsByTagName("td")
y = 1 ' Resets back to column A
For Each td In hTD
ws.Cells(z, y).Value = td.innertext
y = y + 1
Next td
DoEvents
z = z + 1
Next tr
Exit For
Next bb
Exit For
Next tb
End Sub