我正在使用调用python脚本的VBA代码.我可以将参数发送到我的python脚本并使用它来读取它sys.argv[1].
在python代码中,我有一个函数,它接受给定的参数并返回一个值.
请问如何在VBA中获得返回值?
考虑使用VBA Shell StdOut来捕获输出行的流.确保打印Python脚本以筛选值:
蟒蛇
...
print(outputval)
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
信用
剧本借用@bburns.km,未被接受的答案,从这篇SO帖子中借来的