我正在尝试在 VBA 中运行 Python 脚本,以便内部用户可以在仪表板中探索 KPI(Excel 作为 GUI,Python 作为后端)。
每次代码运行到最后一行时,电子表格都会消失,不会返回任何错误消息,但是当我在 PyCharm 中运行脚本时,Excel 上的仪表板可以立即刷新。
运行Python的VBA代码:
Sub RunPythonScriptWithXlwings()
' Specify the path to xlwings executable
Dim xlwingsPath As String
xlwingsPath = "C:\Users\rren\AppData\Local\Programs\Python\Python312\python.exe"
' Specify the path to your Python script
Dim scriptPath As String
scriptPath = "C:\Users\rren\OneDrive - MES\Desktop\Projects\52. MAR's report Python\mar_report.py"
' Construct the command to execute xlwings with the Python script
Dim command As String
command = """" & xlwingsPath & """ run """ & scriptPath & """"
' Use Shell to run the command
Shell command, vbNormalFocus
End Sub
运行脚本后尝试保持窗口打开,以便您可以检查是否有任何错误消息:
Sub Tester()
'run script and keep the cmd window open
RunScript "C:\Program Files\Python312\python.exe", _
"C:\Temp\_Python\test.py", True
End Sub
'Run script `scriptPath` with executable `exePath`
' Pass True to `keepOpen` to keep the cmd window
' open after the script is done
Sub RunScript(exePath As String, scriptPath As String, _
Optional keepOpen As Boolean = False)
Shell "cmd.exe /" & IIf(keepOpen, "k", "c") & " """"" & _
exePath & """ """ & scriptPath & """""", vbNormalFocus
End Sub