将结果从 Python 返回到 Vba [英] Return result from Python to Vba

查看:44
本文介绍了将结果从 Python 返回到 Vba的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

In the python code I have a function that takes the given argument and return a value.

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

Please how can I get the return value in VBA?

推荐答案

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

这篇关于将结果从 Python 返回到 Vba的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆