在VBA中直接解析JSON可以通过Windows Script Host调用JavaScript引擎实现,以下是完整解决方案:
实现原理
利用VBA的ScriptControl组件调用JScript引擎,通过JavaScript的JSON.parse()方法解析JSON字符串。
' 需要先在VBA引用中添加: Microsoft Script Control 1.0
Function ParseJSON(jsonString As String) As Object
On Error GoTo ErrorHandler
Dim sc As Object
Set sc = CreateObject("ScriptControl")
sc.Language = "JScript"
' 注入JSON解析函数
sc.AddCode "function parseJson(json){ return JSON.parse(json); }"
Set ParseJSON = sc.Run("parseJson", jsonString)
Exit Function
ErrorHandler:
Set ParseJSON = Nothing
Err.Raise 1001, "JSON Parser", "解析失败: " & Err.Description
End Function
使用示例
Sub TestJSONParser()
Dim json As String
json = "{""name"":""John"", ""age"":30, ""cars"":[""Ford"",""BMW"",""Fiat""]}"
Dim result As Object
Set result = ParseJSON(json)
' 访问解析结果
Debug.Print "姓名: " & result.name
Debug.Print "年龄: " & result.age
Debug.Print "第一辆车: " & result.cars(0)
End Sub
输出效果
姓名: John
年龄: 30
第一辆车: Ford
注意事项
-
环境要求:
- 仅支持32位Office(64位需改用其他方案)
- 需启用
Microsoft Script Control 1.0引用
-
安全限制:
' 禁用脚本执行安全提示 sc.AllowUI = False -
复杂结构处理:
' 访问嵌套对象 Debug.Print result.address.city ' 遍历数组 For i = 0 To result.cars.Length - 1 Debug.Print result.cars(i) Next
提示:对于大型JSON数据,建议使用专门的VBA JSON库(如VBA-JSON)提高性能。此方案适合轻量级解析需求。
2万+

被折叠的 条评论
为什么被折叠?



