excel - 尝试从 VBA 运行 .bat 脚本失败且没有错误代码

标签 excel vba batch-file

概括:
我正在尝试使用 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 在下面评论中的建议,我更新了 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

当我运行此代码时,仍然没有任何 react 。

更新2:
今天早上我再次运行测试代码,重新启动计算机后,这次我收到一条弹出消息:“错误描述是:权限被拒绝”。然后我再次运行代码以查看是否可以复制此错误消息,并且没有弹出窗口!此外,无论我运行多少次代码,我都无法让错误消息重新出现。所以重新启动似乎做了一些事情......

“权限被拒绝”消息表明这是一个安全问题。任何人有解决它的任何想法?

最佳答案

不是答案,但评论太长了:

如果将以下内容放入文件中,将其另存为 test.vbs(不是文本文档:如果不小心,记事本会创建 test.vbs.txt):

Dim wsh, fullPath, ecode
Set wsh = WScript.CreateObject("WScript.Shell")
fullPath = "C:\programs\test.bat"
ecode = wsh.Run(fullPath, 1, True)
msgbox(ecode)

(根据您的情况调整完整路径)。将其保存到例如桌面,然后单击图标。怎么了?

关于excel - 尝试从 VBA 运行 .bat 脚本失败且没有错误代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55484909/

相关文章:

excel - 在初始化和更改其他组合框时设置组合框值

batch-file - PowerShell 将文件大小显示为 KB、MB 或 GB

Excel:计算自动过滤表中单元格和单元格之间的差异

.net - RegFree COM 从 C# 工作,而不是从 VBA 工作

c# - 如何使用 Microsoft.Interop.Word 将 excel 文件嵌入到 word 文档中?

vba - 将工作表内容复制到另一张工作表

windows - 如何处理批处理文件中 %* 的文件名格式不一致

windows - 在输出的第一行停止 FOR/F 命令(Windows 批处理)

c# - 通过 C# 在 Excel 中运行 vba 脚本

excel - 是否可以将数组的字段传递给具有可变参数数组的函数?