# Currency convertor using Excel

One of the most time-wasting problems at my former job was to get the currency match for a list of dates. I came up with a solution to this problem by using VBA, the programming language of the office suite.

Since I am from Romania, the official RON currency rates are published by the National Bank of Romania([BNR](https://www.bnr.ro/)) and all I had to do was to access the records.

The currency lists are grouped by years in XML files:

* [nbrfxrates2020.xml](https://www.bnr.ro/files/xml/years/nbrfxrates2020.xml)
    
* [nbrfxrates2021.xml](https://www.bnr.ro/files/xml/years/nbrfxrates2021.xml)
    
* etc..
    

I added a new module in the Visual Basic editor window(**Alt + F11**):

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1701429004186/87299707-2217-4adf-8456-9e95e247edd6.jpeg?width=318 align="center")

A reference to the Microsoft XML library is needed since we're gonna be dealing with XML file format:

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1701429015093/bbabfe3f-ef86-4aa5-a815-71287189de60.jpeg?width=491 align="center")

And here is the function that reads the XML file, searches for the given currency symbol, and returns the rate. Putting that in the `currencyModule` and we're good to go:

```basic
Public Function CURS(Data As Date, Symbol As String) As String
    '### LOAD XML
    Dim XMLDoc As MSXML2.DOMDocument60
    Set XMLDoc = New MSXML2.DOMDocument60
    XMLDoc.async = False
    XMLDoc.validateOnParse = False
    XMLDoc.SetProperty \"SelectionNamespaces\", \"xmlns:ns='http://www.bnr.ro/xsd'\"
    XMLDoc.Load (\"https://www.bnr.ro/files/xml/years/nbrfxrates\" & Year(Data) & \".xml\")

    '### CHECK DATE
    Dim currencyDate As String, currencyValue As String
    If IsDate(Data) Then
        currencyDate = Format(Data, \"yyyy-mm-dd\")
    Else
        CURS = \"#VALUE\" 'currency date is invalid
        Exit Function
    End If

    '### GET CURRENCY BY DATE
    If XMLDoc.SelectNodes(\"/ns:DataSet/ns:Body/ns:Cube[@date='\" & currencyDate & \"']/ns:Rate[@currency='\" & UCase(Symbol) & \"']\").Length > 0 Then
        currencyValue = XMLDoc.SelectNodes(\"/ns:DataSet/ns:Body/ns:Cube[@date='\" & currencyDate & \"']/ns:Rate[@currency='\" & UCase(Symbol) & \"']\").Item(0).Text
    Else
        CURS = \"#N/A\" 'currency for that date not found
        Exit Function
    End If
    CURS = currencyValue
End Function
```

Making the function **Public** makes it possible to be used inside the workbook cells, like a normal formula:

`=CURS(\\\"2021-10-01\\\",\\\"EUR\\\")`.

The [XMLDoc.SelectNodes](https://docs.microsoft.com/en-us/office/vba/api/word.xmlnode.selectnodes) function gets the XML node value that matches the XPath string, in this case:

`DataSet->Body->Cube[@date]->Rate[@currency]`

You can download the Excel file [here](https://drate.go.ro/images/articles/Currency.xlsm). Keep in mind you need to have macros enabled for it to work.
