You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VBA解析JSON至Excel:JSONConverter报错及数据转多行实现

VBA解析JSON到集合/数组:解决"Dictionary Key Not Found"错误并实现数据分行

核心问题

触发错误的直接原因是你访问了JSON解析后字典中不存在的键名,或者对JSON的层级结构判断错误(比如把嵌套数组当成顶层集合,或键名拼写错误)。

正确实现步骤

1. 先确认JSON实际结构

先把获取到的JSON字符串输出到立即窗口,明确层级:

Debug.Print jsonStr ' jsonStr为你从网站获取的JSON字符串

2. 分情况解析(以典型人员数据为例)

场景1:JSON顶层是数组结构

比如JSON内容为:

[
  {"id":1,"name":"张三","部门":"技术部"},
  {"id":2,"name":"李四","部门":"人事部"}
]

解析代码:

Dim jsonColl As Collection
Dim itemDict As Dictionary
Dim resultArr() As Variant
Dim idx As Integer

' 直接解析为集合
Set jsonColl = JsonConverter.ParseJson(jsonStr)
' 初始化结果数组(行数=数据条数,列数=字段数)
ReDim resultArr(1 To jsonColl.Count, 1 To 3)

idx = 1
For Each itemDict In jsonColl
    ' 访问键前可先判断是否存在,避免错误
    If itemDict.Exists("id") Then resultArr(idx, 1) = itemDict("id")
    If itemDict.Exists("name") Then resultArr(idx, 2) = itemDict("name")
    If itemDict.Exists("部门") Then resultArr(idx, 3) = itemDict("部门")
    idx = idx + 1
Next itemDict

场景2:JSON顶层是字典,包含数组字段

比如JSON内容为:

{
  "人员列表": [
    {"id":1,"name":"张三","部门":"技术部"},
    {"id":2,"name":"李四","部门":"人事部"}
  ]
}

解析代码:

Dim jsonDict As Dictionary
Dim dataColl As Collection
Dim itemDict As Dictionary
Dim resultArr() As Variant
Dim idx As Integer

' 先解析为顶层字典
Set jsonDict = JsonConverter.ParseJson(jsonStr)
' 取出数组对应的集合(注意键名必须和JSON一致)
If jsonDict.Exists("人员列表") Then
    Set dataColl = jsonDict("人员列表")
Else
    MsgBox "JSON中不存在指定键名"
    Exit Sub
End If

ReDim resultArr(1 To dataColl.Count, 1 To 3)
idx = 1
For Each itemDict In dataColl
    resultArr(idx, 1) = itemDict("id")
    resultArr(idx, 2) = itemDict("name")
    resultArr(idx, 3) = itemDict("部门")
    idx = idx + 1
Next itemDict

关键注意事项

  • 必须确保导入的JSONConverter模块版本正确,且已勾选Microsoft Scripting Runtime引用(VBA编辑器→工具→引用);
  • 所有键名必须和JSON中的完全一致(区分大小写);
  • 不确定键是否存在时,用Dictionary.Exists(键名)做判断,避免触发找不到键的错误。

内容的提问来源于stack exchange,提问作者YasserKhalil

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 21:40:23