【发布时间】:2019-05-16 21:19:11
【问题描述】:
背景
免责声明:我是初学者,请公开我的 - 最有可能是错误的 - 代码。
我想使用启用按钮的 VBA 宏来更新货币对的值(PREV CLOSE)。我的 Excel 工作表在 G:G 列 上包含 FX 对(例如 USDGBP),然后用于为该列中的每一对运行 FOR 循环。
然后该值将存储在 I:I 列
现在,调试器的问题在于我将在下面突出显示的一行代码
来源
我从https://www.youtube.com/watch?v=JxmRjh-S2Ms&t=1050s 获得了一些灵感 - 特别是从 17:34 开始 - 但我希望我的代码只需按一下按钮即可在多个网站上运行。
我试过下面的代码
Public Sub Auto_FX_update_BMG()
Application.ScreenUpdating = False 'My computer is not very fast, thus I use this line of
'code to save some computing power and time
Dim internet_object As InternetExplorer
Dim i As Integer
For i = 3 To Sheets(1).Cells(3, 7).End(xlDown).Row
FX_Pair = Sheets(1).Cells(i, 7)
Set internet_object = New InternetExplorer
internet_object.Visible = True
internet_object.navigate "https://www.bloomberg.com/quote/" & FX_Pair & ":CUR"
Application.Wait Now + TimeValue("00:00:05")
internet_object.document.getElementsByClassName("class")(0).getElementsByTagName ("value__b93f12ea") '--> DEBUGGER PROBLEM
'My goal here is to "grab" the PREV CLOSE
'value from the website
With ActiveSheet
.Range(Cells(i, 9)).Value = HTML_element.Children(0).textContent
End With
Sheets(1).Range(Cells(i, 9)).Copy 'Not sure if these 2 lines are unnecesary
ActiveSheet.Paste
Next i
Application.ScreenUpdating = True
End Sub
预期结果
当我在列 G:G 的单元格中输入“USDGBP”时,宏将转到 https://www.bloomberg.com/quote/EURGBP:CUR 并“获取”PREV CLOSE 值 0.8732(使用今天的值)并插入它在第一列:I
的相应行中到目前为止,我只是面对调试器,对如何解决问题没有太多想法。
【问题讨论】:
-
您在这里遇到了多个问题...
Set internet_object = New InternetExplorer需要在您的循环之外。.Range(Cells(i, 9)).Value应该只是Cells(i, 9).Value。 `internet_object.document.getElementsByClassName` 行需要成为操作的一部分,例如Range("A1").Value = internet_object.document.getElementsByClassName...等。 -
我今天没有时间看这个,但是我会看看我是否可以在明天使用
.querySelector来帮助您解决这个问题:)
标签: excel vba web-scraping