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.
- When you click the button, it will open a new VBA instance, executing the command event associated with that button click.
Next, insert the provided code inside the Command5_Click() function. In this example, the button is named Command5, and that’s why it’s added within this click function.
The provided code encompasses the following steps:- Ensure the table is closed:
It’s crucial to close the table beforehand; otherwise, executing the subsequent command may result in an error. - Truncate the table:
Clear the existing data from the table. If you want to add fresh data each time - Make the API call:
Utilize the ODBC Driver connection string to initiate an API call. - Insert into the Access table:
Use the retrieved data from the API call to insert new records into the Access table. - Open the table:
Reopen the table to inspect the newly inserted data.
123456789101112131415161718192021222324252627' Pass your ZappySys Driver Connection String: Refer to below link to learn how to obtain the ZappySys Driver connection string:' https://community.zappysys.com/t/how-to-copy-the-zappysys-driver-connection-string/172Dim zsConnStr As StringzsConnStr = "DRIVER={ZappySys JSON Driver};DataPath='https://services.odata.org/V3/Northwind/Northwind.svc/Customers?$format=json';Filter='$.value[*]';IncludeParentColumns=0;RequestMethod='GET';RequestHeaders='cache-control: no-cache || Accept: */*'"'ZappySys Driver QueryDim zsDriverQuery As StringzsDriverQuery = "Select * from $"'MS Access Table NameDim tableName As StringtableName = "tblCustomers"' 1. Close Table If OpenCloseTableIfOpen tableName' 2. Truncate Table (Optional): If you want to load fresh data each time, uncomment the line below.'TruncateTable tableName' 3. Import Data From API Into TableImportDataFromAPIIntoTable zsConnStr, zsDriverQuery, tableName' 4. Open Table for Viewing (Optional)OpenTableForViewing tableName' Show Message after Loading Data SuccessfullyMsgBox "Data Loaded Successfully!" - Ensure the table is closed:
- Below the Private Sub Command5_Click() function, please add the necessary functions and procedures as provided below:
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091Sub ImportDataFromAPIIntoTable(zsConnStr As String, zsDriverQuery As String, tableName As String)Dim dscn As New ADODB.Connectiondscn.Open zsConnStrDim rs As ObjectSet rs = New ADODB.Recordset''ZappySys Driver Query Goes herers.Open zsDriverQuery, dscnDim strQuery As StringstrQuery = ""' Check if the recordset is not emptyIf Not rs.EOF Then' Get the field namesDim fieldNames As StringfieldNames = ""For i = 1 To rs.Fields.CountfieldNames = fieldNames & rs.Fields(i - 1).NameIf i < rs.Fields.Count ThenfieldNames = fieldNames & ","End IfNext i' Generate the INSERT scriptDim insertScript As String' Iterate through the recordset to get the valuesDo Until rs.EOF' Generate Insert scriptinsertScript = "INSERT INTO " & tableName & " (" & fieldNames & ") VALUES"insertScript = insertScript & vbCrLf & "("For i = 1 To rs.Fields.Count' Assuming all fields are text, you might need to handle different data types appropriatelyIf IsNull(rs.Fields(i - 1).Value) TheninsertScript = insertScript & "''"ElseinsertScript = insertScript & "'" & EscapeSingleQuote(rs.Fields(i - 1).Value) & "'"End IfIf i < rs.Fields.Count TheninsertScript = insertScript & ","End IfNext iinsertScript = insertScript & ")"'Insert dataCurrentProject.Connection.Execute insertScriptrs.MoveNextLoopEnd If' Close the recordset and connectionrs.Closedscn.CloseSet rs = NothingSet conn = NothingEnd SubSub OpenTableForViewing(tableName As String)If Not IsTableOpen(tableName) ThenDoCmd.OpenTable tableNameEnd IfEnd SubPublic Function IsTableOpen(strName As String) As BooleanIsTableOpen = SysCmd(acSysCmdGetObjectState, acTable, strName)End FunctionSub CloseTableIfOpen(tableName As String)If IsTableOpen(tableName) ThenDoCmd.SelectObject acTable, tableNameDoCmd.RunCommand acCmdSaveRecordDoCmd.CloseEnd IfEnd SubSub TruncateTable(tableName As String)Dim strSql As StringstrSql = "DELETE FROM " & tableName & ";"CurrentProject.Connection.Execute strSqlEnd SubPublic Function EscapeSingleQuote(strData As String) As StringEscapeSingleQuote = Replace(strData, "'", "''")End Function
- Now, save the VBA form code and provide some appropriate form names.
- Make sure to add the reference to the Microsoft ActiveX Data Objects X.0 Library in the project settings.In Microsoft Access VBA,
You can add the reference to the Microsoft ActiveX Data Objects X.0 Library by following these steps:- In the VBA editor, go to “Tools” in the menu and select “References.”
- In the References dialog box, scroll down the list to find “Microsoft ActiveX Data Objects X.0 Library” (where “X.0” corresponds to the version number, such as 6.1, 2.8, etc.).
- Check the box next to the appropriate version to enable the reference.
- Click “OK” to save the changes and close the References dialog box.
Now, your Access project has a reference to the Microsoft ActiveX Data Objects library, and you can use its features in your VBA code.
If the MS ActiveX reference is not added, an error will be thrown.
- Close the code project, open the form in Form View, and click on the button.
- After clicking the button, it will initiate a REST API call, insert the data into the Access table, and open the table to display the inserted records along with a 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.
References
- ZappySys ODBC installer.
- Access ODBC Query
- Using ADO with Microsoft Visual Basic and Visual Basic for Applications
Form VBA Code:
After completing the migration of the higher-level VBA code, you’ll notice a transformation in the structure of your forms’ code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 |
Option Compare Database Private Sub Command5_Click() ' Pass your ZappySys Driver Connection String: Refer to below link to learn how to obtain the ZappySys Driver connection string: ' https://community.zappysys.com/t/how-to-copy-the-zappysys-driver-connection-string/172 Dim zsConnStr As String zsConnStr = "DRIVER={ZappySys JSON Driver};DataPath='https://services.odata.org/V3/Northwind/Northwind.svc/Customers?$format=json';Filter='$.value[*]';IncludeParentColumns=0;RequestMethod='GET';RequestHeaders='cache-control: no-cache || Accept: */*'" 'ZappySys Driver Query Dim zsDriverQuery As String zsDriverQuery = "Select * from $" 'MS Access Table Name Dim tableName As String tableName = "tblCustomers" ' 1. Close Table If Open CloseTableIfOpen tableName ' 2. Truncate Table (Optional): If you want to load fresh data each time, uncomment the line below. 'TruncateTable tableName ' 3. Import Data From API Into Table ImportDataFromAPIIntoTable zsConnStr, zsDriverQuery, tableName ' 4. Open Table for Viewing (Optional) OpenTableForViewing tableName ' Show Message after Loading Data Successfully MsgBox "Data Loaded Successfully!" End Sub Sub ImportDataFromAPIIntoTable(zsConnStr As String, zsDriverQuery As String, tableName As String) Dim dscn As New ADODB.Connection dscn.Open zsConnStr Dim rs As Object Set rs = New ADODB.Recordset ''ZappySys Driver Query Goes here rs.Open zsDriverQuery, dscn Dim strQuery As String strQuery = "" ' Check if the recordset is not empty If Not rs.EOF Then ' Get the field names Dim fieldNames As String fieldNames = "" For i = 1 To rs.Fields.Count fieldNames = fieldNames & rs.Fields(i - 1).Name If i < rs.Fields.Count Then fieldNames = fieldNames & "," End If Next i ' Generate the INSERT script Dim insertScript As String ' Iterate through the recordset to get the values Do Until rs.EOF ' Generate Insert script insertScript = "INSERT INTO " & tableName & " (" & fieldNames & ") VALUES" insertScript = insertScript & vbCrLf & "(" For i = 1 To rs.Fields.Count ' Assuming all fields are text, you might need to handle different data types appropriately If IsNull(rs.Fields(i - 1).Value) Then insertScript = insertScript & "''" Else insertScript = insertScript & "'" & EscapeSingleQuote(rs.Fields(i - 1).Value) & "'" End If If i < rs.Fields.Count Then insertScript = insertScript & "," End If Next i insertScript = insertScript & ")" 'Insert data CurrentProject.Connection.Execute insertScript rs.MoveNext Loop End If ' Close the recordset and connection rs.Close dscn.Close Set rs = Nothing Set conn = Nothing End Sub Sub OpenTableForViewing(tableName As String) If Not IsTableOpen(tableName) Then DoCmd.OpenTable tableName End If End Sub Public Function IsTableOpen(strName As String) As Boolean IsTableOpen = SysCmd(acSysCmdGetObjectState, acTable, strName) End Function Sub CloseTableIfOpen(tableName As String) If IsTableOpen(tableName) Then DoCmd.SelectObject acTable, tableName DoCmd.RunCommand acCmdSaveRecord DoCmd.Close End If End Sub Sub TruncateTable(tableName As String) Dim strSql As String strSql = "DELETE FROM " & tableName & ";" CurrentProject.Connection.Execute strSql End Sub Public Function EscapeSingleQuote(strData As String) As String EscapeSingleQuote = Replace(strData, "'", "''") End Function |