我尝试使用下面的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
窗口,然后cd
到我当前的文件夹地址(为什么ChDir ThisWorkbook.path
)手动运行python脚本而不使用VBA,然后输入{{ 1}}到提示窗口运行python脚本。
我的VBA代码基本上只是重复我手动完成的操作,但为什么它不起作用?
此外,我的代码过去工作得很好很奇怪,但是今天早上我发现它已经不再适用了。
仅供参考,在进入python regressions.py "dummy" "."
函数之前,我使用调试器进入Program
,即时窗口中的Shell
给了我
?Program
经过一些操作后,似乎我不再能够调用Python脚本的原因是因为我的文件夹名称中有空格。我记得,我今天早上将相关文件移到了另一个目录。我刚刚将C:\Users\dongm\Anaconda2\python.exe C:\Company\Insurance Project\Health Insurance Company Regression\regressions.py "dummy" "." "Output"
更改为Insurance Project
,将Insurance_Project
更改为Health Insurance Company Regression
,然后一切都恢复正常。这真是一个有趣的错误,我以前从未见过,但我想知道是什么原因造成的。 Excel VBA或Python和Anaconda?