在 VBA 中访问 Variant/Object/JScriptTypeInfo 属性

Accessing a Variant/Object/JScriptTypeInfo property in VBA

我有以下代码 VBA 代码(用于 Excel 模块)

Function getDesc(ByVal pCode As String) As String
    Dim oRequest As Object
    Set oRequest = CreateObject("WinHttp.WinHttpRequest.5.1")
    oRequest.Open "GET", "https://my.url.com/?filter=CODE=" & pCode, False
    oRequest.SetRequestHeader "Accept", "application/json"
    oRequest.Send ""

    Set props = jsonDecode(oRequest.ResponseText)

    getDesc = props.row_data
End Function

Function jsonDecode(jsonString As Variant)
    Set sc = CreateObject("ScriptControl"): sc.Language = "JScript"
    Set jsonDecode = sc.Eval("(" + jsonString + ")")
End Function

props.row_data的结果如图

我不知道如何将 属性 LONG_DESCRIPTION 分配给 getDesc =

我需要什么正确的语法?或者,我将接受任何允许我 return LONG_DESCRIPTION 的字符串的解决方案。

试试下面的代码。 JSON.bas 模块导入 VBA 项目进行 JSON 处理。

Option Explicit

Function getDesc(ByVal pCode As String) As String

    Dim oRequest As Object
    Dim sJSONString As String
    Dim vJSON As Variant
    Dim sState As String

    Set oRequest = CreateObject("WinHttp.WinHttpRequest.5.1")
    oRequest.Open "GET", "https://my.url.com/?filter=CODE=" & pCode, False
    oRequest.SetRequestHeader "Accept", "application/json"
    oRequest.Send
    sJSONString = oRequest.ResponseText
    JSON.Parse sJSONString, vJSON, sState
    getDesc = vJSON("row_data")(0)("LONG_DESCRIPTION")

End Function

使用 JSON 字符串 {'row_data':[{'LONG_DESCRIPTION':'desc_string'}]} 测试。

您不需要外部库来实现:

Option Explicit

Function getDesc(ByVal pCode As String) As String
    Dim oRequest As Object
    Set oRequest = CreateObject("WinHttp.WinHttpRequest.5.1")
    oRequest.Open "GET", "https://my.url.com/?filter=CODE=" & pCode, False
    oRequest.SetRequestHeader "Accept", "application/json"
    oRequest.Send ""

    Set props = jsonDecode(oRequest.ResponseText)

    Set sc = CreateObject("ScriptControl"): sc.Language = "JScript"
    sc.AddCode "function jsGetDesc(obj) { return obj[0]['LONG_DESCRIPTION']; }"
    getDesc = sc.Run("jsGetDesc", props.row_data)
End Function