【发布时间】:2017-01-23 19:41:10
【问题描述】:
我正在使用调用 python 脚本的 VBA 代码。我可以向我的 python 脚本发送一个参数并使用sys.argv[1] 读取它。
在 python 代码中,我有一个函数,它接受给定的参数并返回一个值。
请问如何在 VBA 中获取返回值?
【问题讨论】:
我正在使用调用 python 脚本的 VBA 代码。我可以向我的 python 脚本发送一个参数并使用sys.argv[1] 读取它。
在 python 代码中,我有一个函数,它接受给定的参数并返回一个值。
请问如何在 VBA 中获取返回值?
【问题讨论】:
考虑使用 VBA Shell 的 StdOut 来捕获输出行的流。确保打印 Python 脚本以筛选值:
Python
...
print(outputval)
VBA (下面的s 将是字符串输出)
Public Sub PythonOutput()
Dim oShell As Object, oCmd As String
Dim oExec As Object, oOutput As Object
Dim arg As Variant
Dim s As String, sLine As String
Set oShell = CreateObject("WScript.Shell")
arg = "somevalue"
oCmd = "python ""C:\Path\To\Python\Script.py""" & " " & arg
Set oExec = oShell.Exec(oCmd)
Set oOutput = oExec.StdOut
While Not oOutput.AtEndOfStream
sLine = oOutput.ReadLine
If sLine <> "" Then s = s & sLine & vbNewLine
Wend
Debug.Print s
Set oOutput = Nothing: Set oExec = Nothing
Set oShell = Nothing
End Sub
信用
从@bburns.km借来的脚本,不接受的答案,来自这个SO post
【讨论】: