VBA Shell函数无法执行Python脚本

我尝试使用下面的VBA代码执行Python脚本(请运行sub Test() ),

 Option Explicit #If VBA7 And Win64 Then Declare PtrSafe Function OpenProcess Lib "kernel32" _ (ByVal dwDesiredAccess As Long, _ ByVal bInheritHandle As Long, _ ByVal dwProcessId As Long) As Long Declare PtrSafe Function GetExitCodeProcess Lib "kernel32" _ (ByVal hProcess As Long, lpExitCode As Long) As Long #Else Declare Function OpenProcess Lib "kernel32" _ (ByVal dwDesiredAccess As Long, _ ByVal bInheritHandle As Long, _ ByVal dwProcessId As Long) As Long Declare Function GetExitCodeProcess Lib "kernel32" _ (ByVal hProcess As Long, lpExitCode As Long) As Long #End If Const interpreter_path As String = "C:\Users\dongm\Anaconda2\python.exe" Sub Test() RegressAndWait "Output" End Sub Private Sub RegressAndWait(ByVal output_folder_name As String) Dim TaskID As Long, hProc As Long, lExitCode As Long Dim ACCESS_TYPE As Integer, STILL_ACTIVE As Integer ACCESS_TYPE = &H400 STILL_ACTIVE = &H103 Dim Program As String, args(1 To 5) As String args(1) = interpreter_path args(2) = ThisWorkbook.path & "\regressions.py" args(3) = """" & "dummy" & """" args(4) = """" & "." & """" args(5) = """" & output_folder_name & """" Program = Join(args, " ") ChDir ThisWorkbook.path TaskID = Shell(Program, vbNormalFocus) hProc = OpenProcess(ACCESS_TYPE, False, TaskID) If Err <> 0 Then MsgBox "Cannot run regressions.py", vbCritical, "Error" Exit Sub End If Do GetExitCodeProcess hProc, lExitCode DoEvents Loop While lExitCode = STILL_ACTIVE End Sub 

运行sub Test() ,我可以看到提示窗口闪烁,然后退出,就好像提示窗口打开,但从来没有使用过(我看不到任何消息写入提示窗口,因为它消失得真快)。

但是,我可以通过打开Anaconda Prompt窗口手动运行python脚本,而不使用VBA,然后cd到我当前的文件夹地址(为什么selectChDir ThisWorkbook.path ),然后inputpython regressions.py "dummy" "." 到提示窗口运行python脚本。

我的VBA代码基本上只是重复我手动完成,但为什么它不工作?

另外,我的代码很好用,但是今天早上我发现它不再有效。


仅供参考,在跳入Shell函数之前,我使用debugging器进入了?Program ,即时窗口中的?Program给了我

C:\Users\dongm\Anaconda2\python.exe C:\Company\Insurance Project\Health Insurance Company Regression\regressions.py "dummy" "." "Output"


经过一些操作,似乎我不能再调用Python脚本的原因是因为我的文件夹名称中有空格。 我记得,今天早上我把相关文件移到了不同​​的目录。 我只是把Insurance Project改成Insurance ProjectHealth Insurance Company Regression Health_Insurance_Company_RegressionHealth_Insurance_Company_Regression ,然后一切恢复正常。 这真是一个有趣的bug,我从来没有见过,但是我想知道是什么原因造成的。 Excel VBA或Python和Anaconda?

Interesting Posts