1

I want to have a button in an excel document (using VBA) which, takes in the data on the sheet and outputs a file (.json). Which I can then use later on within a web page.

I my excel data looks like this:

Image of excel table

Note I would like to have more than one instance of data. I want it to generate a json file in the format of:

{
	"Excel_test": [
		{
			"name" : "tesintg1",
			"age" : 15
		},
		{
			"name" : "testng2",
			"age" : 1
		},
		{
			"name" : "testing3",
			"age" : 435
		}
	]
}
Thanks

4
  • Why don't you do this with help of a proper programming language? Commented Dec 3, 2019 at 12:03
  • What do you mean a proper programming language? Commented Dec 3, 2019 at 14:33
  • Build an app in Python, C#, Java or anything else to read the Excel file and ouput JSON, much more straightforward than programming a macro in VBA. Commented Dec 3, 2019 at 14:44
  • Ok, I'll have a look into it, cheers Commented Dec 3, 2019 at 14:56

1 Answer 1

1

The open-source VBA-JSON project helps with this.

Once you have installed it in your workbook's VBA project, you can do something like this:

Sub convertJson()

    Dim c As Collection
    Dim d As Dictionary 'Add reference to scripting runtime
    Dim v As Dictionary
    Dim json As String

    Set c = New Collection
    Set d = New Dictionary


    d.Add "ExcelTest", c
    For Each cell In Range("A2:A4") 'Adapt as you need
        Set v = New Dictionary
        v.Add "name", cell.Value
        v.Add "age", cell.Offset(0, 1).Value
        c.Add v
    Next
    
    json = JsonConverter.ConvertToJson(d)

    Debug.Print json
    
End Sub

Outputs:

{"ExcelTest":[{"name":"test1","age":15},{"name":"test2","age":1},{"name":"test3","age":435}]}
Sign up to request clarification or add additional context in comments.

2 Comments

When I run this example I get an error on Dim d As Dictionary. Where you put add reference to scripting run time what do you mean?
Go to the VBA editor > Tools > References and select the library Microsoft Scripting Runtime

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.