Quantcast
Viewing all articles
Browse latest Browse all 52

Export Range in Json Format

Macro to Export Range in Json Format


Option Explicit

Sub export_in_json_format()

    Dim fs As Object
    Dim jsonfile
    Dim rangetoexport As Range
    Dim rowcounter As Long
    Dim columncounter As Long
    Dim linedata As String
   
    ' change range here
    Set rangetoexport = Sheet1.Range("a1:d8")
   
    Set fs = CreateObject("Scripting.FileSystemObject")
    ' change dir here
   
    Set jsonfile = fs.CreateTextFile("C:\Users\xx\Desktop\"& "jsondata.json", True)
   
    linedata = "{""Output"": ["
    jsonfile.WriteLine linedata
    For rowcounter = 2 To rangetoexport.Rows.Count
        linedata = ""
        For columncounter = 1 To rangetoexport.Columns.Count
            linedata = linedata & """"& rangetoexport.Cells(1, columncounter) & """"& ":"& """"& rangetoexport.Cells(rowcounter, columncounter) & """"& ","
        Next
        linedata = Left(linedata, Len(linedata) - 1)
        If rowcounter = rangetoexport.Rows.Count Then
            linedata = "{"& linedata & "}"
        Else
            linedata = "{"& linedata & "},"
        End If
       
        jsonfile.WriteLine linedata
    Next
    linedata = "]}"
    jsonfile.WriteLine linedata
    jsonfile.Close
   
    Set fs = Nothing
   
   
End Sub

Viewing all articles
Browse latest Browse all 52

Trending Articles