首页 > 解决方案 > 如何设置一个变量等于另一个变量excel vba中的json值

问题描述

我正在解析的 json 位于此 URL https://reqres.in/api/users?page=2。我正在使用以下代码来解析它。

Option Explicit

Sub Test_LateBinding()

Dim objRequest As Object
Dim strUrl As String
Dim blnAsync As Boolean
Dim strResponse As String

Set objRequest = CreateObject("MSXML2.XMLHTTP")
strUrl = "https://reqres.in/api/users?page=2"
blnAsync = True

With objRequest
    .Open "GET", strUrl, blnAsync
    .SetRequestHeader "Content-Type", "application/json"
    .Send
    'spin wheels whilst waiting for response
    While objRequest.readyState <> 4
        DoEvents
    Wend
    strResponse = .ResponseText
End With

Debug.Print strResponse

End Sub

我可以成功地将 json 放入 strResponse 变量中。但是假设我想要一个等于“Eve”的变量,它在 json 字符串中的名字下。如何从该 json 字符串中设置变量 firstName = "Eve"。

标签: jsonexcelvbaparsing

解决方案


如果您需要在 VBA 中使用 JSON,那么我建议您使用这个库:

https://github.com/VBA-tools/VBA-JSON

使用该库的简单示例:

Public Sub Tester()

    Dim http As Object, JSON As Object, d
    Set http = CreateObject("MSXML2.XMLHTTP")

    http.Open "GET", "https://reqres.in/api/users?page=2", False
    http.SetRequestHeader "Content-Type", "application/json"
    http.Send
    Set JSON = ParseJson(http.responseText)

    For Each d In JSON("data")
        Debug.Print d("id"), d("first_name")
    Next

End Sub

推荐阅读