等待shell命令完成

use*_*047 35 shell excel vba batch-file

我在Excel VBA中运行一个简单的shell命令,它在指定的目录中运行批处理文件,如下所示:

Dim strBatchName As String
strBatchName = "C:\folder\runbat.bat"
Shell strBatchName
Run Code Online (Sandbox Code Playgroud)

有时批处理文件在某些​​计算机上运行可能需要更长时间,并且正在进行的VBA代码依赖于批处理文件来完成运行.我知道你可以设置如下的等待计时器:

Application.Wait Now + TimeSerial(0, 0, 5)
Run Code Online (Sandbox Code Playgroud)

但这可能不适用于某些速度太慢的计算机.有没有一种方法,系统地告诉Excel中使用VBA代码的其余部分进行到壳具有完成运行?

Nat*_*man 67

请改用WScript.Shell,因为它有一个waitOnReturn选项:

Dim wsh As Object
Set wsh = VBA.CreateObject("WScript.Shell")
Dim waitOnReturn As Boolean: waitOnReturn = True
Dim windowStyle As Integer: windowStyle = 1

wsh.Run "C:\folder\runbat.bat", windowStyle, waitOnReturn
Run Code Online (Sandbox Code Playgroud)

(想法从Wait for Shell复制 完成,然后格式化单元格 - 同步执行命令)

  • Nate的答案中的这一行:wsh.Run("C:\ folder\runbat.bat",windowStyle,waitOnReturn)给出了一个编译错误:"Expected:"=".当删除括号时,它的工作原理为:wsh.Run"C :\ folder\runbat.bat",windowStyle,waitOnReturn我不确定它是否与此事有关,但我正在运行Win8和Excel 2013. (6认同)
  • 在.net中,但在VBA中没有... (2认同)
  • 由于"方法'运行'对象'IWshShell3'失败"对我不起作用"错误号-2147024894 (2认同)
  • 它可能不适合你,因为你的路径有空格 @Qbik @Santosh 使用 ```wsh.Run Chr(34) & YourPathWithSpaces & Chr(34)``` (2认同)

小智 8

添加以下Sub:

Sub SyncShell(ByVal Cmd As String, ByVal WindowStyle As VbAppWinStyle)
VBA.CreateObject("WScript.Shell").Run Cmd, WindowStyle, True
End Sub
Run Code Online (Sandbox Code Playgroud)

如果您添加引用C:\Windows\system32\wshom.ocx也可以使用:

Sub SyncShell(ByVal Cmd As String, ByVal WindowStyle As VbAppWinStyle)
Static wsh As New WshShell
wsh.Run Cmd, WindowStyle, True
End Sub
Run Code Online (Sandbox Code Playgroud)

这个版本应该更有效率.


小智 6

将 bat 文件保存在“C:\WINDOWS\system32”上并使用下面的代码它正在工作

   Dim wsh As Object
   Set wsh = VBA.CreateObject("WScript.Shell")
   Dim waitOnReturn As Boolean: waitOnReturn = True
   Dim windowStyle As Integer: windowStyle = 1
   Dim errorCode As Integer

   errorCode = wsh.Run("runbat.bat", windowStyle, waitOnReturn)

If errorCode = 0 Then
    'Insert your code here
Else
    MsgBox "Program exited with error code " & errorCode & "."
End If   
Run Code Online (Sandbox Code Playgroud)