Excel VBA 等待 Shell 完成后再继续脚本
Excel VBA Wait For Shell to Finish before continuing with script
现在我有这个 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 时如何使用它的语法。如果您能帮助我提供正确的语法,我将不胜感激!
改用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
这是我使用的一个函数,它将return命令的状态,包括任何错误。
(差点忘了Sleep声明!)
(编辑 2:您还需要包含对 Windows 脚本宿主对象模型 (wshom.ocx) 的引用,以便您可以使用 Intellisense 功能)
我更喜欢 omegastripe 的建议:
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
作为第二个参数以避免 windows 弹出
现在我有这个 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 时如何使用它的语法。如果您能帮助我提供正确的语法,我将不胜感激!
改用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
这是我使用的一个函数,它将return命令的状态,包括任何错误。
(差点忘了Sleep声明!)
(编辑 2:您还需要包含对 Windows 脚本宿主对象模型 (wshom.ocx) 的引用,以便您可以使用 Intellisense 功能)
我更喜欢 omegastripe 的建议:
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
作为第二个参数以避免 windows 弹出