简体   繁体   English

从VBA调用Python(Winwrap)

[英]Call Python from VBA (Winwrap)

I am using a software which has a programming interface based on VBA / Winwrap Basic. 我正在使用具有基于VBA / Winwrap Basic的编程接口的软件。 I would like to use some machine learning libraries from Python, but I am not sure how to build it efficiently. 我想使用一些来自Python的机器学习库,但是我不确定如何有效地构建它。

The software is a dynamic simulation program. 该软件是一个动态仿真程序。 Every few time steps I would like to update (train) an artifical neural network (ANN) with new data using Pyhton libraries. 我想每隔几个步骤就使用Pyhton库使用新数据更新(训练)人工神经网络(ANN)。 I can see it is possible to call a script (like in How to call python script on excel vba? ). 我可以看到可以调用脚本(例如如何在excel vba上调用python脚本? )。 As I would have to call the script every few times again I am not sure how to handle the ANN object. 由于我不得不每隔几次调用一次脚本,因此我不确定如何处理ANN对象。 What is the best way to implement this? 实现此目的的最佳方法是什么?

If I understand you correctly, you would like to call a Python script and pass an argument and then perhaps handle the return data object? 如果我理解正确,那么您想调用Python脚本并传递一个参数,然后也许处理返回数据对象? If you use Windows and have VBA scripting environment, then perhaps you could use WSH (windows script host) object to run the script. 如果您使用Windows并具有VBA脚本环境,则也许可以使用WSH(Windows脚本宿主)对象运行脚本。 First declare the object 首先声明对象

Dim wsh As New IWshRuntimeLibrary.WshShell  'early binding

Dim wsh As Object
Set wsh = CreateObject("Wscript.Shell") ' late binding

And use the Run() method on the object, passing object and argument as string. 并在对象上使用Run()方法,将对象和参数作为字符串传递。 in this example i call powershell and pass scriptfile (run.ps1) as argument. 在此示例中,我调用powershell并将脚本文件(run.ps1)作为参数传递。 I just call the method, but don't get the return object from the script. 我只是调用该方法,但没有从脚本中获取返回对象。

res = wsh.Run("powershell path\run.ps1", WindowStyle:=False, WaitOnReturn:=True)
If res = 0 Then
    Call MsgBox("script ran successfully")
Else
    Call MsgBox("script ran unsuccessfully")
End If

In this example on the other hand, I use the Exec method to fetch the return data as json 另一方面,在此示例中,我使用Exec方法将返回数据提取为json

res = wsh.Exec("powershell path\run.ps1").StdOut.ReadAll()

Debug.Print res ' return data:

returnObject: 
{
    title: 'theTitle', 
    value: 'the value',
    status: 'status'
}

The run.ps1 basically returns a string: run.ps1基本上返回一个字符串:

return "returnObject: 
{
    title: 'theTitle', 
    value: 'the value',
    status: 'status'
}"

Edit: to call a python script file use python or py in place for powershell 编辑:调用python脚本文件,将pythonpy替换为powershell

res = wsh.Exec("python path\pythonfile.py").StdOut.ReadAll()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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