将结果从 Python 返回到 Vba
- 2025-04-15 09:18:00
- admin 原创
- 27
问题描述:
我正在使用调用 Python 脚本的 VBA 代码。我可以将参数发送到我的 Python 脚本并使用 读取它sys.argv[1]
。
在 python 代码中我有一个函数,它接受给定的参数并返回一个值。
请问如何在 VBA 中获取返回值?
解决方案 1:
考虑使用 VBA ShellStdOut
来捕获输出行流。确保 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:PathToPythonScript.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帖子
相关推荐
热门文章
项目管理软件有哪些?
热门标签
曾咪二维码
扫码咨询,免费领取项目管理大礼包!
云禅道AD