等待shell命令完成

等待shell命令完成

本文介绍了等待shell命令完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

但这可能无法在某些计算机上太慢。有没有办法系统地告诉Excel继续执行其余的VBA代码,直到 shell运行完毕为止?

解决方案

使用WScript.Shell代替,因为它有一个 waitOnReturn 选项:

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

wsh.RunC:\folder\runbat.bat,windowStyle,waitOnReturn

(从)


I'm running a simple shell command in Excel VBA that runs a batch file in a specified directory like below:

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

Sometimes the batch file might take longer on some computer to run, and there are proceeding VBA code that is dependent on the batch file to finish running. I know you can set a wait timer like below:

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

But that might not work on some computer that are too slow. Is there a way to systematically tell Excel to proceed with the rest of the VBA code until after the shell has finish running?

解决方案

Use the WScript.Shell instead, because it has a waitOnReturn option:

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 copied from Wait for Shell to finish, then format cells - synchronously execute a command)

这篇关于等待shell命令完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 07:37