简体   繁体   English

Excel VBA 将参数传递给 Python 脚本

[英]Excel VBA pass arguments to Python script

I want to start a Python script from Excel VBA.我想从 Excel VBA 启动 Python 脚本。 I have this我有这个

Sub RunPython()

    Dim PythonExe As String, PythonScript As String, PythonArgs As String
    Dim objShell As Object
    
    PythonExe = "C:\MyProgs\Python\Python37\python.exe"
    PythonScript = "c:\scripts\Python\test.py"
    PythonArgs = "1 1"

    Set objShell = VBA.CreateObject("Wscript.Shell")
    
    objShell.Run PythonExe & " " & PythonScript
    'objShell.Run PythonExe & " " & PythonScript & " " & PythonArgs
    
End Sub

The Python script is written in a way to accept arguments on the command line or to prompt the user if no arguments are given. Python 脚本的编写方式是接受命令行上的参数,或者在未提供参数时提示用户。 The first objShell.run ... works, it starts the script and waits for user input.第一个 objShell.run ... 工作,它启动脚本并等待用户输入。 The second objShell.run ... does not work.第二个 objShell.run ... 不起作用。 The shell flashes and that's it.外壳闪烁,仅此而已。 If I call the python script from the command line directly like this如果我像这样直接从命令行调用 python 脚本

test.py 1 1

the script works.脚本有效。

So, how can I pass the arguments to the script using VBA?那么,如何使用 VBA 将参数传递给脚本? Ultimately, I want to read the two arguments from an Excel sheet and pass them.最终,我想从 Excel 工作表中读取两个参数并传递它们。

I've read Pass Python Argument Through VBA我已经阅读了通过 VBA 传递 Python 参数

I figured it out.我想到了。 In the Python script, I switched from positional arguments to optional.在 Python 脚本中,我从位置参数切换到可选参数。 As a result, I need to send the arguments like this结果,我需要发送这样的参数

PythonArgs = "--arg1 1 --arg2 1"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM