L’objectif est simple.
Dans un script VBA (dans Access par exemple), j’ai besoin d’exécuter un fichier cmd ou bat et d’attendre la fin d’exécution pour continuer le déroulement du script VBA.
Déclaration des API (en-tête du module)
1 2 |
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 Public Const INFINITE = &HFFFF |
Ajouter cette fonction :
1 2 3 4 |
Function WaitForEnd(strFileToExec) As Long Set wsh = CreateObject("WScript.Shell") WaitForEnd = wsh.Run(strFileToExec, 1, True) End Function |
Si vous ne voulez pas que la fenêtre d’exécution soit visible :
1 2 3 4 |
Function WaitForEnd(strFileToExec) As Long Set wsh = CreateObject("WScript.Shell") WaitForEnd = wsh.Run(strFileToExec, 0, True) End Function |
Dans le code, appeler la fonction pour exécuter la commande :
1 |
codeRetour = WaitForEnd ("mon_script.cmd") |
La variable codeRetour (Long) contient « 0 » si l’exécution s’est déroulée correctement.