在日常的数据处理中,我们经常会处理表格数据并需要将其导出为标准格式,比如 JSON,方便用于系统对接、前端展示或数据交换。今天我们就用一段简单实用的 VBA 代码,来实现这个功能:将 Excel 中选中的单元格区域导出为 JSON 文件。
这段 VBA 代码的功能如下:
.json
文件;转为 JSON 后如下:
[
{
"Name": "Tom",
"Age": 25,
"City": "Tokyo"
},
{
"Name": "Alice",
"Age": 30,
"City": "Osaka"
}
]
为了支持 JSON 格式,需要引入第三方的 JSON 模块:
JsonConverter.bas
Alt + F11
进入 VBA 编辑器文件 > 导入文件
,导入 JsonConverter.bas
RangeToJson
Function RangeToJson(dataRange As Range) As String
Dim headerRange As Range, dataBodyRange As Range
Dim headers As Object
Dim r As Range, c As Range
Dim rowIndex As Long
Dim jsonObject As Object
Dim collectionToJson As New Collection
If dataRange.Rows.Count < 2 Then
RangeToJson = ""
MsgBox "选区至少需要包含表头和一行数据。", vbExclamation
Exit Function
End If
Set headerRange = dataRange.Rows(1)
Set dataBodyRange = dataRange.Resize(dataRange.Rows.Count - 1).Offset(1, 0)
Set headers = CreateObject("Scripting.Dictionary")
For Each c In headerRange.Cells
headers.Add c.Column, CStr(c.Value)
Next
For rowIndex = 1 To dataBodyRange.Rows.Count
Set jsonObject = CreateObject("Scripting.Dictionary")
For Each c In dataBodyRange.Rows(rowIndex).Cells
If headers.Exists(c.Column) Then
jsonObject.Add headers(c.Column), c.Value
End If
Next
collectionToJson.Add jsonObject
Next
RangeToJson = JsonConverter.ConvertToJson(collectionToJson, Whitespace:=2)
End Function
ExportJsonFromSelectedRange
Sub ExportJsonFromSelectedRange()
Dim jsonText As String
Dim fileSaveName As Variant
Dim fileNumber As Integer
If TypeName(Selection) <> "Range" Then
MsgBox "请先选择一个包含表头的区域。", vbExclamation
Exit Sub
End If
jsonText = RangeToJson(Selection)
If jsonText = "" Then Exit Sub
fileSaveName = Application.GetSaveAsFilename(fileFilter:="JSON Files (*.json), *.json")
If fileSaveName <> False Then
fileNumber = FreeFile
Open fileSaveName For Output As fileNumber
Print #fileNumber, jsonText
Close fileNumber
MsgBox "导出成功!"
End If
End Sub
ExportJsonFromSelectedRange
;.json
;通过这段 VBA 代码,你可以轻松将 Excel 数据转为 JSON 文件。
参考资料:
[1] VBA-JSON(https://github.com/VBA-tools/VBA-JSON)
[2] Save Excel Table to JSON File using VBA and VBA-JSON(https://syntaxbytetutorials.com/save-excel-table-to-json-file-using-vba-and-vba-json/)