2016-09-15 37 views
2

我正在使用調用python腳本的VBA代碼。我可以發送一個參數給我的python腳本並使用sys.argv[1]來閱讀它。從Python返回到Vba的結果

在python代碼中,我有一個函數,它接受給定的參數並返回一個值。

請問如何獲得VBA的返回值?

回答

4

考慮使用VBA殼牌StdOut捕獲輸出線的流。一定有Python腳本打印篩選值:

的Python

... 
print(outputval) 

VBAs下面將字符串輸出)

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