通过Excel / VBA运行Python脚本

时间:2022-05-28 04:54:12

I've been trying to find a solution to this problem for ages. I have some python scripts that need to be updated regularly and would like to be able to use a macro to accomplish this. Right now I double click the files and they execute via Shell without a problem.

我一直试图找到这个问题的解决方案多年。我有一些python脚本需要定期更新,并希望能够使用宏来完成此任务。现在我双击文件,它们通过Shell执行没有问题。

Sub RunPyScript()

Dim Ret_Val As Variant
Dim command As String

command = Chr(34) & "C:\Users\Jon Doe\python.exe" & Chr(34) & " " & Chr(34) & "C:\Users\Jon Doe\" & "\Roto.py" & Chr(34)
Ret_Val = Shell(command, vbNormalFocus)

End Sub

When I attempt to run the above macro, it looks as though it will run the same as when I double click, but Shell exits before the script is executed (I think that's the issue, not positive). If anyone could help me out I'd really appreciate it.

当我尝试运行上面的宏时,看起来它将像我双击时一样运行,但Shell在执行脚本之前退出(我认为这是问题,而不是正面)。如果有人能帮助我,我真的很感激。

1 个解决方案

#1


4  

Dim command As String
Dim objShell

command = Chr(34) & "C:\Users\John Doe\python.exe" & Chr(34) & " " & Chr(34) & "C:\Users\John Doe\" & "\roto.py" & Chr(34)

Set objShell = CreateObject("WScript.Shell")

objShell.Run command, 1, True

'Settings for WindowStyle:
'     0 Hide the window (and activate another window.)
'     1 Activate and display the window. (restore size and position) Specify this flag when displaying a window for the first time.
'     2 Activate & minimize.
'     3 Activate & maximize.
'     4 Restore. The active window remains active.
'     5 Activate & Restore.
'     6 Minimize & activate the next top-level window in the Z order.
' *** 7 Minimize. The active window remains active.
'     8 Display the window in its current state. The active window remains active.
'     9 Restore & Activate. Specify this flag when restoring a minimized window.
'    10 Sets the show-state based on the state of the program that started the application.

#1


4  

Dim command As String
Dim objShell

command = Chr(34) & "C:\Users\John Doe\python.exe" & Chr(34) & " " & Chr(34) & "C:\Users\John Doe\" & "\roto.py" & Chr(34)

Set objShell = CreateObject("WScript.Shell")

objShell.Run command, 1, True

'Settings for WindowStyle:
'     0 Hide the window (and activate another window.)
'     1 Activate and display the window. (restore size and position) Specify this flag when displaying a window for the first time.
'     2 Activate & minimize.
'     3 Activate & maximize.
'     4 Restore. The active window remains active.
'     5 Activate & Restore.
'     6 Minimize & activate the next top-level window in the Z order.
' *** 7 Minimize. The active window remains active.
'     8 Display the window in its current state. The active window remains active.
'     9 Restore & Activate. Specify this flag when restoring a minimized window.
'    10 Sets the show-state based on the state of the program that started the application.