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

时间:2015-08-20 20:23:44

标签: excel vba shell ftp

现在我有了这个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 FTP的语法。如果你能用正确的语法帮助我,我真的很感激!

2 个答案:

答案 0 :(得分:3)

使用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)的引用,以便您可以使用Intellisense功能)

答案 1 :(得分:0)

我更喜欢omegastripe的建议:

if

使用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 作为第二个参数来避免弹出窗口