簡體   English   中英

使用VBA從Excel中的網頁提取表

[英]Extract Table from Webpage in Excel using VBA

如何從網頁中提取Excel中的下表?

公司簡介 獎金比率|公告|記錄|前獎金

Codes
Dim ie As SHDocVw.InternetExplorer
Set ie = New InternetExplorerMedium
Set ie = CreateObject("InternetExplorer.Application")
 While ie.busy
 DoEvents
 Wend
 ie.Visible = True
 While ie.busy
 DoEvents
 Wend
Dim NavURL As String
NavURL = "https://www.moneycontrol.com/stocks/marketinfo/bonus/homebody.php?sel_year=2015"

ie.Navigate NavURL
 While ie.busy
 DoEvents
 Wend
 Set doc = ie.document
 Set hTable = doc.GetElementsByTagName("table")


 y = 2 'Column B in Excel
 z = 7 'Row 7 in Excel
 For Each td In hTable
 Set hHead = tb.GetElementsByTagName("td")
 For Each hh In hHead
 Set hTR = hh.GetElementsByTagName("tr")
 For Each tr In hTR

網頁: https//www.moneycontrol.com/stocks/marketinfo/bonus/homebody.php? sel_year = 2015

通過保持與網頁或文本格式相同的獎金比率在Excel中復制獎金比率時,獎金比率將轉換為十進制

您的hTable是一個集合,而不是單個元素。 您的代碼應該拋出錯誤。

您要定位到特定的表,然后循環表中的行和行中的單元格。 您要檢查是否正在處理第二列,以便可以保護比率的格式。 您還希望監視行號以處理頂部的合並單元格。

Option Explicit
Public Sub GetInfo()
    Const URL As String = "https://www.moneycontrol.com/stocks/marketinfo/bonus/homebody.php?sel_year=2015"
    Dim html As HTMLDocument, hTable As HTMLTable, ws As Worksheet, headers()
    headers = Array("Company", "Bonus Ratio", "Announcement", "Record", "Ex-bonus")
    Set ws = ThisWorkbook.Worksheets("Sheet1")
    Set html = New HTMLDocument
    With CreateObject("MSXML2.XMLHTTP")
        .Open "GET", URL, False
        .Send
        html.body.innerHTML = .responseText
    End With
    Set hTable = html.querySelector("table.dvdtbl")
    Dim td As Object, tr As Object, r As Long, c As Long
    r = 1
    With ws
        .Cells(1, 1).Resize(1, UBound(headers) + 1) = headers
        For Each tr In hTable.getElementsByTagName("tr")
            r = r + 1: c = 1
            If r > 3 Then
                For Each td In tr.getElementsByTagName("td")
                    .Cells(r - 2, c) = IIf(c = 2, "'" & td.innerText, td.innerText)
                    c = c + 1
                Next
            End If
        Next
    End With
End Sub

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM