【发布时间】:2019-04-02 23:30:59
【问题描述】:
总结: 我正在尝试使用 Excel VBA 在 Windows 机器上运行 .bat 脚本。我在网上找到了描述如何执行此操作的参考资料,并且我已按照其中包含的说明进行操作。但是,我的 .bat 文件没有运行。
详情: 我的 .bat 文件(“test.bat”)包含以下代码:
echo off
echo This is a test...
pause
exit
它位于我的桌面上,路径如下:“C:\Users\User1\Desktop”。当我双击此 .bat 文件或从命令行调用它时,它会表现出所需的行为。也就是说,它会暂停并等待我按任意键。
我正在尝试使用以下代码从 Excel VBA 运行相同的 .bat 文件:
Sub testBatchScript()
'Print a message to the immediate window to confirm subroutine execution
Debug.Print "The subroutine is running."
'Initialize a windows shell object
Dim wsh As WshShell
Set wsh = New WshShell
'Construct the full path to the .bat file
Dim fullPath As String
fullPath = Chr(34) + "C:\Users\User1\Desktop\test.bat" + Chr(34)
'Run the .bat file
Dim eCode As Long
eCode = wsh.Run(fullPath, waitonreturn:=True, windowstyle:=1)
If eCode <> 0 Then
MsgBox ("An error occurred.")
End If
End Sub
当我运行这个子程序时,什么也没有发生。没有弹出CMD窗口,也没有弹出提示错误的消息框。但是,由于即时窗口中显示的消息,我确实知道子例程正在运行。
我很困惑为什么这不起作用。更令人困惑的是,就在几周前,我还能够成功地从 VBA 调用 .bat 脚本..
有人有什么解释或建议吗?
更新1: 根据@Dhamo 在下面 cmets 中的建议,我更新了 VBA 代码并进行了错误处理:
Option Explicit
Sub testBatchScript()
On Error GoTo EH:
'Print a message to the immediate window to confirm subroutine execution
Debug.Print "The subroutine is running."
'Initialize a windows shell object
Dim wsh As WshShell
Set wsh = New WshShell
'Construct the full path to the .bat file
Dim fullPath As String
fullPath = Chr(34) + "C:\Users\User1\Desktop\test.bat" + Chr(34)
'Run the .bat file
Dim eCode As Long
eCode = wsh.Run(fullPath, waitonreturn:=True, windowstyle:=1)
If eCode <> 0 Then
MsgBox ("An error occurred.")
End If
Exit Sub
EH:
MsgBox ("The error description is: " & Err.Description)
End Sub
当我运行 此 代码时,仍然没有任何反应。
更新2: 我今天早上再次运行了测试代码,在重新启动计算机后,这次我收到了一条弹出消息:“错误描述是:权限被拒绝”。然后我再次运行代码以查看是否可以复制此错误消息,并且没有弹出窗口!此外,无论我运行多少次代码,我都无法让错误消息重新出现。所以重启好像做了点什么……
“权限被拒绝”消息表明这是一个安全问题。任何人有任何解决它的想法?
【问题讨论】:
-
您是否添加了“Windows 脚本宿主对象模型”参考?如果还没有,请添加并尝试 [? == VBA 窗口,点击工具 > 参考]
-
@Dhamo:是的,我有。
-
@Dhamo:对不起,我不明白您所说的“尝试 [? == VBA 窗口...”是什么意思。
-
在第一行添加显式选项并启用错误处理程序 [on error goto EH:] 并定义 EH [EH: msgbox err.description]。至少你会在一定程度上了解实际问题。上面的代码对我来说工作正常[我使用 v2016]
-
如果您已经添加了参考,您可以忽略进一步的评论
标签: excel vba batch-file