Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
 
TitleStart another process and wait for it to complete in VBA
DescriptionThis example shows how to start another process and wait for it to complete in VBA.
KeywordsVBA, shell, shell and wait, OpenProcess, WaitForSingleProcess
CategoriesAPI, Office
 
Subroutine ShellAndWait uses Shell to launch another program. It then uses OpenProcess to get the new program's handle and calls WaitForSingleObject to wait until that process finishes.
 
' Start the indicated program and wait for it
' to finish, hiding while we wait.
Private Sub ShellAndWait(ByVal program_name As String, _
    ByVal window_style As VbAppWinStyle)
Dim process_id As Long
Dim process_handle As Long

    ' Start the program.
    On Error GoTo ShellError
    process_id = Shell(program_name, window_style)
    On Error GoTo 0

    ' Wait for the program to finish.
    ' Get the process handle.
    process_handle = OpenProcess(SYNCHRONIZE, 0, process_id)
    If process_handle <> 0 Then
        WaitForSingleObject process_handle, INFINITE
        CloseHandle process_handle
    End If

    Exit Sub

ShellError:
    MsgBox "Error starting task " & _
        txtProgram.Text & vbCrLf & _
        Err.Description, vbOKOnly Or vbExclamation, _
        "Error"
End Sub
 
While the call to WaitForSingleObject is running, the VBA application is frozen and will not respond.

NOTE: You will need to edit the code to tell the program where to find the executable that you want to run. This example includes a simple SayHi.exe program written in Visual Basic 2003 (you can easily write your own program in other versions of Visual Basic). It just displays a messagebox so you can easily control when it ends. After you observe that the Word application is waiting, click the OK button.

IMPORTANT NOTE: Working with API functions can be tricky in VBA. If something goes wrong while the API call is in progress, the entire host application (in this example Word) often crashes. To avoid losing a lot of work, SAVE YOUR WORK OFTEN!

 
 
Copyright © 1997-2006 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated