Contents
Introduction
In our previous blog we saw how to export REST API to CSV using c# or Python. In this post we will look at specific example on How to Export REST API to MS Access using VBA Command Button, along with few other topics such as how to make REST API Call, how to read all Customers data from Odata using our ODBC JSON Driver and load it into the Ms Access Table.
We will go through the steps to read data from Odata and Load into MS Access using VBA Command Button.
In nutshell, this post will focus on how to make ODBC Driver Call using VBA.
So let’s get started.
Requirements
- First of all, you will need ZappySys ODBC PowerPack installed.
- Secondly, Make sure that Microsoft Access installed for VBA example.
An introduction to Rest API and OData
In this example, we will use OData (Open Data Protocol) to consume REST API. REST API (Representational State Transfer Application Program Interface) allows handling the interoperability between computers and the internet.
In REST API we can handle web services in different formats. In this example, we will work with the Northwind example. The Northwind example is available in this URL:
1 |
https://services.odata.org/V3/Northwind/Northwind.svc |
- By default, the data is displayed in XML format. To show the data in JSON use this URL:
1https://services.odata.org/V3/Northwind/Northwind.svc/?$format=json - There are collections of data like Categories, CustomerDemographic, Customers, Invoices, etc. For example, the following URL will show the data of the categories collection:
1https://services.odata.org/V3/Northwind/Northwind.svc/Customers?$format=json - In the next steps, we will use ZappySys drivers to connect to this URL and query using OData.
Configure ODBC DSN for ZappySys JSON Driver
ODBC driver can be accessed in two modes.
- Using DSN
- Without DSN (Supply direct Connection String e.g. DRIVER={ZappySys JSON Driver}; …….. )
In this article, we will use the DSN approach (User DSN). We will first add the ZappySys JSON Driver in the ODBC Data Source Administrator.
Follow these steps to accomplish the task:
- First, Windows search, write ODBC and select the ODBC Data sources (32 bits)
- As a second step, in ODBC Data source Administrator press the Add button.
- In this step, create the new data source, select ZappySys JSON Driver.
- Here we have several properties, write a data source name. In this example, the name will be ZappySys JSON to Excel.
- The Data Source (URL or file path) can specify the URL of the source or if it is a local file, you can specify the local path. In this example, the URL is:
1https://services.odata.org/V3/Northwind/Northwind.svc/Customers?$format=json
For multiple files: c:\data\myfile_*.json - Configure the ODBC JSON Driver like this and test the connection:
- Now click on Copy Connection string Button.
- That’s it Connection string is copied to clipboard. Now let’s use this connection string in the VBA code.
How to import REST API data to Access using VBA
- Open the access database and create the table with the desire columns to get API data in it.
- Now close the table, and go to Create menu and click on Form Design to add the new blank form in design view.
- It will open the new form in the design view, now add new button with the desire text.
- Now right click on button and go to properties and click on … builder button and select Code Builder.
- It will open the new VBA instance with the button click command event. Add the below Function also in it to check that table is open in the access or not.
123Public Function IsTableOpen(strName As String) As BooleanIsTableOpen = SysCmd(acSysCmdGetObjectState, acTable, strName)End Function - Now add the below code under the Command5_Click()
- Close Table If Open, other wise in the below command it’s throw an error.
- Truncate Table.
- Make the API call using that ODBC Driver connection string and insert into access table.
- Open Table again to view the inserted data.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354''''''''''1. Close Table If Open, other wise in the below command it's throw an errorIf IsTableOpen("tblCustomers") ThenDoCmd.SelectObject acTable, "tblCustomers"DoCmd.RunCommand acCmdSaveRecordDoCmd.CloseEnd If''''''''''2. Truncate TableDim strSql As StringstrSql = "DELETE FROM tblCustomers;"'If you have any ID auto increment Integer type column in the table'To reset the index'CurrentProject.Connection.Execute strSql'strSql = "ALTER TABLE tblCustomers ALTER Column ID INT;"'CurrentProject.Connection.Execute strSql'strSql = "ALTER TABLE tblCustomers ALTER Column ID AUTOINCREMENT;"'CurrentProject.Connection.Execute strSql''''''''''3. Make The ODBC Driver Call to get the data from API and insert into access table'Define dscn as DB connectionDim dscn As New ADODB.Connection'dscn.Open "{{Your ODBC Driver Connection String Goes here}}"dscn.Open "DRIVER={ZappySys JSON Driver};DataPath='https://services.odata.org/V3/Northwind/Northwind.svc/Customers?$format=json';Filter='$.value[*]'"'define recd as record set of table and dataDim recd As New ADODB.Recordsetrecd.Open "Select * from $", dscnWhile Not recd.EOFIf ((IsNull(recd(0)) = False) And (IsNull(recd(1)) = False)) ThenstrQuery = ""strQuery = "INSERT INTO tblCustomers (CustomerID,CompanyName,ContactName,ContactTitle,Address,City,Region,PostalCode,Country,Phone,Fax) VALUES "strQuery = strQuery & "(""" & recd!CustomerID & """, """ & recd!CompanyName & """, """ & recd!ContactName & """, """ & recd!ContactTitle & """, """ & recd!Address & """, """ & recd!City & """, """ & recd!Region & """, """ & recd!PostalCode & """, """ & recd!Country & """, """ & recd!Phone & """, """ & recd!Fax & """);"'Or'strQuery = strQuery & "(""" & recd(0) & """, """ & recd(1) & """, """ & recd(2) & """, """ & recd(3) & """, """ & recd(4) & """, """ & recd(5) & """, """ & recd(6) & """, """ & recd(7) & """, """ & recd(8) & """, """ & recd(9) & """, """ & recd(10) & """)"CurrentProject.Connection.Execute strQueryEnd Ifrecd.MoveNextWend''''''''''4. Open Table again to view the insrted dataIf IsTableOpen("tblCustomers") = False ThenDoCmd.OpenTable ("tblCustomers")End If''''''''''Refresh the Table if Open'DoCmd.SelectObject acTable, "tblCustomers"'DoCmd.Requery'DoCmd.GoToRecord acDataTable, "tblCustomers", acLast''''''''''Show Message after loading data SuccessfullyMsgBox ("Customers Data Loaded Successfully!")dscn.Close - Now save the VBA form code and go to Access.
- And open the form and click on the command button to load the data.
- It will throw the below error if MS ActiveX reference is not added.
- So now add the Microsoft ActiveX Data Objects X.0 Library reference in the project.
- That’s it now again click on the the command button and it will make rest api call, insert the data in the access table and open the table to view the inserted records with success message.
Troubleshooting Errors
While running in Access\Excel\other and reading data from DSN created with ODBC PowerPack, if you get this error "License type [ODBC_PP_TRIAL] not found or its expired"
Please refer to this article for the same: Troubleshooting "License type [ODBC_PP_TRIAL] not found or its expired" error in Microsoft Access
Conclusion
In this article, we saw how to use VBA to call REST API. We show how to do REST API calls in Access using the ZappySys ODBC driver. Also, we show how to write VBA Code in MS Access for command button to make REST API call, truncate access table and insert record in the access table using VBA code. If you liked this article and you want to try, you can download the ZappySys ODBC installer here.