等待shell命令来完成[复制](Wait for shell command to complet

2019-08-21 22:29发布

这个问题已经在这里有一个答案:

  • 等待壳牌结束,然后格式细胞-同步执行的命令 6个答案

我跑在Excel VBA中一个简单的shell命令,运行在类似下面的指定目录下的批处理文件:

Dim strBatchName As String
strBatchName = "C:\folder\runbat.bat"
Shell strBatchName

有时,批处理文件可能需要更长一些的计算机上运行,​​并有继续VBA代码依赖于批处理文件来完成运行。 我知道你可以设置一个等待计时器象下面这样:

Application.Wait Now + TimeSerial(0, 0, 5)

但是,这可能不是某些计算机太慢上工作。 有没有一种方法,系统地告诉Excel中使用VBA代码的其余部分进行到壳有结束运行?

Answer 1:

使用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

(IDEA从复制等待壳牌结束,然后格式细胞-同步执行的命令 )



Answer 2:

添加以下子:

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

如果你添加一个引用到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

这个版本应该是更有效的。



Answer 3:

保存在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   


Answer 4:

你与在运行命令括号的变化提出了工作正常使用VBA我

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
wsh.Run "C:\folder\runbat.bat", windowStyle, waitOnReturn


Answer 5:

你有没有可能在批创建时,它的完成文件和VBA等到该文件的创建? 或有批量删除flagfile时,它的完成和VBA等待,直到flagfile没有了吗?



Answer 6:

无论是外壳链接到一个对象,已在批量作业终止Shell对象(出口)和具有VBA代码继续一旦壳对象=什么?

或者看看这个: 捕捉产值从VBA shell命令?



Answer 7:

这是我用有VB等待过程完成后再继续。 我没有写这个,不邀功。

这是在其他一些公开论坛提供和工作对我非常好:

需要对以下声明RunShell子程序:

Option Explicit

Private Declare Function OpenProcess Lib "kernel32" (ByVal dwDesiredAccess As Long, ByVal bInheritHandle As Long, ByVal dwProcessId As Long) As Long

Private Declare Function GetExitCodeProcess Lib "kernel32" (ByVal hProcess As Long, lpExitCode As Long) As Long

Private Declare Function CloseHandle Lib "kernel32" (ByVal hObject As Long) As Long

Private Const PROCESS_QUERY_INFORMATION = &H400

Private Const STATUS_PENDING = &H103&

'then in your subroutine where you need to shell:

RunShell (path and filename or command, as quoted text)


Answer 8:

昏暗的WSH新的WshShell

CHDIR“批处理文件的目录”

wsh.run“批处理文件的完整路径”,vbnormalfocus,真

做儿子



文章来源: Wait for shell command to complete [duplicate]