64 位 Excel VBA 调用 JavaScript 函数
64 bit Excel VBA to call a JavaScript function
我需要使用 VBA ScriptControl 对象来调用 JavaScript 函数,但它给了我一个 "Class Not Registered" 错误。
我从工具->参考添加了 Microsoft Script Control 1.0
我需要调用 JavaScript 从这个 Rest API 中获取一个 JSON 对象来计算 Excel 宏中的值。
This post 告诉我 ScriptControl 仅用于 32 位。我正在使用 64 位 Excel。
我也尝试使用此 link 中提到的方法,但它没有用,因为 VBA 无法识别 ActiveXObject
我的ExcelVBA调用简单JS函数的代码:
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
我在 Set jsObj = CreateObject("MSScriptControl.ScriptControl") 行收到 class not registered 错误
有没有其他方法可以从 VBA 调用 JavaScript 函数?还是我遗漏了什么?
不需要 ScriptControl 对象:您可以使用 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
我需要使用 VBA ScriptControl 对象来调用 JavaScript 函数,但它给了我一个 "Class Not Registered" 错误。 我从工具->参考添加了 Microsoft Script Control 1.0 我需要调用 JavaScript 从这个 Rest API 中获取一个 JSON 对象来计算 Excel 宏中的值。
This post 告诉我 ScriptControl 仅用于 32 位。我正在使用 64 位 Excel。 我也尝试使用此 link 中提到的方法,但它没有用,因为 VBA 无法识别 ActiveXObject
我的ExcelVBA调用简单JS函数的代码:
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
我在 Set jsObj = CreateObject("MSScriptControl.ScriptControl") 行收到 class not registered 错误 有没有其他方法可以从 VBA 调用 JavaScript 函数?还是我遗漏了什么?
不需要 ScriptControl 对象:您可以使用 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