【问题标题】:x-rates Excel VBA data pullingx-rates Excel VBA 数据拉取
【发布时间】:2019-04-10 08:30:04
【问题描述】:

我是 Excel VBA 的新手,无法从以下网站提取数据:https://www.x-rates.com/historical/?from=CAD&amount=1&date=2018-11-05。我想自动化这个过程,这样我每个月都能得到这些费率。这是我所得到的,我从这里迷路了:

'启动一个名为 SearchBot 的新子程序

Sub SearchBot()

'dimension (declare or set aside memory for) our variables
Dim objIE As InternetExplorer 'special object variable representing the IE browser
Dim aEle As HTMLLinkElement 'special object variable for an <a> (link) element
Dim y As Integer 'integer variable we'll use as a counter
Dim result As String 'string variable that will hold our result link

'initiating a new instance of Internet Explorer and asigning it to objIE
Set objIE = New InternetExplorer

'make IE browser visible (False would allow IE to run in the background)
objIE.Visible = True

'navigate IE to this web page (a pretty neat search engine really)
objIE.navigate "https://www.x-rates.com/table/?from=CAD&amount=1"

任何帮助将不胜感激!

【问题讨论】:

    标签: excel vba web-scraping automation


    【解决方案1】:

    您可以使用以下内容。它使用XMLHTTP 作为更快的检索方法。将昨天的日期连接到 URL 以获取最新费率。按字母顺序排列的表是根据其类名和索引位置选择的。

    Option Explicit
    Public Sub GetTable()
        Dim sResponse As String, html As HTMLDocument, ws As Worksheet, clipboard As Object
    
        Set ws = ThisWorkbook.Worksheets("Sheet1")
    
        With CreateObject("MSXML2.XMLHTTP")
            .Open "GET", "https://www.x-rates.com/historical/?from=CAD&amount=1&date=" & Format$(Date - 1, "yyyy-mm-dd"), False
            .setRequestHeader "If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT"
            .send
            sResponse = StrConv(.responseBody, vbUnicode)
        End With
    
        Set clipboard = GetObject("New:{1C3B4210-F441-11CE-B9EA-00AA006B1A69}")
        Set html = New HTMLDocument
    
        With html
            .body.innerHTML = sResponse
            clipboard.SetText .querySelectorAll(".ratesTable").item(1).outerHTML
            clipboard.PutInClipboard
        End With     
        ws.Cells(1, 1).PasteSpecial 
    End Sub
    

    参考资料(VBE > 工具 > 参考资料):

    1. Microsoft HTML 对象库

    【讨论】:

    • 在末尾添加Set ws = NothingSet clipboard = NothingSet html = Nothing。你需要收拾残局。
    • @NELMVN 我的理解是垃圾收集无论如何都会处理这个问题,因为对象引用将在过程结束时超出范围。也许我错了。
    • NELMVN 正如@chillin 所指出的,当 sub 超出范围时,这将被清除。对象变量将释放它们的引用,并且运行时调用对象的 Release 方法来减少对象的引用计数。这与 set x = Nothing 相同。
    猜你喜欢
    • 1970-01-01
    • 2019-02-08
    • 1970-01-01
    • 2019-05-14
    • 1970-01-01
    • 2021-07-17
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    相关资源
    最近更新 更多