Python脚本在被VBA调用时突然停止运行

2024-04-26 13:49:32 发布

您现在位置:Python中文网/ 问答频道 /正文

编辑:我在下面发帖时出错,说它在终端运行时可以工作(我必须在前面测试过)python.exe安装了环境(env)文件夹中的程序pycharm,而不是我最初进行的独立安装。你知道吗

EDIT#2:问题再次出现,但没有更改任何VBA或python脚本。(仍在使用pycharm环境文件夹)python.exe)

我有一个VBA sub,可以创建WScript.Shell对象,然后执行一个python脚本,该脚本在过去几周内运行良好。在继续构建python脚本中的代码之后(销售历史.py)python脚本不再正确运行并生成退出代码“1”。通过pyCharm或console运行脚本时,脚本完全正确执行,退出代码为0。你知道吗

我尝试了下面包含的一些不同的代码变体。的目录python.exe以及销售历史.py都是正确的,并且不包含任何空格(我知道这是一个常见错误)

还添加了参考文献: Visual Basic应用程序, Microsoft Excel 16.0对象库, OLE自动化, Microsoft Office 16.0对象库, Microsoft HTML对象库, Microsoft脚本运行时, Microsoft XML 3.0版, Windows脚本宿主对象模型

Sub RunPythonScript(pyScript As String)

'Declare varables
Dim objShell As Object
Dim PythonExe, PythonScript As String
Dim waitOnReturn As Boolean, windowStyle As Integer, retVal As Long
waitOnReturn = True
windowStyle = 0

'Create new object shell
Set objShell = VBA.CreateObject("WScript.Shell")
'Tried Set objShell CreateObject("WScript.Shell")

'Provide the file path to the Python Exe
PythonExe = "C:\Users\steve.levy\AppData\Local\Programs\Python\Python37-32\python.exe"
'PC1: C:\Users\Steven\AppData\Local\Programs\Python\Python37-32\python.exe
'PC2: C:\Users\steve.levy\AppData\Local\Programs\Python\Python37-32\python.exe
'make sure you use triple quotes if there is a space in the file path name. single quotes are ok if not

'Procide the file path to the Python Script
PythonScript = "C:\Users\steve.levy\Documents\elberon\api\" & pyScript
'PC1: C:\Users\Steven\Documents\api\
'PC2: C:\Users\steve.levy\Documents\elberon\api\
Debug.Print (PythonExe)
Debug.Print (PythonScript)

'Run the Python Script
'Tried: Call objShell.Run(PythonExe & " " & PythonScript, 0, True)
'Tried: retVal = objShell.Run(PythonExe & " " & PythonScript, 0, True)
retVal = objShell.Run("C:\Users\steve.levy\AppData\Local\Programs\Python\Python37-32\python.exe C:\Users\steve.levy\Documents\elberon\api\salesHist.py", 0, True)

If retVal = 0 Then
    'Do Nothing
Else
    MsgBox "Script could not run. Program exited with error code " & retVal & "."
End If

End Sub

Sub pyscr()
    Call executePython.RunPythonScript("salesHist.py")
End Sub

程序存在,出现消息框: “脚本无法运行。程序退出,错误代码为1。“


Tags: the对象代码py脚本asexeusers