外部アプリケーションの実行と処理待ち

外部アプリケーションの実行と処理待ち。

VBAから呼び出された外部のアプリケーションの処理が終わる(画面を閉じる)のを待った後にVBAの残りの処理が実行されるように同期をはかって処理をさせます。

サンプルコードではShell関数を使用して外部のアプリケーション(Powershell)を起動し、そのアプリケーションが終了した後に後続の処理が実行されるようにしています。

 ●外部アプリケーションの実行と処理待ち

#If VBA7 And Win64 Then
    Declare PtrSafe Function WaitForSingleObject Lib "kernel32" _
        (ByVal hHandle As Long, ByVal dwMilliseconds As Long) As Long
    Declare PtrSafe Function OpenProcess Lib "kernel32" _
        (ByVal dwDesiredAccess As Long, ByVal bInheritHandle As Long, _
         ByVal dwProcessId As Long) As Long
    Declare PtrSafe Function CloseHandle Lib "kernel32" _
        (ByVal hObject As Long) As Long
#Else
    Declare Function WaitForSingleObject Lib "kernel32" _
        (ByVal hHandle As Long, ByVal dwMilliseconds As Long) As Long
    Declare Function OpenProcess Lib "kernel32" _
        (ByVal dwDesiredAccess As Long, ByVal bInheritHandle As Long, _
         ByVal dwProcessId As Long) As Long
    Declare Function CloseHandle Lib "kernel32" _
        (ByVal hObject As Long) As Long
#End If

Const PROCESS_ALL_ACCESS As Long = &H1F0FFF
Const INFINITE As Long = &HFFFF

'******************************************************************
' 外部プログラムの実行と処理待ち
'******************************************************************
Sub WaitApp()


    '外部アプリケーションの実行
    Dim lProcId As Long
    lProcId = shell("Powershell", vbNormalFocus)
    
    'プロセスハンドル取得
    Dim lHProc  As Long
    lHProc = OpenProcess(PROCESS_ALL_ACCESS, 0, lProcId)
    
    'プロセスハンドルが返されたかを判定
    If lHProc <> 0 Then
        'シグナル待ち
        Call WaitForSingleObject(lHProc, INFINITE)

        'プロセスクローズ
        CloseHandle lHProc
    End If
    
    MsgBox "終了"

End Sub