我正在使用调用python脚本的VBA代码。我可以将参数发送到我的python脚本并使用sys.argv[1]
读取它。
在python代码中,我有一个函数,它接受给定的参数并返回一个值。
请问如何在VBA中获得返回值?
答案 0 :(得分:6)
考虑使用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,未接受的答案中借用