使用 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 & " " & param