2016-09-26 95 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

相關問題