使用VBA从Excel运行bat文件

3

我有一个包含脚本的test.bat文件:

copy host_name table_name -p table_name -t "file.csv"

通常情况下,当我点击它时,它能正常工作。现在,我想使用vba从Excel运行test.bat文件。

strPath = ws1.Range("G2").value & "\" 'Directory to folder with bat
Shell strPath & "\test.bat", vbNormalFocus

有些问题出现了,因为我只看到快照/剪辑:就像某些东西在一秒钟内打开和关闭...


有时候从批处理文件中读取输出可能很困难,因为它们会很快关闭。你可以在脚本的末尾添加pause命令。这将防止窗口关闭,直到你按下一个键。或者你可以将输出重定向到日志文件。无论哪种情况,这都应该允许你捕获批处理返回的任何错误消息。 - David Rushton
2
字符串构建完成后,您是否有两个反斜杠? - ThunderFrame
是的,反斜杠会被转义为字符串路径中的一部分。 - 4est
2个回答

8

刚刚解决了它:

ChDir ThisWorkbook.Path & "\folder\"
Shell ThisWorkbook.Path & "\folder\test.bat", vbNormalFocus

0

我不确定你在使用哪种 VBA 和 shell,但尝试类似这样的代码

Dim winShell As Object: Set winShell = CreateObject("WScript.Shell")

    Dim WaitOnReturn As Boolean: WaitOnReturn = False
    Dim windowStyle As Integer: windowStyle = 1

    'Run the desired pair of shell commands in command prompt.
    Call winShell.Run("cmd /k " & command1 & " & " & command2, windowStyle, WaitOnReturn)

    'Release pointer to the command prompt.
    Set winShell = Nothing

只需用您的命令替换我的命令,看看是否有效

编辑:为了完整起见,我的命令看起来像这样

Dim command1 As String: command1 = "cd /d" & projectDirectoryCell.Value

Dim command2 As String: command2 = "create_sensi.bat"

我尝试执行 command1 = "..cd",但是 shell 总是显示:C:\users\my_user\documents>如何更改根目录? - 4est
就像在标准命令行中一样,您可以使用类似于“cd /d“C:\Program Files"”这样的命令。@4est - Luboš Suk

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接