从Array data,Retrieve ElementID访问网站页面,填充新数组

时间:2016-09-26 16:01:21

标签: arrays excel vba loops

目的

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

APPROACH

  1. 选择活动工作表并将要转换的货币复制到数组中(例如[“EUR”,“GBP”,“USD”]
  2. 打开浏览器并访问货币转换网站
  3. 循环使用不同的货币并提取货币换算系数
  4. 将转换因子附加到数组
  5. 使用最新的转换因子重新填充Excel
  6. CODE

    Sub retreiveCurrencies()
    
    Dim ws As Worksheet
    Dim locals() As Variant
    Dim exchangeArray() As Variant
    Dim i As Long
    Dim IE As Object
    
    
    'Select currencies to convert
    Sheets("APPENDIX - CURRENCY CONVERTER").Activate
    locals = Array(ActiveSheet.Range("B2:B15"))
    'This should return locals = ["EUR", "GBP, "USD"]
    
    'Prep Internet Explorer
    Set IE = CreateObject("InternetExplorer.Application")
    IE.Visible = False
    
    Do While IE.Busy And Not IE.readyState = READYSTATE_COMPLETE
        DoEvents
    Loop
    
    'Loop through currencies and retreive exchange rates. Paste rates into exchangeArray
    For i = LBound(locals()) To UBound(locals())
        IE.Navigate "http://www.usforex.com/currency-converter/" & locals(i) & "/usd/1.00/false"
        exchange = IE.Document.GetElementById("converterToAmount").innerText
        'exchangeArray = [] QUESTION: What should I add here to create an array of exchange rates?
    Next i
    
    'Paste exchange rate array into currency conversion column
    ActiveSheet.Range("D2:D15") = exchangeArray()
    
    
    End Sub
    

    问题/ ISSUE(S)

    1. 对于第IE.Navigate "http://www.usforex.com/currency-converter/" & locals(i) & "/usd/1.00/false"行,我收到“类型不匹配”。 我是否需要将locals()转换为文字?
    2. 如何遍历IE.Document.GetElementById("converterToAmount").innerText并将检索到的值附加到新数组exchangeArray()
    3. 注意:此代码中可能存在许多错误。我是VBA的新手,这是我尝试更复杂的剧本。

1 个答案:

答案 0 :(得分:1)

问题是这一行:

locals = Array(ActiveSheet.Range("B2:B15"))

这不是从ActiveSheet.Range("B2:B15)创建一个值数组 - 它创建了一个Range个对象数组,其中只有一个元素。这意味着在实际引发不匹配的代码行中,locals(i)Range。由于Range中有多个单元格,因此默认成员(.Value)将返回Variant的二维数组,该数组无法连接成字符串。

你需要更像这样的东西:

locals = ActiveSheet.Range("B2:B15").Value

'...

'Loop through currencies and retreive exchange 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"
    exchange = ie.document.getElementById("converterToAmount").innerText
    'exchangeArray = [] QUESTION: What should I add here to create an array of exchange rates?
Next i