I'm launching a program from a VBA macro and I need to wait for it to finish running before I can go and post-process the resulting data. So far, I've been satisfied with the following as the running time was pretty consistent (about 2sec.) :
While FileLen(outputFilename) < 9000 And (Timer - Chrono) < 10
Wend
Indeed I've observed that all the result data is written in one go and before that, the output size doesn't exceed 9Ko.
Anyway, for some reason, the program isn't consistent anymore so I looked a bit more into a clean solution to wait for the shell process to stop.
I found ideas about WaitForSingleObject
and the module ShellAndWait
which I found here. This post is what helped me with finding some functions.
My problem now is that the macro keeps running while the Shell is still open. From what I understand, WaitForSingleObject
returns 0, which should mean the Shell is closed (or finished running), but it's not.
More specifically, in ShellAndWait
,
WaitRes = WaitForSingleObject(ProcHandle, DEFAULT_POLL_INTERVAL)
raises 0. I tried to extract the significant part of the code by adapting it a bit :
Private Declare Function WaitForSingleObject Lib "kernel32" (ByVal hHandle As Long, ByVal dwMilliseconds As Long) As Long
Private Declare Function OpenProcess Lib "kernel32" (ByVal dwDesiredAccess As Long, ByVal bInheritHandle As Long, ByVal dwProcessId As Long) As Long
Private Declare Function CloseHandle Lib "kernel32" (ByVal hObject As Long) As Long
Private Const SYNCHRONIZE = &H100000
Public Const INFINITE = &HFFFF
Public Const PROCESS_ALL_ACCESS = &H1F0FFF
Sub launch()
analysisPath = "Path to the files to feed to the programm"
ShellCommand = "Program to run + arguments"
ChDrive ThisWorkbook.Path
ChDir analysisPath
fileID = Shell(ShellCommand, vbNormalFocus)
ProcHandle = OpenProcess(SYNCHRONIZE, False, fileID)
If ProcHandle<>0 Then
WaitRes = WaitForSingleObject(ProcHandle, INFINITE)
Else
MsgBox "Failed running Nastran"
End If
fileID = CloseHandle(ProcHandle)
End Sub
And WaitRes
still raises 0.
Am I using WaitForSingleObject
wrong and if so, could you point me in the right direction ?
edit : It also doesn't work with the solution accepted in this post (meaning the shell runs but doesn't stop the macro to keep going). Could it be due to the specific program I'm running which would behave strangely ?