Object尽pipe已经定义了对象(EXCEL,VBA)

目的

提取各种货币的汇率数据。

APPROACH

  1. select活动工作表并将待转换货币复制到数组中(例如[“EUR”,“GBP”,“USD”]
  2. 打开浏览器并访问货币转换网站
  3. 循环使用不同的货币并提取货币转换因子
  4. 将转换因子附加到数组
  5. 用最新的转换因子重新devise优秀

HTML

<span class="amount" id="converterToAmount" style="">26.21</span> 

 Sub retreiveCurrencies() Dim ws As Worksheet Dim locals() As Variant Dim rates As Object Dim exchangeArray() As Variant Dim i As Long Dim IE As Object 'Select currencies to convert Sheets("APPENDIX - CURRENCY CONVERTER").Activate locals = ActiveSheet.Range("B2:B15").Value 'This should return locals = ["EUR", "GBP, "USD"] 'Prep Internet Explorer Set IE = CreateObject("InternetExplorer.Application") IE.Visible = True 'Loop through currencies and retreive rates. Paste rates into exchangeArray For i = LBound(locals, 1) To UBound(locals, 1) IE.Navigate "http://www.usforex.com/currency-converter/" & locals(i, 1) & "/usd/1.00/false" Do While IE.Busy And Not IE.readyState = READYSTATE_COMPLETE DoEvents Loop '!!!!error on following line = "Object required"!!!! Set rates = IE.Document.GetElementById("converterToAmount").innerText ReDim Preserve exchangeArray(rates) Next i 'Paste exchange rate array into currency conversion column ActiveSheet.Range("E2:E15") = exchangeArray() End Sub 

问题/ ISSUE(S)

  1. 目前得到错误“对象需要”@ Set rates = IE.Document.GetElementById("converterToAmount").innerText尽pipe定义Dim rates As Object 。 任何解决scheme
  2. ActiveSheet.Range("E2:E15") = exchangeArray()足以将单元格粘贴回excel?

标题问题已经由@Dave在注释中解决了 – .innerText是一个String ,而不是一个Object

也就是说,你的数组语法是有点closures的Redim Preserve实际上只调整了数组的大小 – 它没有写入数值。 您也尝试使用rates作为索引而不是添加它。 另外,我会采取@Jeeped在评论中提出的build议,并将其应用到您的exchangeArrayarrays。 这个大小是固定的,它的大小和locals 。 这意味着你可以这样做:

 ReDim exchangeArray(LBound(locals, 1) To UBound(locals, 1), LBound(locals, 2) To UBound(locals, 2)) 

一旦它已经设置为正确的大小,你甚至不必在循环中ReDim 。 只要镜像你的“关键”数组的位置:

 Dim rates As String '... 'Loop through currencies and retreive rates. Paste rates into exchangeArray ReDim exchangeArray(LBound(locals, 1) To UBound(locals, 1), LBound(locals, 2) To UBound(locals, 2)) For i = LBound(locals, 1) To UBound(locals, 1) ie.navigate "http://www.usforex.com/currency-converter/" & locals(i, 1) & "/usd/1.00/false" Do While ie.Busy And Not ie.readyState = READYSTATE_COMPLETE DoEvents Loop '!!!!error on following line = "Object required"!!!! rates = ie.document.getElementById("converterToAmount").innerText exchangeArray(i, 1) = rates Next i