有关“在 VBA 中运行的 Python 脚本每次都会崩溃”的问题

问题描述 投票:0回答:1

我试图在 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
python excel vba dashboard
1个回答
0
投票

运行脚本后尝试保持窗口打开:

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

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
© www.soinside.com 2019 - 2024. All rights reserved.