使用 VBA 调用 Python 脚本并传递参数,Shell
函数和 Windows 脚本宿主(WSH)
都可以实现。以下是这两种方法的示例代码,展示如何将 VBA 中的参数变量传递给 Python 中的变量。
方法一:使用 Windows 脚本宿主(WSH)
这种方法更为灵活,可以同步等待 Python 脚本执行完成。
VBA代码
Sub RunPythonScript()
Dim objShell As Object
Dim pythonExePath As String
Dim scriptPath As String
Dim param1 As String
Dim param2 As String
Dim command As String
' 创建WScript.Shell对象
Set objShell = VBA.CreateObject("WScript.Shell")
' 指定Python解释器的路径
pythonExePath = "C:\Path\To\Python\python.exe"
' 指定Python脚本的路径
scriptPath = "C:\path\to\your_script.py"
' 定义要传递的参数
param1 = "argument1"
param2 = "argument2"
' 构建命令
command = pythonExePath & " " & scriptPath & " " & param1 & " " & param2
' 运行命令并等待完成
objShell.Run command, 1, True
End Sub
Python代码
import sys
def main():
if len(sys.argv) != 3:
print("Usage: python your_script.py <param1> <param2>")
sys.exit(1)
param1 = sys.argv[1]
param2 = sys.argv[2]
print(f"Parameter 1: {param1}")
print(f"Parameter 2: {param2}")
if __name__ == "__main__":
main()
方法二:使用 Shell 函数
这种方法简单直接,但异步执行,不能等待 Python 脚本执行完成。如果需要同步执行,可以考虑用 ShellAndWait
函数。
VBA代码
Sub RunPythonScript()
Dim pythonExePath As String
Dim scriptPath As String
Dim param1 As String
Dim param2 As String
Dim command As String
Dim shellResult As Long
' 指定Python解释器的路径
pythonExePath = "C:\Path\To\Python\python.exe"
' 指定Python脚本的路径
scriptPath = "C:\path\to\your_script.py"
' 定义要传递的参数
param1 = "argument1"
param2 = "argument2"
' 构建命令
command = pythonExePath & " " & scriptPath & " " & param1 & " " & param2
' 运行命令
shellResult = Shell(command, vbNormalFocus)
End Sub
Python代码
与上面的 Python 代码相同。
总结
- 使用 WSH:更适合需要同步执行的场景,能够等待 Python 脚本执行完成并返回结果。
- 使用 Shell:更简单直接,但异步执行,适合不需要等待结果的场景。
根据你的需求选择适合的方法。如果需要同步执行和等待结果,建议使用 WSH
。如果不需要等待结果,Shell
方法会更简单。