簡體   English   中英

64 位 Excel VBA 調用 JavaScript ZC1C425268E68389411AB507ZA809Z

[英]64 bit Excel VBA to call a JavaScript function

I need to use a VBA ScriptControl object to call a JavaScript function, but it gave me a "Class Not Registered" error. I have added Microsoft Script Control 1.0 from Tools->References I need to call JavaScript to get a JSON object from this Rest API to calculate values in an Excel Macro.

這篇文章告訴我 ScriptControl 僅用於 32 位。 我正在使用 64 位 Excel。 我也嘗試使用此鏈接中提到的方法,但它不起作用,因為 VBA 無法識別 ActiveXObject

我的Excel VBA代碼調用一個簡單的JS function:

Private Sub CommandButton1_Click()
    Dim jsObj As MSScriptControl.ScriptControl, result As Integer
    Set jsObj = CreateObject("MSScriptControl.ScriptControl")
    jsObj.Language = "JScript"
    With jsObj
        .AddCode ("function prod1(a,b){return a*b;}")
        result = .Run("prod1", 2, 3)
    End With
    MsgBox result
End Sub

I am getting a class not registered error for the line Set jsObj = CreateObject("MSScriptControl.ScriptControl") Is there an alternate way to call a JavaScript function from VBA? 還是我錯過了什么?

不需要 ScriptControl object:您可以使用 XMLHTTP 和 VBA-JSON。

例如:

Public Sub Tester()

    'Import the "JsonConverter.bas" file from 
    '     https://github.com/VBA-tools/VBA-JSON
    'and add a reference to the Microsoft Scripting Runtime library
    Dim http As Object, JSON As Object, i As Integer, o As Object, k

    Set http = CreateObject("MSXML2.XMLHTTP")
    http.Open "GET", "https://www.alphavantage.co/query?" & _
          "function=CURRENCY_EXCHANGE_RATE&from_currency=USD" & _
          "&to_currency=JPY&apikey=demo", False

    http.Send

    Debug.Print http.responseText
    Debug.Print "-----------------------------------"

    Set JSON = ParseJson(http.responseText)

    Set o = JSON("Realtime Currency Exchange Rate")
    For Each k In o.keys
        Debug.Print k, o(k)
    Next k

End Sub

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM