首页 > 解决方案 > VBA如何发送“ENTER”来执行Web

问题描述

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

标签: htmlvbaweb-scraping

解决方案


该页面执行 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

推荐阅读