一尘不染

将结果从Python返回到Vba

python

我正在使用一个调用python脚本的VBA代码。我可以将参数发送到python脚本并使用读取sys.argv[1]

在python代码中,我有一个函数,该函数接受给定的参数并返回一个值。

请问如何在VBA中获得返回值?


阅读 162

收藏
2020-12-20

共1个答案

一尘不染

考虑使用VBA ShellStdOut捕获输出线流。确保打印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
2020-12-20