且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将结果从 Python 返回到 Vba

更新时间:2023-11-29 15:30:28

考虑使用 VBA Shell 的 StdOut 来捕获输出行流.一定要打印 Python 脚本来筛选值:

Consider using VBA Shell's StdOut to capture a stream of the output lines. Be sure to have the Python script print to screen the value:

Python

...
print(outputval)

VBA (下面的s是字符串输出)

VBA (s below would be string output)

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 帖子

Script borrowed from @bburns.km, non-accepted answer, from this SO post