批处理文件未通过Excel VBA运行

时间:2016-01-25 21:06:55

标签: windows excel-vba batch-file vba excel

我有一个运行python脚本的批处理文件。如果我手动单击并尝试执行该批处理文件,它运行完全正常。但是,当我尝试通过Excel VBA运行它时,文件不会执行。批处理文件中的代码是这样的:

%cd
file.py

批处理文件&我想要执行的文件位于同一目录中。

如果输入确切的目录地址,则代替上述代码中的%cd%,Excel VBA运行批处理文件没有问题。例如,如果我的批处理文件看起来像这样,那么根本就没有问题。

c:
cd c:\folder
file.py

2 个答案:

答案 0 :(得分:2)

在批处理文件中使用以下代码:

@echo off
cd /D "%~dp0"
python.exe file.py

如果批处理文件总是在已知Python安装位置的同一台机器上执行,那么用完整路径指定python.exe会更好。

命令cd /D "%~dp0"将当前目录设置为批处理文件的目录,即使它位于与当前驱动器不同的驱动器上。在命令提示符窗口cd /?call /?中运行以获取详细信息。

* .py文件不是可执行文件。它是一个Python脚本,需要Python解释器才能执行某些操作。因此,最好使用脚本文件作为参数显式运行Python解释器,而不是让Windows通过Windows注册表找出要用于打开 a * .py文件的应用程序,这将导致执行脚本python.exe是为打开操作注册的应用程序。

答案 1 :(得分:0)

非常感谢您,我很长时间以来一直对此感到困扰。现在,它变得更加有意义。我需要执行文件夹中的所有SQL。 **我是批处理文件的新手

这是我的答案示例:-

Excel CommandButton代码:

Private Sub CommandButton1_Click()
Dim Username1 As String
Dim Password1 As String
Dim Server1 As String
Dim Database1 As String
Dim CommandString As String

Username1 = Cells(5, 6).Value
Password1 = Cells(6, 6).Value
Server1 = Cells(7, 6).Value
Database1 = Chr(34) + Cells(8, 6).Value + Chr(34)
CommandString = ThisWorkbook.Path & "\Place_SQL_Scripts_in_here\ExecuteAllSQLWithExcelParameters.bat" + " " + Username1 + " " + Password1 + " " + Server1 + " " + Database1
Call Shell("cmd.exe /c" & CommandString, vbNormalFocus)
End Sub

批处理文件代码:@Mofi-我使用了您的代码段

@Echo off 

goto :init

:init
setlocal 
set Username1=%1
set Password1=%2
set Server1=%3
set Database1=%4
Echo.
Echo Executing All SQL Scripts in Folder "Place_SQL_Scripts_in_here"
Echo.

cd /D "%~dp0"

for %%G in (*.sql) do (echo [Executing %%G] & echo. & sqlcmd -S %Server1% -d %Database1% -U %Username1% -P %Password1% -i "%%G" & echo.)
Goto :End

:End
Echo Completed
Echo.
PAUSE
endlocal
goto :EOF

我也收到了该帖子(How to execute Batch File while passing parameters from Excel)的帮助