2016-09-26 97 views
1

目的所需的对象尽管已经定义的对象(EXCEL,VBA)

拉在各种货币汇率数据。

APPROACH

  1. 选择活动薄板和复制货币-待转换成一个阵列(例如[ “EUR”, “GBP”, “USD”]
  2. 打开浏览器和访问货币转换网站
  3. 遍历不同的货币,并提取货币换算系数
  4. 追加转换因子为一个数组
  5. 重新填充的excel用最新的变换因子

HTML

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

CODE

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. 尽管定义了Dim rates As Object,但目前收到错误“Object Required”@Set rates = IE.Document.GetElementById("converterToAmount").innerText。任何解决方案
  2. 是否ActiveSheet.Range("E2:E15") = exchangeArray()足以将细胞粘贴回excel?
+3

'rates' should not be a object。您将它设置为IE元素的innertext文本的值,这是一个字符串。尝试将其定义为字符串并删除“Set”关键字。 – Dave

+0

我可以发誓我以前做过这件事。谢谢你解决这个问题。 但是,当我在'ReDim'之后调用'MsgBox exchangeArray(i)'时,我没有看到任何值。我是否误解了某些内容?由于某些原因,费率未被拉到和/或保存到交换列表中 – jonplaca

+1

我倾向于用变量数组的范围来定义目标范围,例如'.Range(“E2”)。Resize(UBound(exchangeArray,1),UBound(exchangeArray,2))= exchangeArray' – Jeeped

回答

4

标题问题已由@Dave解决--是String,而不是Object

这就是说,你的数组语法有点关 - Redim Preserve实际上只调整了数组的大小 - 它没有给它写值。您还试图使用rates作为索引而不是添加它。此外,我会采取@Jeeped在评论中提出的建议,并将其应用于您的exchangeArray。尺寸是固定的,并且尺寸始终与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 
+0

谢谢 - 这将一切都很好地结合在一起,并说明我出错的地方。标记为解决方案。 – jonplaca

相关问题