How to enable macros in excel How to calculate age in Excel How to create a Pivot Table in excel How to enable the Developer Tab in Excel How to Calculate Standard Deviation in Excel How to Calculate Time Difference in Excel How to Freeze Cells in Excel What-if Analysis in Excel How To Insert Checkbox in MS Excel How To Insert PDF in MS Excel How to change the Date Format in Excel How to compare two Excel sheet How To Apply Filter In Excel How To Move Columns In Excel How to add or remove Hyperlink in Excel How to calculate Mean in Excel How to Separate text in Excel How to recover a macro in Excel How to recover a Corrupted Excel file How to recover an Excel file How to remove comma in Excel How to sum a column in Excel How to remove the filter in Excel How to remove gridlines in Excel How To Convert Excel To CSV How To Create Table in Excel How to Calculate IRR in Excel How to Count Characters in Excel How to Make an Excel Sheet How to Replace Words in Excel How to Sort by Date in Excel How to hide formulas in Excel How to subtract in excel How to use the IF function in Excel How To Create A Graph In Excel How to use concatenate in Excel How to spell check in Excel How to Change Lowercase to Uppercase in Excel How to Create a Dashboard in Excel How to Delete Duplicate Rows in Excel How to use sumifs formula in Excel How to add page break in Excel How to remove the page break in Excel How to Convert Columns to Rows in Excel How to Convert Number to Words in Excel How to Make a Table in Excel How to Put Tick Mark in Excel How to Remove Passwords from Excel File How to Wrap Text in Excel How to insert comments in Excel How to add/remove Password from Excel How to use MS Excel How to sort in Excel How to record a macro in Excel How Many Rows and Columns in Excel 2007 How to Search in Excel How to add a text box in Excel How to save Excel document How to set background image in Excel How to use COUNTIF function in Excel How to import the data from CSV file in Excel How to unlock scroll lock in Excel What is a cell in Excel Uses of MS Excel How to Reduce Excel File Size How to Save Excel File as PDF ODS to Excel How to lock cells in Excel How to unlock cells in Excel Hyperlink in Excel How to compare two columns in Excel Conditional formatting in Excel How to define custom rules for conditional formatting in Excel Data validation in Excel Apply data validation in Excel Remove spaces in Excel How to Save Excel File Watermark in Excel How to unhide columns in Excel How to delete blank rows in Excel Excel round off formula How to Add Watermark in Excel How to Remove Watermark in Excel Excel Save As Shortcut Excel Shortcut Keys Excel match function HLOOKUP formula in Excel What is the file extension for Excel Offset function in Excel Compound interest formula in Excel Excel password remover FV() function in Excel MS Excel Definition What is Excel Excelity login Income tax calculating formula in Excel Google Excel Spreadsheet Online Excel Viewer Online Excel Editor How to make pie charts in excel How to calculate number of days between two dates in Excel Excel Download Download MS Office 2019 using command prompt Download Windows and MS office activator Excel Header and Footer Excel to JPG JPG to Excel Salary slip format in Excel How to count colored cells in Excel Excel Substring formula CSV to Excel Word to Excel Regression analysis in Excel How to calculate CAGR in Excel Excel to Word Percentage formula in Excel Mail merge in Excel How to unhide rows in Excel How to Split Cells in Excel Current Date in Excel Index function in Excel How to remove formula in Excel Excel Features Flash Fill in Excel How to convert Excel to JSON Convert Excel to JSON using VBA code Round formula in Excel Excel formula Ratio in Excel Excel Delete Row Shortcut Insert Column Excel Shortcut Excel not equal to operator Logical operators in Excel Delete Data in Excel Excel Slicer Excel Difference Between Two Dates Excel Filter Shortcut Excel Charts Excel text function Excel LOOKUP() function MS Excel Grade Formula 10 Disadvantages of Microsoft Excel Shortcut Keys in Excel 2010 Advanced Formulas in Excel Excel Merge Cells Shortcut Excel Paste Special Shortcut INDIRECT() function in Excel What is Relative Reference in Excel Excel Sum Shortcut Redo Shortcut in Excel Arrow key is not working in Excel Type of charts in Excel Nested If Function in Excel Lower() in excel Proper() in excel Types of References in Excel AND Function in Excel How to do subtraction in Excel Excel MAX() Function How to delete a Sheet in Excel How to Insert Chart in Excel Excel ISERROR() function Excel add-ins IF() in excel REPT() in excel What is Formatting in Excel OR Function in Excel Solver in Excel Excel AVERAGE() Function Excel MIN() Function Format Painter in Excel COUNTA function in excel Excel mid function Excel right function Excel Choose Function How to Use RIGHT Function in Excel NOT Function in Excel Excel COUNT() Function Line Chart Excel Excel RAND() function Excel find() function Excel tricks Dollar function in excel Left formula in excel Randbetween function in excel ROUNDDOWN Function in Excel Tenure Formula in Excel Excel TODAY and NOW How to unhide worksheet in Excel Freeze panes in Excel Excel PMT Function NETWORKDAYS Formula in Excel Pivot Chart in Excel Excel Hide Shortcut Unhide Shortcut in Excel Range in Excel Strikethrough in Excel How to password protect an Excel sheet Page Orientation in Excel Area Chart in Excel Bubble Chart Excel Autofill in Excel Convert rows to columns Analysis ToolPak Zoom In/Out in Excel Excel Format Painter Shortcut Excel Wrap Text Shortcut Uppercase Shortcut in Excel How to make a bar chart in Excel JSON to Excel Sparkline chart Why MS Excel is Important Waterfall Chart Excel Excel IRR formula Excel Pareto chart Column Chart Formatting Charts Pie Chart Doughnut Chart Excel Scatter Plot Excel Text to column in Excel Excel IFERROR() function Excel Median() function Gantt Chart Excel Consolidate data in Excel Excel Strikethrough Shortcut Flow Chart Excel Organization Chart Excel Excel box plot Excel Transpose Function Circular reference in Excel Excel Filter Function Excel VAR.S() Function Email Workbook Share Workbook Correlation in Excel How many sheets are there in excel workbook by default What is Mod Function in Excel Compatibility mode in Excel How to unprotect Excel sheet without password Adding Graphics Translate Worksheet Excel Large Function Excel Rank Function Cross Referencing in Excel Using Themes in Excel Excel IFNA Function Excel TRIM Function Excel DATEVALUE Function Excel SUBSTITUTE Function Special Symbols in Excel Basic Excel Shortcuts Keys Excel CORREL function Sheet Options in Excel Text Alignment in Excel Parts of MS Excel Window How to attach file in excel Excel Exact Function Advanced Excel Shortcut keys Adjust Margins in Excel Cell Styles in Excel Rotate Cells in Excel Excel group rows Calculate average weighted in Excel Find and Replace in Excel Excel EVEN Function Excel ODD Function Excel SUMPRODUCT Function Custom Number Format in Excel Excel NPER Function Excel PV Function How to go to next line in excel How to insert calendar in excel Print Worksheet in Excel Undo Changes in Excel Excel FV Function Excel NPV Function Date to month in excel How to merge sheets in excel Create a Worksheet in Excel Hiding Worksheet in Excel Formula reference in Excel Copying Formula in Excel Formula Errors in Excel How to open JSON file in Excel How to insert Excel file in ppt Cell References in Excel Excel ABS Function Excel Floor Function How to remove time from date in excel How to set print area in excel Excel CEILING Function Excel IPMT Function Setting Colors in Excel Setting Cell Type and Font in Excel How to share Excel sheet Data bars in Excel Excel Highlight Cell Rules Formula for percentage of total in Excel How to open XML in Excel Borders and Shades in Excel Fractions in Excel How to insert image in excel Merge columns in excel Excel Color Scales Convert Decimal to Fraction in Excel Format Cells in Excel Excel Rules Manager Excel Top/Bottom Rules Copy Worksheet in Excel Currency Vs Accounting Format in Excel Highlight Duplicates in Excel How to insert date in Excel Mail merge from Excel to Word How to recover unsaved Excel file How to remove table in Excel Check Mark in Excel Excel Templates Excel Small Function Excel XOR() Function How to subtract time in Excel Excel Icon Sets Excel ROWS Function Numbers to Text in Excel Text to Numbers in Excel How to remove decimals in Excel Insert object in Excel How to convert text to number in Excel How to remove dropdown in Excel Insert Bullets in Excel Text Wrapping in Excel Heap map in Excel Excel array formula Freeze Columns in Excel Freeze Rows in Excel Merge Excel Files Excel errors Excel Remove Blank Rows How to delete rows in Excel How to calculate percentage in Excel #### Error in Excel How to insert a column in Excel How to insert multiple rows in Excel MIS report in Excel Error Bars in Excel Value Error in Excel Excel formulas not working Logical functions in Excel #Div/0! Excel Error #NULL error in Excel #NAME? Error in Excel #REF! Error in Excel How to add prefix in Excel Show formula in Excel VLOOKUP Errors in Excel Excel automation Compile Error in Hidden Module INDEX and MATCH Function in Excel What is concatenate in Excel Goal Seek in Excel Sequence Function in Excel Excel XIRR Function Hyperlink Function in Excel Excel DB Function Trend Function Excel Excel Forecast Function Excel IFS Function Excel FORECAST.ETS.CONFINT function Excel FORECAST.ETS Function Excel FORECAST.ETS.STAT function Excel FORECAST.ETS.SEASONALITY function Growth Function in Excel Sunbrust Chart in Excel Treemap in Excel Formula Auditing in Excel Moving Average Formula Sum Formula in Excel Excel #SPILL! error Excel Contains Function Excel Gauge Chart Random Number Generator Excel Autofit #N/A error in Excel How to Convert Kg to Pound Print Titles in Excel Excel Advance Filters How to get sheet name in Excel Randomize a list in Excel Excel Status Bar Excel Trendline Excel Sort by Color Dependent Drop-down Line Break in Excel How to add Double Quotes in MS Excel How to Change Data Range in Pivot Table How to Delete Excel Sheet in Mac How to Unfreeze Excel on mac How to use VBA in MS Excel 2016 How to view macro code in Excel 2007 Histogram chart in Excel Paste options in Excel Square Root in Excel Thermometer Chart in Excel Pivot table in Excel 2011 Wildcard in Excel Excel Value Function Chart Element in MS Excel ANOVA in the Microsoft Excel Custom Sorting in Excel Excel Replace Function How to create the Budget in the Microsoft Excel Mode Function in the Microsoft Excel 3D Reference in Microsoft Excel Formula Auditing in the Microsoft Excel Get Pivot Data Function in Microsoft Excel Macro comments in VBA EXCEL Mod Operator in Excel One Drive in Microsoft Excel Remove spaces in Microsoft Excel Running Total in the Microsoft Excel Subscript Out of Range Error in Microsoft Excel VBA Union and Intersection in Excel VBA Count Names in Microsoft Excel Excel Formula Bar Formula bar How to add text or character to every cell in Microsoft Excel Merge multiple Excel sheets into one SUMIF between two Dates Countif Function in Excel How to create and use Excel data entry form MAXIFS and MINIFS in Excel Sum Largest Number How can we convert column numbers to letters in Microsoft Excel How to calculate percentages in Microsoft Excel - formula examples How to compare two columns in Microsoft Excel for matches and differences How to Delete every other row or every Nth row in Excel How to extract text from Excel cells How to insert a tick symbol and cross mark in Excel How to insert the New Lines in Microsoft Excel 6 methods to put tick symbol in Microsoft Excel Calculating week number in Microsoft Excel with the help of the WEEKNUM function How can we change an Excel CSV delimiter to a comma or semicolon in Microsoft Excel 6 methods to put tick symbol in Microsoft Excel Calculating week number in Microsoft Excel with the help of the WEEKNUM function How can we change an Excel CSV delimiter to a comma or semicolon in Microsoft Excel How one can insert Excel If Statement with Multiple Conditions How to Filter in Excel: add, apply, use, and remove filter VLOOKUP to compare two columns in Microsoft Excel for common values and missing data Dynamic Named Range Excel Sumif function Extracting numbers from the string Finding Top or Bottom 'N' values in Excel How to change the row color in Excel based on a cell's value How to make Use of the MONTH and EOMONTH functions in Excel - formula examples Logical Functions in Excel Regex Formula in Microsoft Excel Excel Date Function in Microsoft Excel Excel VLOOKUP from Another Sheet How to add zeros before the number in Excel How to create User Defined Function in Microsoft Excel How to cut characters in Excel How to delete an Empty column in Microsoft Excel Convert to the Proper Case in Microsoft Excel Correlation in Microsoft Excel: coefficient, matrix, and graph Excel Named Range How can one implement PPMT Function in Microsoft Excel How can one insert Subscript and Superscript in Microsoft Excel How do you auto-fill the sequence of dates in Excel How one can open a Password Protect Excel File How to calculate Variance in Excel How to convert Date to text in Microsoft Excel How to count non-empty cells in Excel How to enable and disable Macros in Excel How to open Microsoft Excel files in separate windows How to pin the home bar in Excel How one can sum only filter cells in Microsoft Excel How to merge Cells in Excel without losing the data How to prevent duplicates in a column in Excel How to Prevent Text Spilling in Excel How to remove the first character in Excel How to use and implement the IPMT Function in Microsoft Excel: Calculating interest portion of a loan payment Quick Methods to Insert Multiple Rows in Excel Excel COUNTIF and COUNTIFS Function How one can group rows in Microsoft Excel to collapse and expand them How to convert text to Date and number to Date in Microsoft Excel How to edit, evaluate, and debug formulas in Excel Random Samples in Excel How can one remove text and leave numbers in Microsoft Excel or vice versa How one can copy as well move Excel sheets in Microsoft Excel How to add a hyperlink to another worksheet Count Unique Values in Excel How one can copy formula in Microsoft Excel: down a column, without changing references How to enter Multiple Lines in a Single Cell in Excel How to implement Left LOOKUP in Excel How to use Linest Function in Excel Microsoft Excel: if match formula to check whether two or multiple cells are equal Excel Address Function With Formulas How to Change and Autofit Row Height in Excel Microsoft Excel SUBTOTAL function with formula examples UNIQUE function: a quick method to find a unique value in Microsoft Excel How can one Convert a Microsoft Excel table to range or vice versa How to count cells with specific text How to Group Columns in Microsoft Excel How to swap columns in Excel: Dragging and other methods to move columns XLOOKUP function in Excel Excel MAX IF Formula: To get highest value with conditions How one can compare two columns for matches and differences in Microsoft Excel How one can group and ungroup worksheets in Microsoft Excel How one can run Macro in Microsoft Excel and create macro button Copy and Move the Worksheet to Excel Excel Charts: Tips, Techniques, and Tricks Find and Remove External Link How one can easily create a chart (graph) in Microsoft Excel and save it as Template How to insert Page Numbers in Excel How to repeat row and column headers on every page of Excel spreadsheets Excel Multiply Formulas How to add or create a dropdown list in Microsoft Excel How to find duplicates in Excel How do you chart titles in Excel How to Divide and handle #DIV/0! Error in Excel How to Figure Out which Excel Version you are using Inserting date in Excel Merge Two columns without losing data How can one convert an image file to an Excel sheet How can one perform Data Analysis in Microsoft Excel: DATA ANALYSIS TOOL How to easily convert (open or import) a CSV file to Microsoft Excel Advanced Excel Tutorial: How To Master Microsoft Excel Excel Formulas List How to Divide and handle #DIV/0! Error in Excel How to filter in Excel What do you mean by Computer Excel Annuity Function in Excel A spreadsheet in Microsoft Excel Dashboard in Microsoft Excel Functions in Excel Dashboard in Microsoft Excel How one can make use of the SUM Function in Microsoft Excel Income Tax Calculator in Microsoft Excel Invoice Format in Microsoft Excel Quotation Format in Microsoft Excel Salary sheet in Microsoft Excel Rows and Columns in Microsoft Excel How to format Excel Sheet Percentage formula present in Excel Concatenation in Excel Data Entry in Excel How to create Barcode in Microsoft Excel What is Radar Chart in Microsoft Excel Diameter Symbol in Microsoft Excel How do you draw the S curve in Microsoft Excel PowerPivot in Microsoft Excel EDATE Function in Microsoft Excel How to create a Timeline in Microsoft Excel Days Sales Outstanding What is the difference between Microsoft Excel and Microsoft Access Difference between Excel and Tableau What is the difference between Excel and DBMS Advantages of using Power BI over Microsoft Excel What is the difference between Vlookup and Hlookup What is the difference between Absolute and Relative references in Microsoft Excel Python vs. Excel VBA What is the difference between Trend and Forecasting in Microsoft Excel Data Scrapping In Microsoft Excel Data Cleaning in Microsoft Excel Microsoft Excel VS CSV GDPR in Microsoft Excel 20 Ms Excel Jobs Arrow keys in Excel BARCODE FONT FOR EXCEL Best excel VBA Course Best Python library for excel Best way to learn ms excel Do Engineers use Excel How do you convert Notepad to Excel Excel 2008 for Mac Excel 2016 Excel CDate Excel Data Types Excel for Windows Vista EXCEL READER EXCEL VERSIONS Macros to Send an Email using Excel Mathematical Functions Merge First and Last Names in Excel Ms Excel Logo Automatic Numbering in Excel Calculate the Cost Of Common Stock Comparison Charts In Excel Comparison Graph In Excel Create a Search Box In Excel Diagram Vs Chart How to Combine Duplicates in Excel Merge Excel files online OCR to excel Project Management Dashboard Excel Difference between RDBMS and Microsoft Excel Table vs Range in Microsoft Excel Data Excel Excel Editor Excel Js MIS Full form in Excel Offset Excel Web Excel Excel Modeling Maximum Rows in Excel Merging Duplicates in Excel Excel 365 Excel 2019 Excel PowerPoint Fungsi Excel Latest Version of Excel Microsoft Excel 2010 Microsoft Excel Vs. LibreOffice Power View In Microsoft Excel Chebychev's Inequality in Excel Excel's Clustered Bar Chart Control charts in Excel Data Maintenance in Excel Microsoft Excel 2016 Portable Excel 2016 vs Excel 2013 Excel 2016 vs Excel 365 Excel 2016 vs Excel 2019 Excel Alternatives EXCEL CONSULTING EXCEL DATA SETS Excel datasheet Excel Games that You Should Play Excel Lite Excel Projects for Practice Excel Sports Logo Excel Student Table Microsoft Excel Viewer 2016 ExcelR.com EXPORT TO EXCEL C# Financial Functions in Excel HOW TO ADD RUPEE SYMBOL IN EXCEL How to remove 91 from mobile number in excel How to use Custom Views in Excel How to Work in Excel Difference between Sum and Sumif function in Microsoft Excel Bell Curve in Excel Best Excel Skills How to Write Paragraphs in Excel Medical Bill Format Microsoft Excel 2016 for Mac PRODUCT SHEET IN EXCEL QUICK ANALYSIS TOOL IN EXCEL REFRESH EXCEL Word Excel PowerPoint Data Validation Icon Excel Courses Excel Developer Tools Excel Developer f4 Function in Excel Message Box Name Manager LOOKUP vs VLOOKUP XLOOKUP VS INDEX-MATCH IN MICROSOFT EXCEL XLS Icon XLS Online Attendance sheet format in excel Balance sheet format in Excel Best online excel courses for finance Best Way to Learn Excel Online Free Create Excel Application EXCEL BILLING Excel book EXCEL INT FUNCTION Excel is Fun Excel Modelling How to make a Checklist in Excel HRA Calculation in Excel Improve your Excel Microsoft Mobile Excel Bonus Calculation Formula in Excel DA calculation formula in Excel Debit Note Format in Excel GST invoice format in excel How to Create Mark Sheets in Excel Name Box in Excel Purchase Order format in Excel Sheet Tab in Excel SKILLS MATRIX TEMPLATE EXCEL Difference between Autofilter and Advanced filter in Microsoft Excel Excel Help Excel OR Excel Summary Excel Website Car loan Emi calculator in Excel Carried Interest Calculation in Excel Convert Negative to Positive Daily Loan Calculator in Excel House Construction Cost Calculator in Excel How do you draw a cash flow diagram in Excel Loan Amortization Schedule in Excel Creating a Database in Excel Petty Cash Format in Excel Recurring Deposit in Excel TDS Calculator in Excel Two-wheeler Loan EMI Calculator in Excel Excel Series ISBLANK Function in Microsoft Excel Bill Book format in excel Computation of Income tax Format in Excel EXCEL LIST BOX Excel Now HOW TO LINK EXCEL SHEETS How to put power in Excel Labour Contractor Bill format in Excel Lead Time Calculation in Excel Outliers Excel Overtime Calculation in Excel Over Eight Hours TEXT COMPARE Time Addition TIME CARD CALCULATOR Basic Excel Practice Exercises xls COUNTBLANK Function in Microsoft Excel How to Calculate ATR in Excel Delivery Challan format in excel GOOGLE SHEETS CONDITIONAL FORMATTING ON ANOTHER CELL How to Color Alternate Rows in Excel IFERROR VLOOKUP Stock average calculator Excel Travelling Bill Format in Excel Convert Text to Excel How to use the VLOOKUP Function with Choose Function in Microsoft Excel Cash flow statement format in excel DTR CALCULATOR EXCEL Excel to XML converter Fibonacci Retracement calculator in Excel How to Insert Radio Button in Excel How to make use of Vlookup with Multiple categories or Values HOW TO RESIZE CELLS IN EXCEL HOW TO SELECT NON-CONTIGUOUS IN EXCEL How to Shift Rows up in Excel HOW TO SUMMARIZE DATA IN EXCEL Linear Programming in Excel PROGRESS CHART EXCEL STRIKETHROUGH TEXT SHORTCUTS Tax Invoice format in excel Vlookup with the Countif Function in Microsoft Excel What is Data Filtering XML to Excel Converter Online COUNTIF Not Blank Cell in Microsoft Excel HOW TO REMOVE CONDITIONAL FORMATTING IN EXCEL Reducing Rate of Interest Calculator with Flat in Excel CUSTOM LIST Debt consolidation calculator excel DGET FUNCTION IN EXCEL HOW TO CALCULATE DESCRIPTIVE STATISTICS IN EXCEL Spearman rank correlation Calculator Excel How to get Unique Count in Pivot Table XLS to PDF XML to XLSX converter online CPF Calculator in Excel Customer service tracker in Excel How to Calculate AHT in Excel How to Convert 1000000 to 1.00 in Excel How to easily delete a Pivot Table in Microsoft Excel HOW TO DELIMIT IN EXCEL How to Invert Data in Excel Subtotal with Countif Function in Microsoft Excel

Shortcut Keys

Excel Shortcut Keys

Interview Questions

Excel Interview HR Interview SQL Interview PL/SQL Interview

Convert the Excel to JSON using VBA code

Instead of downloading the Excel to JSON conversion software, you can also use the VBA Code Editor to convert the Excel data to JSON format. You can create your own customized code on VBA editor and run it to get the task done.

VBA Code Editor is a developer tool or in-built feature of Excel. It comes default with Excel when you download MS Excel. In VBA code Editor, you can write your own code and perform a particular task. If you are comfortable in doing coding, then it's a good way for you.

Make a code for Excel to JSON conversion by mapping of Excel columns to JSON object keys. Then execute the code to convert the data into JSON format. One who knows coding in visual basics then use this tool.

Why VBA code editor?

If you are good at coding and create logical codes, then why go for tools. Create your own customized code in VBA code editor and convert any number of Excel documents to JSON format by running that code. It does not need to download or internet connection and all.

You do not need to explicitly download any tool to convert your Excel data to JSON format. While you can do it without downloading any software on your system using Excel VBA code Editor. If you are comfortable in doing coding, then it's a good way for you. Even you do not need to install the VBA editor as it comes with Excel by default.

Tip: Your Excel data must have column names because the first row is always considered as a header.

Open VBA editor

  • You can open the VBA code editor in Excel from the Developer tab.
  • In case the developer tab is not available in your Excel ribbon, customize the ribbon by right-clicking on the ribbon and choose the developer tab from the list.
  • Then, click the first option Visual Basic to open the VBA code editor.
  • In VBA code editor, create a new module under your currently opened Excel file.
  • Write the Excel to JSON conversion code here.
  • VBA Code

    Following is the complete code for the conversion of the Excel file data to JSON format. Copy this following code and paste this to your respective VBA code editor.

    Public Function ExcelToJSON(rng As Range) As String ' Check there must be at least two columns in the Excel file If rng.Columns.Count < 2 Then ExcelToJSON = CVErr(xlErrNA) Exit Function End If Dim dataLoop, headerLoop As Long ' Get the first row of the Excel file as a header Dim headerRange As Range: Set headerRange = Range(rng.Rows(1).Address) ' Count the number of columns of targeted Excel file Dim colCount As Long: colCount = headerRange.Columns.Count Dim JSON As String: JSON = "[" For dataLoop = 1 To rng.Rows.Count ' Skip the first row of the Excel file because it is used as header If dataLoop > 1 Then ' Start data row Dim jsonData As String: jsonData = "{" ' Loop through each column and combine with the header For headerLoop = 1 To colCount jsonData = jsonData & """" & headerRange.Value2(1, headerLoop) & """" & ":" jsonData = jsonData & """" & rng.Value2(dataLoop, headerLoop) & """" jsonData = jsonData & "," Next headerLoop ' Strip out the comma in last value of each row jsonData = Left(jsonData, Len(jsonData) - 1) ' End data row JSON = JSON & jsonData & "}," End If ' Strip out the last comma in last row of the Excel data JSON = Left(JSON, Len(JSON) - 1) JSON = JSON & "]" ExcelToJSON = JSON End Function

    In this VBA code, we have defined a function named ExcelToJSON that will later be used in an Excel file for the conversion of Excel to JSON. Let's see how it will execute.

    Syntax

    =ExcelToJSON(range)

    This function will take the range of Excel cells, e.g., A1:F9 that you would like to convert to JSON format.

    Convert the Excel data to JSON format

    Now, we will use the function ExcelToJSON() that we have created using the above code to convert the Excel data to JSON format. Remember one thing - this function is created only for this particular file. It is not available for other Excel files.

    Go back to the Excel file and write the following ROUND() formula in an Excel cell where you want to place the converted JSON result. For example,
    =ExcelToJSON(A1:D3)
    Currently, we are converting the first two Excel rows and four columns data into JSON format only. Press the Enter key and get the result and see that the data is successfully converted into JSON form.
    In the same way, you can use this function for more data conversion by increasing the range of the Excel cells. Copy this converted JSON data from here and store it simple Word file.

    Code Explanation

    Code 1

    If rng.Columns.Count < 2 Then ExcelToJSON = CVErr(xlErrNA) Exit Function End If

    First of all, this code is used to verify that the selected range must have at least two columns for Excel to JSON conversion. If not, you will be exit from this function.

    Code 2

    Dim dataLoop, headerLoop As Long ' Get the first row of the Excel file as a header Dim headerRange As Range: Set headerRange = Range(rng.Rows(1).Address)

    Next, we have created two variables: dataLoop and headerLoop. The dataLoop variable for the Excel data stored in Excel file, and headerLoop for the column header. Both variables will use during conversion.

    Code 3

    ' Count the number of columns of targeted Excel file Dim colCount As Long: colCount = headerRange.Columns.Count

    Here, we have created a variable colCount. We have used this code to find the number of targeted columns to convert their data to JSON format in an Excel file.

    Code 4

    Dim JSON As String: JSON = "[" For dataLoop = 1 To rng.Rows.Count ' Skip the first row because it is used as header If dataLoop > 1 Then ' Start data row Dim jsonData As String: jsonData = "{"

    Now, this code starts creating JSON data from Excel file. Here, dataLoop variable is used inside a for loop from 1 to end of the selected rows. The first row of the Excel file data will be skipped because while converting Excel data to JSON first row always be considered as a header.

    The data in JSON format will be enclosed between curly {} braces.

    Code 5

    ' Loop through each column and combine with the header For headerLoop = 1 To colCount jsonData = jsonData & """" & headerRange.Value2(1, headerLoop) & """" & ":" jsonData = jsonData & """" & rng.Value2(dataLoop, headerLoop) & """" jsonData = jsonData & "," Next headerLoop ' Strip out the comma in last value of each row jsonData = Left(jsonData, Len(jsonData) - 1) ' End data row JSON = JSON & jsonData & "}," End If

    A loop will run through each column and combine the column header with row data. Each value will be separated by comma. While this code ( jsonData = Left(jsonData, Len(jsonData) - 1) ) will skip the comma in last value after each row.

    In JSON file format, each row of data will be enclosed between {} braces.

    Code 5

    ' Strip out the last comma in last row of the Excel data JSON = Left(JSON, Len(JSON) - 1) JSON = JSON & "]" ExcelToJSON = JSON

    All concatenated data will be stored in a JSON name variable and this complete data will be placed between the [] square brackets. The converted JSON data will display to the user in an Excel cell where he will use this user-defined ExcelToJSON() function.

    Next Topic Round formula in Excel