|
楼主 |
发表于 2014-10-27 14:05
|
显示全部楼层
[广告] Excel易用宝 - 提升Excel的操作效率 · Excel / WPS表格插件 ★ 免费下载 ★ ★ 使用帮助★
本帖最后由 wcymiss 于 2014-10-31 09:41 编辑
JSON转换成vba对象
1、JSON数组在vba内需要用For Each来获取其元素:(For Each 后面的变量不能定义为Object类型)- Sub Test()
- Const strJSON As String = "[""甲"",""乙"",""丙""]"
- Dim objJSON As Object
- Dim Cell '这里不能定义为object类型
- With CreateObject("msscriptcontrol.scriptcontrol")
- .Language = "JavaScript"
- .AddCode "var mydata =" & strJSON
- Set objJSON = .CodeObject
- End With
- Stop '查看vba本地窗口里objJSON对象以了解JSON数据在vba里的形态
- For Each Cell In objJSON.mydata
- Debug.Print Cell
- Next
- End Sub
复制代码 2、JSON对象在vba内可直接用“对象.属性”的方法获取,但当名称不被vba允许时,用CallByName函数获取:- Sub Test()
- Const strJSON As String = "{""name"":""甲"",""age"":36}"
- Dim objJSON As Object
- With CreateObject("msscriptcontrol.scriptcontrol")
- .Language = "JavaScript"
- .AddCode "var mydata=" & strJSON
- Set objJSON = .CodeObject
- End With
- Stop '查看本地窗口
- Debug.Print objJSON.mydata.age
- Debug.Print objJSON.mydata.Name '此句出错
- End Sub
复制代码 “name”作为vba对象的属性时会被自动首字母大写。而JavaScript里是区分大小写的,“Name”不能等同“name”,json数据里无“Name”属性,所以代码运行出错。
这时让我们请出“CallByName”吧。(使用前请先查看vba帮助中对此函数的说明)
将出错的那句代码改成:- Debug.Print CallByName(objJSON.mydata, "name", VbGet)
复制代码 ok。数据成功获取!
3、综合处理:- Sub Test()
- Const strJSON As String = "[{""name"":""甲"",""age"":36,""children"":[{""name"":""甲儿"",""age"":10},{""name"":""甲女"",""age"":7}]},{""name"":""乙"",""age"":28,""children"":[{""name"":""乙女"",""age"":6}]}]"
- Dim objJSON As Object
- Dim Person, Child
- Dim arrData(1 To 100, 1 To 4)
- Dim i As Long
-
- With CreateObject("msscriptcontrol.scriptcontrol")
- .Language = "JavaScript"
- .AddCode "var mydata =" & strJSON
- Set objJSON = .CodeObject
- End With
- Stop '多多查看本地窗口,你才会进步更快。。。
-
- '为了编写方便,假设每个Person的children数组里至少有一个元素:
- For Each Person In CallByName(objJSON, "mydata", VbGet)
- For Each Child In CallByName(Person, "children", VbGet)
- i = i + 1
- arrData(i, 1) = CallByName(Person, "name", VbGet)
- arrData(i, 2) = CallByName(Person, "age", VbGet)
- arrData(i, 3) = CallByName(Child, "name", VbGet)
- arrData(i, 4) = CallByName(Child, "age", VbGet)
- Next
- Next
- Cells.Clear
- Range("a1:d1").Value = Array("name", "age", "childname", "childage")
- Range("a2").Resize(i, 4).Value = arrData
- End Sub
复制代码 个人建议:为了区分vba对象本身的属性,建议JSON对象的属性都用CallByName表示。
更多在vba中使用JavaScript的例子,敬请参考figfig大师的帖子:
http://club.excelhome.net/thread-478544-1-1.html、
http://club.excelhome.net/thread-483942-1-1.html、
http://club.excelhome.net/thread-484702-1-1.html
|
评分
-
5
查看全部评分
-
|