【问题标题】:Return result from Python to Vba从 Python 返回结果到 Vba
【发布时间】:2017-01-23 19:41:10
【问题描述】:

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

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

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

【问题讨论】:

    标签: python vba


    【解决方案1】:

    考虑使用 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

    【讨论】:

    • 这行得通,但是当有很多行要迭代的输出时,它会非常慢。你知道为什么这么慢吗?
    • @jippyjoe4,一切都取决于您的用例以及您所说的极慢。如果您需要帮助,请提出一个新问题。
    猜你喜欢
    • 2018-02-21
    • 1970-01-01
    • 1970-01-01
    • 2021-01-04
    • 1970-01-01
    • 1970-01-01
    • 2017-09-30
    • 2012-08-21
    相关资源
    最近更新 更多