gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 20:28:09 30 4
gpt4 key购买 nike

概括:
我正在尝试使用 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/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com