vba 在 Excel 中使用 JavaScript

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15911478/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 20:30:16  来源:igfitidea点击:

Using Javascript in Excel

javascriptexcelvbawsc

提问by Izomiac

I'm currently creating an Excel workbook that runs a Monte Carlo type simulation. The simulator code is currently in Javascript though, and porting entirely to VBA appears to be non-trivial given the team's inexperience with this language. So, I've been able to incorporate the javascript components into a WSC file, which works well. (Simplified example below.)

我目前正在创建一个运行 Monte Carlo 类型模拟的 Excel 工作簿。不过,模拟器代码目前是 Javascript,考虑到团队对这种语言缺乏经验,完全移植到 VBA 似乎并非易事。因此,我已经能够将 javascript 组件合并到一个 WSC 文件中,该文件运行良好。(下面的简化示例。)

    Sub Simulate()
        Set ATPSim = GetObject("script:http://www.example.com/ATPSim.wsc")
        'Set ATPSim = GetObject("script:C:\ATPSim.wsc")
        Dim ParamOne As Integer
        ParamOne = Range("B2").Value
        Dim ParamTwo As Double
        ParamTwo = Range("B3").Value
        Dim ParamThree As Double
        ParamThree = Range("B4").Value
        Range("B1").Value = ATPSim.simulate(ParamOne, ParamTwo, ParamThree)
    End Sub

Unfortunately, this requires me to host the javascript code or rely on unsophisticated users to update the absolute path. Is there a self-contained solution? I'd prefer to keep everything in one .xlsm file which can be e-mailed to the users.

不幸的是,这需要我托管 javascript 代码或依赖不熟练的用户来更新绝对路径。有独立的解决方案吗?我更愿意将所有内容都保存在一个 .xlsm 文件中,该文件可以通过电子邮件发送给用户。

回答by Laurence Moroney

You should be able to host the JS in a COM Component and use WSH to access it.

您应该能够在 COM 组件中托管 JS 并使用 WSH 访问它。

See the example here: How can I use JavaScript within an Excel macro?

请参阅此处的示例:如何在 Excel 宏中使用 JavaScript?