I was using this VBA code that was working, now the function returns 0 because the URL has changed. What URL should I use now?
Thank you very much.
Function YahooCurrencyConverter(ByVal strFromCurrency, ByVal strToCurrency, Optional ByVal strResultType = "Value")
On Error GoTo ErrorHandler
'Init
Dim strURL As String
Dim objXMLHttp As Object
Dim strRes As String, dblRes As Double
Set objXMLHttp = CreateObject("MSXML2.ServerXMLHTTP")
strURL = "http://finance.yahoo.com/d/quotes.csv?e=.csv&f=c4l1&s=" & strFromCurrency & strToCurrency & "=X"
'Send XML request
With objXMLHttp
.Open "GET", strURL, False
.setRequestHeader "Content-Type", "application/x-www-form-URLEncoded"
.Send
strRes = .ResponseText
End With
'Parse response
dblRes = Val(Split(strRes, ",")(1))
Select Case strResultType
Case "Value": YahooCurrencyConverter = dblRes
Case Else: YahooCurrencyConverter = "1 " & strFromCurrency & " = " & dblRes & " " & strToCurrency
End Select
CleanExit:
Set objXMLHttp = Nothing
Exit Function
ErrorHandler:
YahooCurrencyConverter = 0
GoTo CleanExit
End Function
Using a JSON parser:
Or, you could used Power Query to set up a refreshable data connection
You can set up the Query in the UI by entering the URL. After you run it, edit the query by
After you do this, you can refresh the query whenever you want with a single button press.
This is the M-code generated by the UI. I chose to also keep the Time Updated column:
Split:
Now you have obtained the JSON string you can parse with Split function. Here I am reading the JSON in the comments from a cell
JSON Parser:
Here you can use a JSON parser, JSONConverter.bas and then add a reference via VBE > Tools > References > Microsoft Scripting Dictionary
This is the path to your desired change rate:
The initial object is a dictionary containing another dictionary. Dictionaries are denoted by
{}
. You access the first dictionary with the keyRealtime Currency Exchange Rate
and then the required value, from the inner dictionary, by the associated key:5. Exchange Rate
Whole request with JSON parser:
As an UDF:
To use split function replace penultimate function line with