Discussion Locked

Excel VBA

0 helpful
3 replies
Closed to new repliesThis discussion is closed. It stays readable, but it takes no new replies.

When I write VBA in excel, I have to use
shell command call for external program. How can I ensure that the statement after the shell statement will not run until the execution of external program completed.

3 replies

by peyison

The following routine should do what you're looking for. Pass the name of the external program, and it will wait until the program is done.

Public Sub ShellAndWait(asCommand As String, asCommandLine As String)
Dim lPid As Long
Dim lHnd As LongDim lRet As Long

lPid = Shell(asCommand & " " & asCommandLine)
If lPid <> 0 Then
lHnd = OpenProcess(SYNCHRONIZE, 0, lPid)
If lHnd <> 0 Then
lRet = WaitForSingleObject(lHnd, INFINITE)
CloseHandle (lHnd)
End If
End If

End Sub

Put these declares at the top of the module.

Private Declare Function WaitForSingleObject Lib "kernel32" (ByVal hHandle As Long, ByVal dwMilliseconds As Long) As Long
Private Declare Function CloseHandle Lib "kernel32" (ByVal hObject As Long) As Long
Public Declare Function OpenProcess Lib "kernel32" (ByVal dwDesiredAccess As Long, ByVal bInheritHandle As Long, ByVal dwProcessId As Long) As Long

Private Const INFINITE = &HFFFF
Private Const SYNCHRONIZE =&H100000

Hope this helps.

This discussion is closed to new replies.