neodjandre
Well-known Member
- Joined
- Nov 29, 2006
- Messages
- 950
- Office Version
- 2019
- Platform
- Windows
I am using this function to get FX rates predominantly from USD to GBP. However, it is not always accurate to the specified date. Does anyone use something else which could be more accurate please?
many thanks,
Andrew
Code:
Function GetFxRate(CurrencyIn As String, CurrencyOut As String, Dt As Date) As Double
Dim strURL As String
Dim StartAtPos As String
Dim objHTTP
Dim WebResponse
Dim d As Long
Dim DtTxt As String
Dim DtPos As String
Dim ValTxt As String
'https://api.exchangeratesapi.io/history?start_at=2017-12-25&end_at=2018-01-02&symbols=CAD&base=EUR
GetFxRate = 1
'Get 7 days of data as some days might not have data (new year, christmas, etc)
strURL = "https://api.exchangeratesapi.io/history?"
strURL = strURL & "start_at=" & Format(Dt - 7, "yyyy-mm-dd") & "&end_at=" & Format(Dt, "yyyy-mm-dd")
strURL = strURL & "&symbols=" & CurrencyIn & "&base=" & CurrencyOut
'Debug.Print strURL 'The Url that is being called
Set objHTTP = CreateObject("WinHttp.WinHttpRequest.5.1")
objHTTP.Open "GET", strURL, False
objHTTP.send
If objHTTP.Status = "200" Then
objHTTP.WaitForResponse
WebResponse = objHTTP.responseText
'e.g. "{"rates":{"2018-12-27":{"EUR":0.6451612903},"2018-12-31":{"EUR":0.6408202499},"2018-12-28":{"EUR":0.6409434688}},"start_at":"2018-12-25","base":"CAD","end_at":"2019-01-01"}"
StartAtPos = InStr(WebResponse, "start_at")
For d = Dt To Dt - 7 Step -1
DtTxt = Format(d, "yyyy-mm-dd")
DtPos = InStr(WebResponse, DtTxt)
If DtPos > 0 And DtPos < StartAtPos Then
ValTxt = Mid(WebResponse, 1 + InStr(DtPos, WebResponse, "{"), InStr(DtPos, WebResponse, "}") - InStr(DtPos, WebResponse, "{") - 1)
GetFxRate = Val(Right(ValTxt, Len(ValTxt) - InStr(ValTxt, ":")))
Exit For
End If
Next d
End If
Set objHTTP = Nothing
End Function
many thanks,
Andrew