简体   繁体   中英

Loading VBA JSON variable then referencing it in Cells using Excel Formulas

I have an event button in my excel document that loads a JSON document using a technique from this link: Is There a JSON Parser for VB6 / VBA?

This creates a JSON variable in the vb script that I can use based on this JSON string:

{
    "a": 1,
    "b": [
        13,
        1.4142135623730951,
        15
    ]
}

I can easily use VBA script to load the page. But...

How can I use Json inside a formula within a Cell? Does something exist that does this? $VARIABLE_LOOKUP(Json)("a") to get a value of 1 in the cell.

Can anyone get a working hello world scenario working of this scenario?

Excel doc屏幕截图,更加清晰

  • Click command button
  • It loads the Json
  • The formula in A5 should now evaluate to 1 .

Can it be done?

An example of the code is inside this excel document here: https://drive.google.com/file/d/0B540RQ1Nj-KINnVQS3cwMDFsc1E/view?usp=sharing

The answer: you can use custom functions defined in your own module to do this.

Create a module, add global variable for json and a method to set it (that your button will hit):

Private jsObj As Object

Public Function SetJsObj(jsonString As String)
    jsObj = JSON.parse(jsonString)
End Function

Public Function GetJsObj()
    GetJsObj = jsObj
End Function

Using the json parser Is There a JSON Parser for VB6 / VBA?

Then you use the function in the cell:

=GetJsObj()("a")

will now eval to

1

A solution would be to create an UDF to eval any expression:

Public Function Eval(expression As String)
  Application.Volatile
  Eval = Application.Evaluate(expression)
End Function

Then in your formula:

=Eval("JSON.parse(Json)(""a"")")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM