Excel vba json api

Excel is probably one of the most used tools in this world, so the demand for integrations with extremely complex spreadsheets is a recurring scenario. APIs allow easy access to information in systems, which is becoming more and more standard in the market, with that in mind, some demands of connecting to systems via API in Excel are necessary and very useful, so I decided to share a little how I created this integration. Let’s learn how to query Rest APIs using VBA and convert the result to JSON for use in the spreadsheet.

This article hopes you will know the basics of Excel and VBA, as well as what is an API and how it works . Our goal will be to consult a Public Pokemon API and list the result in the tab results .

Creating a blank worksheet

First let’s create a blank sheet with macro enabled, inside it I’ll create a tab called results .

Excel spreadsheet

Creating the macro to query the API

by shortcut alt + f11 let’s open the Excel macro editor, and create a module called list pokemons .

Macro VBA

Importing the VBA-JSON library

As the API we’re going to query returns a JSON as an answer we will need to import the library VBA JSON , it will take care of all the boring work of translating the JSON and returning as an array and object. Installation is very simple, just download the latest version here and in the macro editor go to File > Import File > JsonConverter.bas .

Import VBA JSON

Enabling Microsoft Scripting Runtime

We also need to enable Microsoft Scripting Runtime, to do this just browse Tools > References and search and enable in the list the Microsoft Scripting Runtime .

Excel API Rest Microsoft Scripting Runtime

Creating the VBA macro to query the REST API

Below is the complete code for our request, it might sound scary, but don’t worry, I’ll explain what each part is doing:

Sub listPokemons()
Dim json As String
Dim jsonObject As Object, item As Object
Dim i As Long
Dim ws As Worksheet
Dim objHTTP As Object

'We selected our results sheet
Set ws = Worksheets("results")

'We create our request object and send
Set objHTTP = CreateObject("WinHttp.WinHttpRequest.5.1")
URL = "https://pokeapi.co/api/v2/pokemon"
objHTTP.Open "GET", URL, False
objHTTP.Send
strResult = objHTTP.responseText
json = strResult

Set objectJson = JsonConverter.ParseJson(json)

'We create the header cells
ws.Cells(1, 1) = "name"
ws.Cells(1, 2) = "link"

'We loop the results property of the API response
i = 2 'We will start the counter on line 2
For Each pokemon InJsonObject("results")
    ws.Cells(i, 1) = pokemon("name")
    ws.Cells(i, 2) = pokemon("url")
    i = i + 1
next

End Sub

First we define all the variables that we will use in our scripts, including the VBA JSON library import that we previously imported into our project.

Dim json As String
Dim jsonObject As Object, item As Object
Dim i As Long
Dim ws As Worksheet
Dim xmlhttp As Object
Set xmlhttp = CreateObject("MSXML2.serverXMLHTTP")
Dim objHTTP As Object

Then we select the spreadsheet we want to display the results of the API query, in our case Worksheets("results") and then we create an object that will allow us to make the request to the API. https://pokeapi.co/api/v2/pokemon . We’ll take the answer and put it in the variable json , for now it is nothing more than a text.

'We selected our results sheet
Set ws = Worksheets("results")

'We create our request object and send
Set objHTTP = CreateObject("WinHttp.WinHttpRequest.5.1")
URL = "https://pokeapi.co/api/v2/pokemon"
objHTTP.Open "GET", URL, False
objHTTP.Send
strResult = objHTTP.responseText
json = strResult

Here where the magic happens, the function parsejson from the VBA JSON library converts the text of our variable json for an accessible object in our script. We are now able to access all properties programmatically in our code.

Set objectJson = JsonConverter.ParseJson(json)

Now that we have the result of our API accessible, we create in the first row of the spreadsheet the header containing the columns Name and link .

'We create the header cells
ws.Cells(1, 1) = "name"
ws.Cells(1, 2) = "link"

Now before analyzing the script we need to understand the result of the API. If you open the link https://pokeapi.co/api/v2/pokemon in your browser you will see the following result:

{
  "count": 964,
  "next": "https://pokeapi.co/api/v2/pokemon?offset=20&limit=20",
  "previous": null,
  "results": [
    {
      "name": "bulbasaur",
      "url": "https://pokeapi.co/api/v2/pokemon/1/"
    },
    {
      "name": "ivysaur",
      "url": "https://pokeapi.co/api/v2/pokemon/2/"
    },
    {
      "name": "venusaur",
      "url": "https://pokeapi.co/api/v2/pokemon/3/"
    },
    {
      "name": "charmander",
      "url": "https://pokeapi.co/api/v2/pokemon/4/"
    },
    {
      "name": "charmeleon",
      "url": "https://pokeapi.co/api/v2/pokemon/5/"
    },
    {
      "name": "charizard",
      "url": "https://pokeapi.co/api/v2/pokemon/6/"
    },
    {
      "name": "squirtle",
      "url": "https://pokeapi.co/api/v2/pokemon/7/"
    },
    {
      "name": "wartortle",
      "url": "https://pokeapi.co/api/v2/pokemon/8/"
    },
    {
      "name": "blastoise",
      "url": "https://pokeapi.co/api/v2/pokemon/9/"
    },
    {
      "name": "caterpie",
      "url": "https://pokeapi.co/api/v2/pokemon/10/"
    },
    {
      "name": "metapod",
      "url": "https://pokeapi.co/api/v2/pokemon/11/"
    },
    {
      "name": "butterfree",
      "url": "https://pokeapi.co/api/v2/pokemon/12/"
    },
    {
      "name": "weedle",
      "url": "https://pokeapi.co/api/v2/pokemon/13/"
    },
    {
      "name": "kakuna",
      "url": "https://pokeapi.co/api/v2/pokemon/14/"
    },
    {
      "name": "beedrill",
      "url": "https://pokeapi.co/api/v2/pokemon/15/"
    },
    {
      "name": "pidgey",
      "url": "https://pokeapi.co/api/v2/pokemon/16/"
    },
    {
      "name": "pidgeotto",
      "url": "https://pokeapi.co/api/v2/pokemon/17/"
    },
    {
      "name": "pidgeot",
      "url": "https://pokeapi.co/api/v2/pokemon/18/"
    },
    {
      "name": "rattata",
      "url": "https://pokeapi.co/api/v2/pokemon/19/"
    },
    {
      "name": "raticate",
      "url": "https://pokeapi.co/api/v2/pokemon/20/"
    }
  ]
}

We are interested in the property. results , an array containing a list of pokemons with their names and links to more details. We will access this matrix at jsonobject("results") and we will loop to display each pokemon result in a new row of our table.

'We loop the results property of the API response
i = 2 'We will start the counter on line 2
For Each pokemon InJsonObject("results")
    ws.Cells(i, 1) = pokemon("name")
    ws.Cells(i, 2) = pokemon("url")
    i = i + 1
next

If everything goes as expected, by pressing f5 to run our macro, in your spreadsheet you should see the following result:

Excel API Rest

Conclusion

This was a very simple example of a query, with the object of HT TP it is possible to perform all types of requests, GET, POST, UPDATE, … The interesting thing is to understand how the request is made and how you can display the result, thanks to the VBA JSON library, which already drastically reduces the work required. Now you just need to adapt this flow and script to your needs.

3.7
6
votos

Nota do Artigo

VBA-JSON

JSON conversion and parsing for VBA (Windows and Mac Excel, Access, and other Office applications).
It grew out of the excellent project vba-json,
with additions and improvements made to resolve bugs and improve performance (as part of VBA-Web).

Tested in Windows Excel 2013 and Excel for Mac 2011, but should apply to 2007+.

  • For Windows-only support, include a reference to «Microsoft Scripting Runtime»
  • For Mac and Windows support, include VBA-Dictionary

Donate

Examples

Dim Json As Object
Set Json = JsonConverter.ParseJson("{""a"":123,""b"":[1,2,3,4],""c"":{""d"":456}}")

' Json("a") -> 123
' Json("b")(2) -> 2
' Json("c")("d") -> 456
Json("c")("e") = 789

Debug.Print JsonConverter.ConvertToJson(Json)
' -> "{"a":123,"b":[1,2,3,4],"c":{"d":456,"e":789}}"

Debug.Print JsonConverter.ConvertToJson(Json, Whitespace:=2)
' -> "{
'       "a": 123,
'       "b": [
'         1,
'         2,
'         3,
'         4
'       ],
'       "c": {
'         "d": 456,
'         "e": 789  
'       }
'     }"
' Advanced example: Read .json file and load into sheet (Windows-only)
' (add reference to Microsoft Scripting Runtime)
' {"values":[{"a":1,"b":2,"c": 3},...]}

Dim FSO As New FileSystemObject
Dim JsonTS As TextStream
Dim JsonText As String
Dim Parsed As Dictionary

' Read .json file
Set JsonTS = FSO.OpenTextFile("example.json", ForReading)
JsonText = JsonTS.ReadAll
JsonTS.Close

' Parse json to Dictionary
' "values" is parsed as Collection
' each item in "values" is parsed as Dictionary
Set Parsed = JsonConverter.ParseJson(JsonText)

' Prepare and write values to sheet
Dim Values As Variant
ReDim Values(Parsed("values").Count, 3)

Dim Value As Dictionary
Dim i As Long

i = 0
For Each Value In Parsed("values")
  Values(i, 0) = Value("a")
  Values(i, 1) = Value("b")
  Values(i, 2) = Value("c")
  i = i + 1
Next Value

Sheets("example").Range(Cells(1, 1), Cells(Parsed("values").Count, 3)) = Values

Options

VBA-JSON includes a few options for customizing parsing/conversion if needed:

  • UseDoubleForLargeNumbers (Default = False) VBA only stores 15 significant digits, so any numbers larger than that are truncated.
    This can lead to issues when BIGINT’s are used (e.g. for Ids or Credit Cards), as they will be invalid above 15 digits.
    By default, VBA-JSON will use String for numbers longer than 15 characters that contain only digits, use this option to use Double instead.
  • AllowUnquotedKeys (Default = False) The JSON standard requires object keys to be quoted (" or '), use this option to allow unquoted keys.
  • EscapeSolidus (Default = False) The solidus (/) is not required to be escaped, use this option to escape them as / in ConvertToJson.
JsonConverter.JsonOptions.EscapeSolidus = True

Installation

  1. Download the latest release
  2. Import JsonConverter.bas into your project (Open VBA Editor, Alt + F11; File > Import File)
  3. Add Dictionary reference/class
    • For Windows-only, include a reference to «Microsoft Scripting Runtime»
    • For Windows and Mac, include VBA-Dictionary

Resources

  • Tutorial Video (Red Stapler)

16 Aug How to Import JSON to Excel Using VBA

Posted at 13:26h
in Excel VBA
12 Comments

Howdee! It’s becoming increasingly more common for data to be generated in a JSON format as opposed to XML. XML was widely used for years, but recently JSON has started to become the preferred method of data exchange. Many REST APIs have the option to return both but the majority that I interact with default to returning JSON formatted data. Therefore, as excel ninjas, it’s important to understand how to import JSON to Excel for analysis. Before we begin on that route, let’s take a quick moment to talk about what JSON is for those that aren’t familiar with it.

Curious how to do this in VSTO? Click Here!

What is JSON?

JSON stands for JavaScript Object Notation and is a lightweight data-interchange format. In layman’s terms, it is a string of text that represents a universal data structure. It is easy for humans to read (when formatted properly) and, because of the universal structure, it is very easy and fast for machines to parse and generate. It’s made simple because JSON, at it’s most basic, is only two data types. It is made up of objects, or arrays, or a combination of both. Objects are made up of key/value pairs (often called a dictionary) and arrays are simply collections of values or objects separated by a comma.

It’s important to note that object/dictionary and array are the terminology applicable to the .NET language. Other languages might have other terminology such as hash table for object, or vector for an array. This site gives a great high level, cross-language overview of JSON.

JSON Object

A JSON object always begins with { and ends with }. The key is separated from its value with a colon (“:”). The key/value pairs will then be separated by commas all within the curly brackets. In the image below, the first key “color” corresponds to its value “red”, while the second key “value” corresponds to the red hex code “#f00”. Hopefully you can see why this might be called a dictionary as you look up the key (word to define) to get its value (definition of the word).

import json to excel

JSON Array

A JSON array, in its simplest form, is a list of values separated by a comma that begins with [ and ends with ]. In the below image, the JSON array is a list of string data points. We can see that they are colors but there is no key in this example explicitly telling that this string represents a color. Therefore, JSON is most commonly seen as a combination of arrays and objects.

import json to excel

JSON Objects & Arrays Together

Most of the time, JSON is returned as an array of objects. If you recall, an object always begins and ends with curly brackets. Therefore, the array of objects would have several objects enclosed in curly brackets that are separated by commas and all objects are enclosed in normal brackets (the array). That looks like this image:

import json to excel

In this example, each object represents a color and its corresponding hex code. In Excel, this would likely be two columns of data. One column for color, and the other for its hex code value. Now that you’re more familiar with JSON data structure, let’s learn how to import JSON to Excel!

Setup JSON to Excel

There are several libraries out there to help you import JSON to Excel. The most popular of these is VBA-JSON which is available here on GitHub. This library will do most of the hard work of parsing the JSON string to a dictionary for you and then you can write the values to an excel worksheet. When you download the latest release, you’ll need to import the “JsonConverter.bas” file to your VBA project. This GIF shows how that is accomplished. You will also need to add a  reference to the “Microsoft Scripting Runtime” by clicking tools from the ribbon, selecting references and checking the box for Microsoft Scripting Runtime as shown in the screen grab.

Once you have completed both steps, insert a new module into your project and title it whatever you like. To get started, we need to dimension some variables to use later.

Dim ws As Worksheet
Dim jsonText As String
Dim jsonObject As Object

The ws variable will represent a worksheet in excel. In this example, we will use this worksheet to both read in our JSON string from and write the parsed JSON to Excel. To assign a worksheet to this variable, set it like this:

Set ws = Worksheets("JSON to Excel Example")

The jsonText variable will represent our string of valid JSON data. For this example, I’ve pasted that string of colors and hex codes we looked at earlier into cell A1 on the JSON to Excel Example tab. To assign that string to a variable, type this code:

jsonText = ws.Cells(1, 1)

This step is not necessary for the code to work for us. We could simply reference the cell in the worksheet that contains the JSON. However, most of the time you’ll be returning your JSON string from another data source, most likely a HTTP GET Web Call. If you’re not familiar with HTTP Requests in VBA, click here to learn more.

Lastly, to put the JSON string into the jsonObject, we will use one of the methods contained in the JsonConverter file you imported to begin this example. Since the builder of this library made all of the subroutines public, it is callable from the module this code is in. That call looks like this:

Set jsonObject = JsonConverter.ParseJson(jsonText)

This call instructs the JsonConverter module to parse the JSON string you’ve passed it using the jsonText variable to a collection of dictionaries that we can now access. Now that we’ve finished our setup, we can start learning to import JSON to Excel in the next section.

Import JSON to Excel

The code to import JSON to Excel might sound daunting, but it is much easier than it sounds. At a high level, all you have to do is loop through the jsonObject you’ve created, and write each dictionary value to the sheet. The wonderful thing about dictionaries, is this is easy to do with a for each loop. I’ve added a couple of variables and a for each loop to our code and the result is this:

Sub JsonToExcelExample()
Dim jsonText As String
Dim jsonObject As Object, item As Object
Dim i As Long
Dim ws As Worksheet

Set ws = Worksheets("JSON to Excel Example")

jsonText = ws.Cells(1, 1)

Set jsonObject = JsonConverter.ParseJson(jsonText)

i = 3

ws.Cells(2, 1) = "Color"
ws.Cells(2, 2) = "Hex Code"

For Each item In jsonObject
    ws.Cells(i, 1) = item("color")
    ws.Cells(i, 2) = item("value")
    i = i + 1
Next

End Sub

I set a counter variable, i, that I can use to tell the loop which row to write the data to. Next, create my column headers for the data. Then, for each “item” in the jsonObject write that dictionaries values to the cell row I indicate and increment my counter variable. That’s it! The results of our import JSON to Excel code looks like this:

import json to excel

As you can see, we’ve turned that odd-looking string of text in cell A1 to an easy to understand table of data with just a few lines of code!

Understanding JSON to Excel (Advanced)

Now, I do want to point out that understanding the structure of the JSON you’ll be parsing is very important. Within the for each loop, the code can access the value of each object by referencing its key. This goes back to understanding the key/value pair relationship of JSON and the dictionary structure to which it is parsed. The reason I stress this so much is because, when you’re pulling back more complex looking JSON, you may need to have multiple levels of dictionary references to access the value you want. There may also be times when you have to nest for loops when you have an array of objects with arrays of objects nested inside each object.

For example, let’s look at an example where the JSON is structured as a single object with key “data” and the value is an array of data about employee’s and their organizations:

import json to excel

As you can see, we have an object with an array nested inside. Some objects in the array contains other nested objects as well. This multi-tiered data structure is very common when pulling data from a REST service and was very confusing to me when I first began trying to import JSON to Excel. Let’s examine what the code looks like for this scenario before we dive any deeper.

Sub JsonToExcelAdvancedExample()
Dim jsonText As String
Dim jsonObject As Object, item As Object
Dim i As Long
Dim ws As Worksheet

Set ws = Worksheets("JSON to Excel Advanced Example")

jsonText = ws.Cells(1, 1)

Set jsonObject = JsonConverter.ParseJson(jsonText)

i = 3

ws.Cells(2, 1) = "id"
ws.Cells(2, 2) = "Name"
ws.Cells(2, 3) = "Username"
ws.Cells(2, 4) = "Email"
ws.Cells(2, 5) = "Street Address"
ws.Cells(2, 6) = "Suite"
ws.Cells(2, 7) = "City"
ws.Cells(2, 8) = "Zipcode"
ws.Cells(2, 9) = "Phone"
ws.Cells(2, 10) = "Website"
ws.Cells(2, 11) = "Company"

For Each item In jsonObject("data")
    ws.Cells(i, 1) = item("id")
    ws.Cells(i, 2) = item("name")
    ws.Cells(i, 3) = item("username")
    ws.Cells(i, 4) = item("email")
    ws.Cells(i, 5) = item("address")("street")
    ws.Cells(i, 6) = item("address")("suite")
    ws.Cells(i, 7) = item("address")("city")
    ws.Cells(i, 8) = item("address")("zipcode")
    ws.Cells(i, 9) = item("phone")
    ws.Cells(i, 10) = item("website")
    ws.Cells(i, 11) = item("company")("name")
    i = i + 1
Next

End Sub

The code overall is the exact same, just referencing a different tab and added more fields to pull out. The change I want to point out is to the for loop itself. The beginning of the for loop now starts by referencing the overall object that contains the array. This is referred to as the “root” of the JSON and you’ll see it if you’re querying a REST API for JSON data. This moves the for each loop inside the “data” level of the JSON and will now loop through all objects in the highest-level array. Had I left this out, the loop would only occur once as the JSON is all contained within a single object at its top level.

The second piece I want to point out is the lines for address and company. These are both objects contained within the parent object. So, in order for me to reach to value I want, I have to reference both keys to get the specific value I need. Lastly, I want to call out that you do not need to write every value from the returned JSON to the sheet. I have skipped over several fields to get the end result I desired and it does not affect my code results, which coincidently look like this:

import json to excel

I hope this brief explanation of how to import JSON to Excel was useful for you! Please let me know if it was helpful or if you have any questions in the comments below. Also, if you want to download the file with the example JSON and VBA code, you can do so here if you’re a free subscriber to the site. It’s free, easy, and only takes a moment to sign up.

Cheers!

R

One increasingly common task for Excel users is to retrieve data from the internet.

Simply, retrieving data from the web is the first challenge.

This sounds simple enough (and as you’ll soon see, it is).

But most people run into a roadblock with the second challenge: wrestling with data in JSON format.

Read on to discover the easiest and fastest method to get JSON data into Excel…

How to Import & Parse JSON Data with VBA

You’ve got several approaches to parsing data from the web which is in JSON format:

1) Roll Your Own

You could write your own VBA code to parse the JSON data.

This approach is only recommended if you have acute masochistic tendencies.

This path (of parsing JSON) has been travelled by others before you.
Leverage off their work 😉

2) Free / Open-Source Libraries

You can use free or open-source VBA libraries like VB-JSON or VBA-JSON.

While many of these libraries do work, some do have their own issues, may not be supported and often suffer from performance issues.

3) Third Party Libraries

You could buy a parsing library from a third-party provider.

But if you’re in a corporate environment, you may find it difficult to purchase non-standard software products.

In one recent project, it took 93 days from request to authorisation to installation to get my favourite VBA productivity suite, MZ-Tools installed.

Good thing I wasn’t in a hurry.

But if you are . . .

4) Standard COM components

The last approach, which we’ll cover here, is using standard COM components.

At the end of the day, Excel is just one big component.

What this means is that we can leverage other COM components and libraries quickly and (usually) easily.

Oh, and did I mention they’re free 🙂

What the heck is JSON?

Before we get cracking, let’s give a little attention to JSON.

You’re probably already familiar with XML.

Just like HTML uses tags to structure a webpage, XML uses tags to structure data. This data can be saved to a text file or transmitted over the internet.

JSON, which stands for JavaScript Object Notation, is another method of structuring data, although it doesn’t use tags.

Originally designed for JavaScript, JSON is now used widely for transmitting data between apps and across the web.

You can read all the gory details here.

Using a Web-service to Get Data

The web-service we’ll use to get data in JSON format for this example is Datamuse.

Datamuse is a word-finding query engine. It lets you retrieve a list of words based on a variety of criteria including meaning, spelling, sound and vocabulary.

For example, you could retrieve a list of words related to duck that start with the letter ‘b’, or adjectives that are often used to describe ocean.

The Magic of COM Libraries

You’ll be using two COM libraries to do all the heavy lifting for you.

The first is the Microsoft XML parser library which also includes the ability to query a website and retrieve data.

The second is the Microsoft Script Control

Retrieving the Web Data

The first thing you’ll need to do is set a reference to the Microsoft XML parser library in the Excel Visual Basic Editor (VBE):

You should find the Microsoft XML library in the list of References.

Its exact location may differ on your computer.

Once you’ve done that, in a new module, enter the following VBA function.

You can see it accepts a web URL as an input parameter and will return some text (as a string).

So, what’s it doing?

  1. The first couple of lines declare some constants to make the code easier to read and avoid including any “magic numbers”.
  2. You then declare a variable as the Microsoft XML parsing library and instantiate it.
  3. Next, you’ll open a connection to the web-service with the URL, request that the data come back in JSON format and send the request.
  4. Now we wait. We’ll just staying in holding pattern until the request (declared as a Microsoft XML object) tells us it’s finished.
  5. The function finally returns the JSON it retrieved from the web-service.

Testing Your Code

Let’s test it out.

Enter this routine above the GetResponse() function.

Remember, we’re using the Datamuse web-service to test retrieving JSON data. This query says:

Give me a list of adjectives used to describe the word ‘ocean’.

Let’s test it out.

Enter the following test routine above the GetResponse() function.

Remember, we’re using the Datamuse web-service to test retrieving JSON data.

This query says: Give me a list of adjectives used to describe the word ‘ocean’.

If you pasted this URL into your web browser, it’d look something like this:

Making Sense of JSON

Okay, we’re half-way there.

You’ve got a clean and simple way to retrieve data from a web-service.

Now you just need an efficient way to parse the JSON and load it into Excel.

Enter the Script Control . . .

Now set a reference to the Microsoft Script Control in the Excel VBE:

The script control has several other purposes, including the interpretation and execution of scripts in a host application.

But for your purposes, you just need it to parse JSON.

Enter the following function in your module:

Let’s have a look at what it’s doing . . .

  1. First you declare your ScriptControl variable and set the Language property to «JScript», Microsoft’s flavour of JavaScript. 
  2. Next you declare another Object variable. You then use ScriptControl’s Eval to parse the JSON into a structure you can interrogate.
  3. Here we want to populate an array with the Word collection in the items object, but first we use a helper function called GetItemCount to count the number of elements in the items object to size the array correctly.
    Yes, you could use ReDim Preserve to keep resizing the array but it’s slow and inefficient.
    I’ve listed the GetItemCount helper function below. 
  4. Next you loop through each element in the items object and assign each successive value to your array.
  5. Finally, just for good measure, return the number of elements found.

Now you have a simple routine to parse your JSON data, enter the specific data you want into an array and tell you how many items it found.

What’s in the JSON?

Before we look at the code in more detail, let’s take a quick peek at what’s inside that JSON object we retrieved from the web-service.

Remember, what was returned is a JSON object, not a VBA array.

However, you can peer inside the object as well as loop through it to pluck out data you’re interested in.

When the MS Script Code does is convert the blog of JSON text you saw in the browser screenshot above to something structured.

 If you looked at it in the VBE Locals window, it would look like this:

  1. Notice that the structure “looks” like a regular array with a hierarchy.
  2. But remember, it’s really a JavaScript object.

Okay, to be pedantic, it’s a JScript – Microsoft’s ‘version’ of JavaScript – object.

 Now, back to the code . . .

  1. The first few lines declare a variable, script, as being a shiny new MS Script Control object and tells it you want to use “JScript”. The other alternative is “VBScript”.
  2. You then define an object variable called items (original, I know) to hold the data structure. This is then populated by asking the Script Control to evaluate the JSON.
  3. As this isn’t a true array you can’t use UBound() to determine how many items it has. Instead, you can use a helper function to loop through the Items object and count them.
    You’ll then use this number to resize the output array, ready to be populated. This also helps avoid using ReDim Preserve which can be a tad on the slow side.
  4. You then loop through each top-level element in the object, retrieving the value for “word” and passing it to the VBA array.

Just a minute . . .

How did you know the element you wanted was called “word”?

It’s right there in the JSON string that you retrieved earlier.

Remember, JSON is composed of a couple of simple data structures, the main one being an unordered set of name/value pairs (essentially a dictionary).

Now that you’ve looped through the object and populated the array that was passed by reference, the function returns a count of how many items were found.

Now let’s see it in action.

Update the Test_GetResponse routine so it looks like this:

Let’s pull this code apart. . .

  1. First you declare some variables you need for this process. One to hold the JSON data returned from the webservice (json), an array to hold the values parsed from the JSON object (words) and a range object (Target) so you can paste the results to a worksheet.
  2. Next you call the GetResponse function, passing the URL and have the resulting JSON assigned to the json variable.
  3. Finally, you call the ParseJson function, passing the JSON object and the array to be populated.

If this returns a value greater than zero, you swing into action and define where you want the list of words entered and assign the array to that range.

The eagle-eyed among you probably noticed that you’re also flipping the array using the worksheet Transpose function before assigning it to the Target range.

Meanwhile, you should now have a list of words in worksheet one.

You could have used this to populate a listbox, create a report, anything you’d normally do with extract data.

Over to You

Admittedly, the JSON data structure used in this example was not very complicated. However, the same principles apply to more complex data structures.

Take your time to example the returned data in the Locals window and you’ll be in a better position to parse even the most complicated JSON data.

What challenges have you faced importing and processing JSON data into Excel. How did you solve them?

Let me know in the comments below.

If you’re still wrestling with some JSON data let me know about that too.

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.

json vba

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.

msscript

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

Download Source Code

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?
  • Stop IE from loading further when required data is there
  • VBA Excel : Populate TextBox with specific string of text when Option Button is selected
  • Object Defined Error in Data from Internet Pull
  • Range.Find does not find exactly what I’m searching for
  • How to disable arrow keys in ListView control in VBA with Excel
  • Run-time error ‘1004’: The PivotTable field name is not valid
  • Weird activecell.offset output
  • Move files from multiple folders to a single folder
  • moving range of values from one sheet to another
  • VBS code not working in HTA (WScript declaration)
  • VBA Form Is (automatically) Tied/Bound To ActiveWorksheet When calling Form.Show vbmodeless
  • Make the second combo-box item selected based on item selection of first combo box
  • How to check the same values between 2 table (MSAccess)
  • How do you run a Word mail merge macro from Excel?
  • Stop procedure if condition is not met using a global variable in VBA
  • Setting default values in Data Validation drop-down list
  • Pivot table expand and substract or Show/Hide Details using Excel VBA
  • Using one or two dimensional arrays in Excel VBA
  • Summing up a column based on multiple Criterion
  • Calculate Time of each row excel

Like this post? Please share to your friends:
  • Excel vba objects and methods
  • Excel vba items in combobox
  • Excel vba object module
  • Excel vba isnumber vba
  • Excel vba is value in array