VBA如何发送“ ENTER”以执行Web

时间:2019-11-27 08:52:33

标签: html vba web-scraping

VBA如何发送“ ENTER”以执行Web?在Web中输入“ 5904”时,需要在键盘上手动按“ ENTER”。那么如何在VBA中自动将其按入网页。

Public Sub Web()
Dim ie As New InternetExplorer

With ie
.Visible = True
.Navigate2 "https://www.tpex.org.tw/web/stock/statistics/monthly/st44.php?l=zh-tw"

While .Busy Or .readyState < 4: DoEvents: Wend
 Set ticker = ie.document.getElementById("input_stock_code")
 ticker.Value = "5904"

End With
End Sub

1 个答案:

答案 0 :(得分:0)

该页面执行xhr POST请求,因此您可以模仿添加预期的Content-Type标头。我使用剪贴板写出了与类名匹配的table,但是您可以循环trs节点的tdstable

Option Explicit

Public Sub WriteOutMonthlyStockTrading()
    'VBE>Tools>References>Microsoft HTML Object Library
    Dim http As Object, html As MSHTML.HTMLDocument

    Set http = CreateObject("MSXML2.XMLHTTP")
    Set html = New MSHTML.HTMLDocument

    With http
        .Open "POST", "https://www.tpex.org.tw/web/stock/statistics/monthly/st44.php?l=zh-tw", False
        .setRequestHeader "User-Agent", "Mozilla/5.0"
        .setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
        .send "yy=2019&input_stock_code=5904"
        html.body.innerHTML = .responseText
    End With

    Dim clipboard As Object

    Set clipboard = GetObject("New:{1C3B4210-F441-11CE-B9EA-00AA006B1A69}")

    clipboard.SetText html.querySelector(".page-table-board").outerHTML

    clipboard.PutInClipboard
    ThisWorkbook.Worksheets("Sheet1").Range("A1").PasteSpecial
End Sub