Excel是一款非常流行的電子表格軟件,它可以方便地進行數據處理,而JSON則是一種輕量級的數據交換格式,可以用于數據的傳輸和存儲。如果想將Excel中的數據轉換成JSON格式,可以使用Excel 2 JSON工具。
Sub Excel2Json() Dim jsonObj As Object Set jsonObj = CreateObject("Scripting.Dictionary") Dim sheet As Worksheet Set sheet = ActiveSheet Dim header As Range Set header = sheet.Range("A1", sheet.Cells(1, sheet.Columns.Count).End(xlToLeft)) Dim cell As Range Dim row As Range For Each row In sheet.UsedRange.Rows Set cell = row.Cells(1) Dim key As String key = Trim(cell.Value) If key = "" Then Exit For End If Dim value As String value = "" Dim col As Range For Each col In header.Columns If col.Column< cell.Column Then Continue For End If If value<>"" Then value = value & ", " End If Dim content As String content = Trim(row.Cells(1, col.Column).Value) value = value & """" & col.Value & """: """ & content & """" Next col Dim item As String item = "{" & value & "}" jsonObj.Add key, item Next row Dim jsonStr As String jsonStr = "{" Dim keyStr As Variant For Each keyStr In jsonObj If jsonStr<>"{" Then jsonStr = jsonStr & ", " End If jsonStr = jsonStr & """" & keyStr & """: " & jsonObj(keyStr) Next keyStr jsonStr = jsonStr & "}" Debug.Print jsonStr End Sub
這段VBA代碼將活動工作表中的數據轉換成JSON格式。首先創建了一個Scripting.Dictionary對象,用于存儲轉換后的JSON數據。然后獲取了第一行的標題,按行遍歷數據并轉換成JSON格式,最后將所有轉換后的JSON數據合并成一個JSON字符串輸出。
要使用Excel 2 JSON工具,只需要將以上代碼復制并粘貼到Excel VBA中即可。