[分享]Excel VBA 抓取台灣銀行匯率


剛剛看到有在問抓取台灣銀行匯率的資料
所以幫忙寫了一下程式碼

[分享]Excel VBA 抓取台灣銀行匯率

Sub test()

Dim t: t = Timer

[A9:G50].ClearContents

Dim myXML As Object
Set myXML = CreateObject("Microsoft.XMLHTTP")

Dim myHTML As Object
Set myHTML = CreateObject("HTMLFile")

ReDim myArr(1 To 30, 1 To 7)

With myXML
.Open "GET", "http://rate.bot.com.tw/xrt?Lang=zh-TW", False
.send

'Debug.Assert InStr(1, .responseText, "28.94") <> 0
myHTML.body[removed] = .responseText
Set myTable = myHTML.getElementsByTagName("table")(0)
Set myTrs = myTable.getElementsByTagName("tbody")(0).getElementsByTagName("tr")
i = 1
For Each myTr In myTrs
Set myTds = myTr.getElementsByTagName("td")
j = 1
For Each myTd In myTds
If InStr(1, myTd.innerText, ")") <> 0 Then
myArr(i, j) = Split(Split(myTd.innerText, ")")(1) & ")", Chr(10))(1)
Else
myArr(i, j) = myTd.innerText
End If
If j > 5 Then ActiveSheet.Hyperlinks.Add anchor:=Cells(i + 8, j), Address:="http://rate.bot.com.tw" & Split(myTd.getElementsByTagName("a")(0).getAttribute("href"), ":")(1)
j = j + 1
If j > 7 Then Exit For
Next
i = i + 1
Next

[A9].Resize(UBound(myArr, 1), UBound(myArr, 2)).Value = myArr

End With

Set myXML = Nothing

Debug.Print Format(Timer - t, "0.00秒")

End Sub

[分享]Excel VBA 抓取台灣銀行匯率

用此程式甚至可以將上面的連結一起抓下來
供大家參考
https://raymondchiendtrt.blogspot.tw/2018/05/excel-vba.html
2018-05-21 11:54 發佈
先前用版主的程式碼抓取匯率,非常實用
但近期改用office 365後再跑這段巨集就會出現"執行階段錯誤9:陣列索引超出範圍"的錯誤訊息
執行偵錯是下面這段出現錯誤

If j > 5 Then ActiveSheet.Hyperlinks.Add anchor:=Cells(i + 8, j), Address:="http://rate.bot.com.tw" & Split(myTd.getElementsByTagName("a")(0).getAttribute("href"), ":")(1)

後來試著改成0以後可以跑了
ActiveSheet.Hyperlinks.Add anchor:=Cells(i + 8, j), Address:="http://rate.bot.com.tw" & Split(myTd.getElementsByTagName("a")(0).getAttribute("href"), ":")(0)

但是第一欄的幣別名稱顯示就出不來,
想請問大大有其他修改方式
謝謝
內文搜尋
X
評分
評分
複製連結
Mobile01提醒您
您目前瀏覽的是行動版網頁
是否切換到電腦版網頁呢?