24 Aug Convert Excel to JSON Using VBA
Posted at 02:58h
in Excel VBA
2 Comments
Howdee! I had a lot of requests after my recent article on converting a JSON string to Excel, asking if it was possible to convert Excel to JSON. Fortunately, it is not only possible, but you can use the same library we previously covered to do so! In this article, we will go over how to convert your Excel data to a JSON string, and how to convert that same data to a JSON file. If you haven’t read the previous article linked above, I highly recommend you do so before reading on here. Beyond covering how to import JSON, it also covers the basics of JSON objects and arrays. With that said, let’s dive in!
Convert Excel to JSON String
The most common occurrence for me, is the need to transfer some sort of data from an Excel file to a JSON string so I can pass that information through a HTTP request or to another program. For this, you’ll need to convert Excel to JSON, and store that in a variable. To do that, we need to dimension a few variables to use later:
Dim excelRange As Range
Dim jsonItems As New Collection
Dim jsonDictionary As New Dictionary
Dim i As Long
Dim cell As Variant
The first variable, excelRange, will be used to define the range of data we want to convert to JSON. The second, jsonItems, will be the collection we ultimately store our data in. Collection might be a new term to some so, at a high level, a collection is just an object that we can use to group and manage related objects. The third variable, jsonDictionary, is the dictionary we will first store our Excel values in. A dictionary is a type of collection that you can access using a key. Again, check out the previous post on JSON to get a better understanding of this type of object. The last two variables, i & cell, will be used in our for loop to help store the values to a dictionary. The next bit of our code looks like this:
Set excelRange = Cells(1, 1).CurrentRegion
For i = 2 To excelRange.Rows.Count
jsonDictionary("id") = Cells(i, 1)
jsonDictionary("name") = Cells(i, 2)
jsonDictionary("username") = Cells(i, 3)
jsonDictionary("email") = Cells(i, 4)
jsonDictionary("street") = Cells(i, 5)
jsonDictionary("suite") = Cells(i, 6)
jsonDictionary("city") = Cells(i, 7)
jsonDictionary("zipcode") = Cells(i, 8)
jsonDictionary("phone") = Cells(i, 9)
jsonDictionary("website") = Cells(i, 10)
jsonDictionary("company") = Cells(i, 11)
jsonItems.Add jsonDictionary
Set jsonDictionary = Nothing
Next i
MsgBox JsonConverter.ConvertToJson(jsonItems, Whitespace:=3)
So what is happening here? Firstly, I start by setting the range where our data exists. Now that I know the size of the range, I can begin to convert Excel to JSON by looping through each row (skipping headers) and writing each cell’s value into the dictionary. At the end of each loop, I need to write the dictionary to my collection and then clear it for the next loop. Lastly, I’m printing this JSON string to a message box so we can view it. You can do whatever you wish with the JSON string at this point, I’m only printing to a message box to demonstrate how to convert Excel to JSON string.
Convert Excel to JSON File
Converting Excel data to a JSON file is almost the exact same process. The only difference is, instead of outputting the result to a string variable or writing it to a cell in the workbook, you’re going to use the FileSystemObject model to create a new file to convert & store Excel data to a JSON file. You’ll need these two new variables:
Dim jsonFileObject As New FileSystemObject
Dim jsonFileExport As TextStream
The first allows you to access the FileSystemObject model which will allow you to create new files and save them to a folder. The second allows you to write text, in this case the JSON string, to the file. Those two new lines of code look like this:
Set jsonFileExport = jsonFileObject.CreateTextFile("C:UsersusernameDesktopjsonExample.json", True)
jsonFileExport.WriteLine (JsonConverter.ConvertToJson(jsonItems, Whitespace:=3))
The first will create the new JSON file. Make sure you use the keyword “True” if you’re planning to reuse this code. This will allow the program to overwrite the file. However, if you’re having the user create the name of the file, it might be useful to use “False” which will not allow the program to create any new file that would overwrite a previous one.
The second line of code simply writes the converted JSON to the file. Unless you open the file in your code, there is no need to explicitly save or close the file in this example. The full code to convert Excel to JSON looks like this:
Sub excelToJsonFileExample()
Dim excelRange As Range
Dim jsonItems As New Collection
Dim jsonDictionary As New Dictionary
Dim jsonFileObject As New FileSystemObject
Dim jsonFileExport As TextStream
Dim i As Long
Dim cell As Variant
Set excelRange = Cells(1, 1).CurrentRegion
For i = 2 To excelRange.Rows.Count
jsonDictionary("id") = Cells(i, 1)
jsonDictionary("name") = Cells(i, 2)
jsonDictionary("username") = Cells(i, 3)
jsonDictionary("email") = Cells(i, 4)
jsonDictionary("street") = Cells(i, 5)
jsonDictionary("suite") = Cells(i, 6)
jsonDictionary("city") = Cells(i, 7)
jsonDictionary("zipcode") = Cells(i, 8)
jsonDictionary("phone") = Cells(i, 9)
jsonDictionary("website") = Cells(i, 10)
jsonDictionary("company") = Cells(i, 11)
jsonItems.Add jsonDictionary
Set jsonDictionary = Nothing
Next i
‘change the path below to save where you desire
Set jsonFileExport = jsonFileObject.CreateTextFile("C:UsersusernameDesktopjsonExample.json", True)
jsonFileExport.WriteLine (JsonConverter.ConvertToJson(jsonItems, Whitespace:=3))
End Sub
Here is the outputted JSON file displayed in Visual Studio Code:
I hope this tutorial was useful for those of you that need to write your Excel data to JSON either to a string or to a file. If you have questions, drop them in the comments below. As always, the example file is available for your download if you’re a registered member to this site. The file contains the examples I walked through today to convert Excel to JSON. Registering is free and only takes a minute. You’ll get notified as I release additional content but I won’t spam you with tons of unsolicited emails. Until next time!
Cheers,
R
JSON format data is widely popular when it comes to send and receive information between a web server and a client. I bumped into a situation where I needed to do the POST to my server and obviously the data format I needed was in JSON. So, I wrote this little Excel VBA macro to convert a given range into a JSON format.
Excel Macro to convert given range to JSON format
Public Function ToJSON(rng As range) As String
‘ Make sure there are two columns in the range
If rng.Columns.Count < 2 Then
ToJSON = CVErr(xlErrNA)
Exit Function
End If
Dim dataLoop, headerLoop As Long
‘ Get the first row of the range as a header range
Dim headerRange As range: Set headerRange = range(rng.Rows(1).Address)
‘ We need to know how many columns are there
Dim colCount As Long: colCount = headerRange.Columns.Count
Dim json As String: json = «[»
For dataLoop = 1 To rng.Rows.Count
‘ Skip the first row as it’s been used as a header
If dataLoop > 1 Then
‘ Start data row
Dim rowJson As String: rowJson = “{”
‘ Loop through each column and combine with the header
For headerLoop = 1 To colCount
rowJson = rowJson & “””” & headerRange.Value2(1, headerLoop) & “””” & “:”
rowJson = rowJson & “””” & rng.Value2(dataLoop, headerLoop) & “”””
rowJson = rowJson & “,”
Next headerLoop
‘ Strip out the last comma
rowJson = Left(rowJson, Len(rowJson) – 1)
‘ End data row
json = json & rowJson & “},”
End If
Next
‘ Strip out the last comma
json = Left(json, Len(json) – 1)
json = json & “]”
ToJSON = json
End Function
VBA-Excel-Table-To-JSON
What is this?
A small VBA script that converts Excel tables to JSON format and exports the data to a .json file at the location of your choice. Use the script by importing the .bas and .frm & .frx files to your Excel VBA editor.
Installation
You can use this script by following these steps:
- Open up Microsoft Excel
- Go to the Developer tab (For more information on how to show the developer tab, go here)
- Click on Visual Basic, in the upper left corner of the window
- In the toolbar at the top of the window that appears, click on file 👉 Import file…
- Select ExcelToJSON.bas and click on Open
- Click on file 👉 Import file… for a second time
- Select ExcelToJSONForm.frm and click on Open (make sure that ExcelToJSONForm.frx is located in the same folder, or this step will not work)
- Congratulation, you have successfully installed the script 🎉🥳
Usage
To use the script, you need an Excel file with at least one table in it. Once you do, follow these instructions:
- Go to the Developer tab
- Click on Macros
- Select PERSONAL.XLSB!ExcelToJSON.ExcelToJSON
- Click on Run
- In the window that appears, select which tables that you would like to export, and then click on Submit
- Finally select the name for the JSON file that will be selected as well as the location that you would like to save the file in
Please note that the script ‘escapes’ all double quotes that exists in the table cells to stay compatible with the JSON format. This means that a cell that contains the text Lorem ipsum "dolor sit" amet, consectetur
will be edited to look like Lorem ipsum "dolor sit" amet, consectetur
.
The script prints out the cell values of all cell contents as strings, and will not print out the formulas used
The script does not support unicode characters yet, but this will be implemented in a future version.
Contact
You can reach me at otto[dot]wretling[at]gmail[dot]com
License
MIT License
Copyright (c) 2020 theAwesomeFufuman
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
«Software»), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.THE SOFTWARE IS PROVIDED «AS IS», WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Добрый день, имеется выгрузка в excell в табличном виде, нужно данные сохранить в json структуре, через формулу «=» практически получил нужную структуру но не могу последнюю проблему решить как объяснить макросу, что если работа входит в фазу (суммарную работу), то нужно добавить в конце » ]} » и добавить столько в зависимости от уровня раз. (надеюсь последнее предложение более или менее понятно объяснил)). Прикрепленные файлы
|
|
Doober Пользователь Сообщений: 2201 |
Здравствуйте.опубликуйте результирующий json, на пару строк с таблицы. |
Добрый день, вот пример файла на всю таблицу Прикрепленные файлы
|
|
Doober Пользователь Сообщений: 2201 |
В макросе изложен принцип формирования JSON. Прикрепленные файлы
|
Добрый день, если я правильно понял, то в макросе test, Вы вручную всю структуру завели? тогда не очень понятен принцип формирования json структуры… или я не туда смотрю…может укажете куда смотреть? |
|
Doober Пользователь Сообщений: 2201 |
Во вложении Ваш отформатированный json ,структуру в макросе создал согласно файла руками. Прикрепленные файлы
Изменено: Doober — 13.03.2017 12:04:48 |
Сергей Шистеров Пользователь Сообщений: 249 |
#7 16.03.2017 07:12:23 я увидел что формируется, но проблема в другом получается если у меня будет 300 строк мне всю структуру необходимо будет в макрос писать? и так под каждую новую структуру?
ниже библиотека для подключения JsonConverter.zip (8.01 КБ) Изменено: Сергей Шистеров — 16.03.2017 07:16:02 |
||
Максим Зеленский Пользователь Сообщений: 4646 Microsoft MVP |
#8 16.03.2017 12:36:17 Сергей Шистеров, спасибо за наводку, интересная библиотека, надо ее поковырять, уж очень она навернутая.
https://github.com/VBA-tools/VBA-JSON#installation добавьте в редакторе VBA референс на «Microsoft Scripting Runtime» Но в вашем случае проблема не в конвертации строки в json, а в объяснении любому конвертеру, что в этом месте заканчивается объект или массив (или несколько объектов/массивов). Начинал возиться да потом отвлекли, бросил. F1 творит чудеса |
||
Вот полностью рабочий вариант , этой библиотеки с примерами, но Children так мне и не победить( https://cloud.mail.ru/public/KBCQ/24FFyvYFh размер 150 кб не влазит на форум даже в архиве Изменено: Сергей Шистеров — 16.03.2017 13:02:03 |
|
Сергей Шистеров Пользователь Сообщений: 249 |
#10 16.03.2017 12:57:44 вот другой пример, где добавляется Location мне бы вместо него, типа проверки если фаза то children :[
Изменено: Сергей Шистеров — 16.03.2017 13:01:03 |
||
Сергей Шистеров Пользователь Сообщений: 249 |
#11 17.03.2017 11:52:41
результат его работы
Подскажите как его адаптировать под мою задачу? |
||||
Не стал пока колбаситься с макросом, сделал формулами. Проверьте |
|
Сергей Шистеров Пользователь Сообщений: 249 |
#13 21.03.2017 09:52:38 Да спасибо, все работает! |
So I would pass in the range to a JavaScript function and let it iterate over the Excel object model and build the array in JavaScript. Then call a JavaScript library to convert array into a string (hat tip Douglas Crockford) and simply return the string to VBA. So no string operations in VBA.
The JavaScript function is given below but depends upon Douglas Crockford’s library at https://raw.githubusercontent.com/douglascrockford/JSON-js/master/json2.js. Save this in a file and then amend VBA code with the correct file path so the JavaScript is loaded into the Microsoft Script Control.
function ExcelTableToJSON(rngTable) {
try {
if (rngTable && rngTable['Rows'] && rngTable['Columns']) {
var rowCount = rngTable.Rows.Count;
var columnCount = rngTable.Columns.Count;
var arr = new Array();
for (rowLoop = 1; rowLoop <= rowCount; rowLoop++) {
arr[rowLoop - 1] = new Array();
for (columnLoop = 1; columnLoop <= columnCount; columnLoop++) {
var rngCell = rngTable.Cells(rowLoop, columnLoop);
var cellValue = rngCell.Value2;
arr[rowLoop - 1][columnLoop - 1] = cellValue;
}
}
return JSON.stringify(arr);
}
else {
return { error: '#Either rngTable is null or does not support Rows or Columns property!' };
}
}
catch(err) {
return {error: err.message};
}
}
The Excel VBA code is thus
Option Explicit
'In response to
'http://stackoverflow.com/questions/38100193/is-it-possible-in-vba-convert-excel-table-to-json?rq=1
'Is it possible in VBA convert Excel table to json
'Tools->References->
'Microsoft Script Control 1.0; {0E59F1D2-1FBE-11D0-8FF2-00A0D10038BC}; C:WindowsSysWOW64msscript.ocx
Private Sub Test()
Dim oScriptEngine As ScriptControl
Set oScriptEngine = New ScriptControl
oScriptEngine.Language = "JScript"
oScriptEngine.AddCode GetJavaScriptLibraryFromWeb("https://raw.githubusercontent.com/douglascrockford/JSON-js/master/json2.js")
Dim sJavascriptCode As String
sJavascriptCode = CreateObject("Scripting.FileSystemObject").GetFile("<<<Your file path to javascript file>>>ExcelTableToJSON.js").OpenAsTextStream.ReadAll
oScriptEngine.AddCode sJavascriptCode
Dim rngTable As Excel.Range
Set rngTable = ThisWorkbook.Worksheets.Item("Sheet2").Range("A1:B2")
rngTable.Cells(1, 1) = 1.2
rngTable.Cells(1, 2) = "red"
rngTable.Cells(2, 1) = True
rngTable.Cells(2, 2) = "=2+2"
Dim sStringified As String
sStringified = oScriptEngine.Run("ExcelTableToJSON", rngTable)
Debug.Assert sStringified = "[[1.2,""red""],[true,4]]"
Stop
End Sub
Public Function GetJavaScriptLibraryFromWeb(ByVal sURL As String) As String
Dim xHTTPRequest As Object 'MSXML2.XMLHTTP60
Set xHTTPRequest = VBA.CreateObject("MSXML2.XMLHTTP.6.0")
xHTTPRequest.Open "GET", sURL, False
xHTTPRequest.send
GetJavaScriptLibraryFromWeb = xHTTPRequest.responseText
End Function