VBA中向字典添加字典项报错,求解决方案
VBA字典嵌套赋值错误的解决方法
错误原因
VBA中,Dictionary属于对象类型,对象的赋值操作必须使用Set关键字,直接赋值会触发类型不匹配错误,这就是最后一行代码报错的核心原因。
修正后的代码
Dim jsonDictionary As New Dictionary jsonDictionary(Cells(1, 1).Text) = Cells(1, 2).Text Dim tempDict As New Dictionary tempDict(Cells(2, 2).Text) = Cells(2, 3).Text tempDict(Cells(3, 2).Text) = Cells(3, 3).Text ' 用Set关键字将字典对象作为条目值存入外层字典 Set jsonDictionary(Cells(3, 1).Text) = tempDict
额外注意事项
- 确保已引用Microsoft Scripting Runtime库:打开VBA编辑器,依次点击
工具→引用,勾选该选项即可。 - 若不想依赖前期绑定,可改用后期绑定创建字典,无需手动引用库:
Dim jsonDictionary As Object Set jsonDictionary = CreateObject("Scripting.Dictionary") Dim tempDict As Object Set tempDict = CreateObject("Scripting.Dictionary")
内容的提问来源于stack exchange,提问作者patpatwithhat
相关产品推荐
相关产品推荐

