Skip to main content
 首页 » 编程设计

python之从 VBA 运行 python 脚本

2025年01月19日7Free-Thinker

场景:我正在尝试从 excel 中的 vba 代码运行 python 脚本。代码运行没有错误,但没有产生任何结果。

VBA 代码:

Private Sub CommandButton1_Click() 
 
    Dim Ret_Val 
    Dim args As String 
 
    args = "\\X\s\D\D\Data_manager.py" 
    Ret_Val = Shell("C:\Users\D\AppData\Local\Continuum\anaconda2\python.exe" & " " & args, vbNormalFocus) 
 
'also tried this, same result 
Ret_Val = Shell("C:\Users\D\AppData\Local\Continuum\anaconda2\python.exe \\X\s\D\D\Data_manager.py") 
 
End Sub 

问题:几个月前我运行了同样的代码,它工作得很好,但现在,由于某种原因,它表现得很奇怪。对可能发生的事情有什么想法吗?

OBS1:我还阅读了 SO 中存在类似问题的其他帖子,但对于那些,VBA 似乎会抛出错误,这在我的代码中不会发生。

OBS2:我知道代码没有产生任何结果,因为我的 python 脚本非常简单,它需要几个输入并将它们输出到一个 csv 文件。

请您参考如下方法:

应该是这样的

RetVal = Shell("<full path to python.exe> " & "<full path to your python script>") 

或者如果 python 脚本与工作簿在同一个文件夹中,那么您可以尝试:

RetVal = Shell("<full path to python.exe> " & ActiveWorkBook.Path & "\<python script name>") 

How to call python script on excel vba?

或者,试试这个:

Dim wsh As Object 
Set wsh = VBA.CreateObject("WScript.Shell") 
Dim waitOnReturn As Boolean: waitOnReturn = True 
Dim windowStyle As Integer: windowStyle = 1 
 
wsh.Run "cmd.exe /S /C perl a.pl c:\temp", windowStyle, waitOnReturn