在Windows Excel VBA中,将JSON写入2d变体数组

时间:2016-07-11 15:36:50

标签: javascript json excel-vba vba excel

在这里回答我自己的问题。可以调用在Microsoft脚本控件中运行的JavaScript并返回一些JSON数据结构。虽然可以使用脚本控件的Evaluate方法解析JSON,但有时人们想要写入二维(2d)变量数组,然后可以将其直接粘贴到工作表或返回用户定义的函数。这有助于防止数据结构的编组。

无法将2d变量数组传递给JavaScript函数,写入它然后将其传回。 [如果您有不真实的证据,请发布]。所以这段代码失败了

'Tools->References->
'Microsoft Script Control 1.0;  {0E59F1D2-1FBE-11D0-8FF2-00A0D10038BC}; C:\Windows\SysWOW64\msscript.ocx

Private Sub TestJSONtoOleVariantGridFails1()

    Dim oScriptEngine As ScriptControl
    Set oScriptEngine = New ScriptControl
    oScriptEngine.Language = "JScript"

    oScriptEngine.AddCode "function WriteResults1(vGrid) { vGrid(0,0)=1.2;vGrid(0,1)='red';vGrid(1,0)=true;vGrid(1,1)=null; return vGrid;};"

    ReDim vGridBefore(0 To 1, 0 To 1)
    Dim vGridAfter
    vGridAfter = oScriptEngine.Run("WriteResults1", vGridBefore) '<---- FAILS with error "Cannot assign to a function result"

    Debug.Assert vGridAfter(0, 0) = 1.2
    Debug.Assert vGridAfter(0, 1) = "red"
    Debug.Assert vGridAfter(1, 0) = True
    Debug.Assert IsNull(vGridAfter(1, 1))


End Sub

所以这就引出了如何最好地填充二维变体数组的问题?

我有一个我发布的解决方案,但我很想知道其他人是否已经找到了JSON和2d变体数组之间的编组。

1 个答案:

答案 0 :(得分:0)

这是我的解决方案,它通过创建一个类来包装2d变量数组,然后传入对类的引用。这就像&#34;拳击&#34;。

'Tools->References->
'Microsoft Script Control 1.0;  {0E59F1D2-1FBE-11D0-8FF2-00A0D10038BC}; C:\Windows\SysWOW64\msscript.ocx

Private Sub TestJSONtoOleVariantGridSucceeds()

    Dim oScriptEngine As ScriptControl
    Set oScriptEngine = New ScriptControl
    oScriptEngine.Language = "JScript"

    oScriptEngine.AddCode "function WriteResults(oGrid) { oGrid.Redimension(2,2); oGrid.Cell(0,0)=1.2;oGrid.Cell(0,1)='red';oGrid.Cell(1,0)=true;oGrid.Cell(1,1)=null;};"

    Dim oGrid As JSONOLEVariant
    Set oGrid = New JSONOLEVariant

    Call oScriptEngine.Run("WriteResults", oGrid)

    Dim vGrid As Variant
    vGrid = oGrid.ExportGridData

    Debug.Assert vGrid(0, 0) = 1.2
    Debug.Assert vGrid(0, 1) = "red"
    Debug.Assert vGrid(1, 0) = True
    Debug.Assert IsNull(vGrid(1, 1))



End Sub

和类代码JSONOLEVariant.cls

Option Explicit
Option Base 0

Private mvGridData As Variant

Public Function ExportGridData()
    ExportGridData = mvGridData
End Function

Public Sub Redimension(ByVal lRows As Long, ByVal lColumns As Long)
    ReDim mvGridData(0 To lRows - 1, 0 To lColumns - 1) 'Zero base
End Sub

Public Property Let Cell(ByVal lRow As Long, ByVal lColumn As Long, ByVal vNewValue As Variant)
    mvGridData(lRow, lColumn) = vNewValue
End Property