在继续使用脚本之前,Excel VBA等待Shell完成

现在我有这个VBA脚本:

Sub executeFTPBatch(ftpfileName) Call Shell("FTP -i -s:C:\Temp\" & ftpfileName & ".txt") On Error Resume Next Kill (C:\temp\" & ftpfileName & ".txt") End Sub 

问题是它甚至在FTP脚本开始之前杀死了文本文件。 我看到了一些wsh代码,但我不确定如何使用它来调用shell的语法。 如果你能用正确的语法来帮助我,我会非常感激!

使用WScript的Shell,那么你可以检查命令的状态

 Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long) Public Function RunCMD(ByVal strCMD As String) As String 'Runs the provided command Dim wsh As New wshShell Dim cmd As WshExec Dim x As Integer On Error GoTo wshError x = 0 RunCMD = "Error" Set cmd = wsh.Exec(strCMD) Do While cmd.Status = WshRunning Sleep 100 'for 1/10th of a second x = x + 1 If x > 1200 Then 'We've waited 2 minutes so kill it cmd.Terminate MsgBox "Error: Timed Out", vbCritical, "Timed Out" End If Loop RunCMD = cmd.StdOut.ReadAll & cmd.StdErr.ReadAll Exit Function wshError: RunCMD = cmd.StdErr.ReadAll End Function 

这是我使用的一个函数,它将返回命令的状态,包括任何错误。

(几乎忘了睡眠宣言!)

(编辑2:您还需要包含对Windows脚本宿主对象模型(wshom.ocx)的引用,以便您可以使用Intellisensefunction)

我更喜欢omegastripe的build议:

 Public Sub RunCMD(ByVal strCMD As String) 'Runs the provided command Dim wsh As Object Set wsh = CreateObject("WScript.Shell") Call wsh.Run(strCMD, 2, True) End Sub 

2作为第二参数,以避免窗口popup