In this article, we will learn how to perform the How can you extract a nested JSON value in VBA Excel using VBA-Json Parse Nested Json package.
In this article, I will explain to you a step-by-step for performing Parsing complex JSON Data using VBA JSON in Excel VBA.
You can download the source code at the bottom of the post
Recently I’m working on a Excel VBA project in which I need to call the rest and parse the json response. I google this question and but can’t find any good article which covers this topic with complex json response. so that I decided to write an article on Parsing Nested Arrays using VBA and JSON.
VBA Excel doesn’t have a built JSON parser for us , that’s why are going to use VBA-tools JSON parser package to parse the JSON that we receive after making a rest api calll.
Go to the GitHub link : https://github.com/VBA-tools/VBA-JSON
and download code.
And open your Excel sheet and go to the developer tool and visual basic and then import the JSON converter that we download from Github.
Go to File and click on Import file and naviate to the folder that and select the JsonConverter.bas And click on Open.
So now go back to the visual basic IDE and click on Tools and select references and Microsoft scripting runtime references in our project.
So let write code for parsing json.
Simple Json Parsing Example
Private Sub ParseSimpleJson() Dim JsonObject As Object Dim strResponse As String strResponse = "{""name"": ""johny"", ""address"": { ""country"": ""USA"",""city"": ""New York City"" } }" Set JsonObject = JsonConverter.ParseJson(strResponse) MsgBox ("User name :" & JsonObject("name") & " User Country: " & JsonObject("address")("country")) End Sub
1. Parsing Nested Arrays using VBA and JSON
Sample json
{ "apidata": { "success": true, "data": { "music_events": { "Magic": { "users": ["Tayler", "Ally"], "event_status": "Pending", "event_sites": { "ticketbet": { "odds": { "h2h": ["1.86", "1.99"] }, "last_update": 1488956952 }, "stream411": { "odds": { "h2h": ["1.70", "2.10"] }, "last_update": 1488957101 }, "darkmusic": { "odds": { "h2h": ["1.83", "1.98"] }, "last_update": 1488957104 }, "lastride": { "odds": { "h2h": ["1.83", "2.00"] }, "last_update": 1488957115 } } } } } } }
Our goal is to get the music_events, users details into table and the event_sites data into a separate table.
VBA Code for parsing above json
Private Sub ParseNestedJson() Dim JsonObject As Object Dim strResponse As String Dim music_events, k, users, v, event_sites strResponse = Sheet1.Range("A1").Value Set JsonObject = JsonConverter.ParseJson(strResponse) Set music_events = JsonObject("apidata")("data")("music_events") For Each k In music_events Debug.Print "event", k Set users = music_events(k)("users") For Each v In users Debug.Print , "participant", v Next v Set event_sites = music_events(k)("event_sites") For Each v In event_sites Debug.Print , "site", v Next v Next 'MsgBox ("User name :" & JsonObject("name") & " User Country: " & JsonObject("address")("country")) End Sub
2. Parsing complex JSON Data using VBA JSON
Sample Json
{ "UniqueId": "{344DSD-343-34D-343-23SDSDSD}", "from": "2021-01-16", "to": "2021-01-22", "data": [ { "date": "2021-01-16", "person": "{34343DS-343-3434-343-SFDSS343}", "personName": "Rohit Smith", "company": "{SDSD344-343-343-343-3FDFDFD}", "companyName": "Appsloveworld pvt ltd", "minutes": "400", "task": [ { "name": "Training", "code": "TRN", "minutes": "120" }, { "name": "Human Resources", "code": "HR", "minutes": "150" }, { "name": "Yoga", "code": "YG", "minutes": "15" }, { "name": "Lunch", "code": "", "minutes": "30" } ] } ] }
There may be any number of ‘data’ records, as well as any number of ‘tasks’ within each “data” including zero.
we want a row in the spreadsheet for each activity, with the task name and other data outputted next to that day’s task.
VBA Code for that
Sub NestedJsonExample() Dim ts, act Dim Json As Object, c As Range, strResponse As String 'reading json from a worksheet cell... strResponse = Sheet1.Range("B1").Value Set Json = JsonConverter.ParseJson(strResponse) Set c = ActiveSheet.Range("C5") 'loop over timesheets For Each ts In Json("data") 'loop over timesheet activities For Each act In ts("task") c.Resize(1, 11).Value = Array(Json("UniqueId"), Json("from"), Json("to"), _ ts("date"), ts("personName"), ts("companyName"), _ ts("minutes"), act("name"), act("code"), _ act("minutes")) Set c = c.Offset(1, 0) Next act Next ts End Sub
Some information Regarding VBA
Excel VBA is the programming language of Microsoft Excel like for Microsoft Office projects like Word and PowerPoint.
VBA is the truncation for Visual Basic for Applications. It is an occasion driven programming language from Microsoft. Which is currently fundamentally utilized with Microsoft Office applications like MS-Excel, MS-Word and MS-Access. It helps in the making of tweaked applications and their answers, which improve the abilities of those applications. The benefit of this component is that we don’t have to introduce Visual Basic on our PC yet introducing Office assists us with accomplishing our target.
We can utilize VBA in all renditions of Office from MS Office 97 to MS Office 2013. You can likewise explore different avenues regarding other present day forms of Office that are accessible with them. Dominate VBA is the most famous of all VBA and the benefit of utilizing VBA is that we can assemble an amazing asset utilizing Linear Programming.
Visual Basic is a programming language that accompanies a coordinated advancement climate. Planned by Microsoft, the Visual Basic download makes coding a basic and pleasant experience. Reasonable for all clients, including fledglings and specialists, this language is object-driven and gives you admittance to sentence structure developments and an information base of components. You can fabricate a scope of Windows applications and front-end frameworks.
What is Windows Visual Basic?
Visual Basic is an article driven improvement climate and PC programming language made by Microsoft. The framework gives a graphical UI that permits them to alter the code by relocating components, permitting clients to change the appearance and conduct of the application. The article arranged language depends on BASIC and is considered appropriate for amateurs to code.
Microsoft expected to improve on the language and backing quicker coding. That is the reason it is known as RAD or Rapid Application Development System. With its assistance, coders can model applications prior to thinking of them in a more effective however troublesome dialect. What’s more, Virtual Basic likewise gives punctuation that is more clear and data set associated.
The post Simple way to Parse JSON with Excel VBA appeared first on Software Development | Programming Tutorials.
Read More Articles
- Excel VBA macro using iTunes search API - fastest way to query & parse JSON results
- How to parse JSON with VBA without external libraries?
- JSON VBA Parse to Excel
- Parse JSON with VBA (Access 2010)
- Quickest Way to open an excel file with VBA
- Excel VBA throws overflow error with a simple division
- Simple way to refresh power pivot from VBA in Excel 2010?
- Excel VBA Arrays: Is there a simple way to delete a dataset by the index?
- Parse simple two dimensional JSON array in VBA without external libraries
- MS Excel 2003 - Simple unselect question in Excel VBA when dealing with shapes
- Best way to distribute Excel spreadsheet with VBA
- Simple recursive function in VBA with Excel not returning expected result
- Fastest way of Parsing Json to Excel using VBA
- Is there a simple way to parse comma separated Key:Value pairs in Excel, Power Query or VBA if the values contain unescaped commas?
- parse a string with VBA on EXCEL
- Parse local webpages with Selenium in VBA Excel fails
- How can I parse json in Excel vba without using microsoft scripting runtime?
- How to fix and extract google CSE JSON API results with excel vba
- Using VBA in Excel to retrieve a Json from an API (problem with the API password)
- VBA Json Parse response with JsonConverter
- Parsing Google Books JSON to obtain book info by entering ISBN in EXCEL with VBA
- Review my simple VBA script with built-in Excel function
- Excel VBA out of memory error with simple line of code
- get data from a JSON string with VBA Excel
- Best way to get column totals on multiple columns with varying row sizes using MS Excel VBA
- Faster Way to copy files from one folder to another with Excel VBA
- VBA code in excel operates inconsistently with very simple code
- VBA Excel - Problems with a simple macro to auto-fill cells for a budgeting spreadsheet I'm attempting to make
- excel to json with vba
- With Excel VBA is there a way to copy an entire worksheet's NumberFormat to a new worksheet?
- How can I force Excel to place Sigma Values pivot field into the Columns Label using VBA code?
- Highlight row range if column value is greater than zero
- Automating selection of radio buttons in web form filling through vba
- button that will hide and unhide row one at a time. Something similar to spin button
- VBA CountIf external document
- Excel Custom List to sort PivotTable PivotFields (Columns)
- 3134 run time error on Insert into statement
- Copying Multiple Cells based on a criteria and printing all of them onto one cell
- ActiveX control Blocks Me.Saved=True
- List all unique values based on criterias
- Record delimiter in NACHA file format?
- Loop through worksheets while exporting range as image
- Excel VBA: Application-defined or object-defined error when setting a cell formula
- Conditional average of array in Excel VB
- For Each loop error VBA
- ByRef argument type mismatch error raised when I change location of Dim statement
- Running R script in VBA Wrong Directory
- Excel VBA Array from Range Starting at -1 rather than 0
- Regex - how to test for 2 str patterns and make replacements based on which str pattern matches
- Macro for Loop through outlook unread emails