Return result from Python to Vba

后端 未结 1 1821
隐瞒了意图╮
隐瞒了意图╮ 2020-11-28 12:49

I\'m using a VBA code that calls a python script. I can send a parameter to my python script and reading it using sys.argv[1].

In the python code I have

相关标签:
1条回答
  • 2020-11-28 13:02

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

    Credit

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

    0 讨论(0)
提交回复
热议问题