Advertisement
Guest User

vba_RunApplication

a guest
May 3rd, 2012
156
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. Option Explicit
  2.  
  3. Private Declare Function GetExitCodeProcess Lib "kernel32" (ByVal hProcess As Long, lpExitCode As Long) As Long
  4. Private Declare Function WaitForSingleObject Lib "kernel32" (ByVal hHandle As Long, ByVal dwMilliseconds As Long) As Long
  5. Private Declare Function OpenProcess Lib "kernel32" (ByVal dwDesiredAccess As Long, ByVal bInheritHandle As Long, ByVal dwProcessId As Long) As Long
  6. Private Declare Function CloseHandle Lib "kernel32" (ByVal hObject As Long) As Long
  7. Private Declare Function FormatMessage Lib "kernel32" Alias "FormatMessageA" (ByVal dwFlags As Long, lpSource As Any, ByVal dwMessageId As Long, ByVal dwLanguageId As Long, ByVal lpBuffer As String, ByVal nSize As Long, Arguments As Long) As Long
  8.  
  9. Public Const INFINITE = &HFFFF
  10. Public Const PROCESS_ALL_ACCESS = &H1F0FFF
  11.  
  12. Sub RunApplication(ByVal Cmd As String)
  13. Dim lTaskID As Double
  14. Dim lPID As Long
  15. Dim lExitCode As Long
  16.  
  17.     lTaskID = Shell(Cmd, vbNormalFocus)
  18.     'Get process handle
  19.    lPID = OpenProcess(PROCESS_ALL_ACCESS, True, lTaskID)
  20.     If lPID Then
  21.         'Wait for process to finish
  22.        Call WaitForSingleObject(lPID, INFINITE)
  23.         'Get Exit Process
  24.        If GetExitCodeProcess(lPID, lExitCode) Then
  25.             'Received value
  26.            MsgBox "Successfully returned " & lExitCode, vbInformation
  27.         Else
  28.             MsgBox "Failed: " & DLLErrorText(Err.LastDllError), vbCritical
  29.         End If
  30.     Else
  31.         MsgBox "Failed: " & DLLErrorText(Err.LastDllError), vbCritical
  32.     End If
  33.     lTaskID = CloseHandle(lPID)
  34. End Sub
  35.  
  36. Public Function DLLErrorText(ByVal lLastDLLError As Long) As String
  37.     Dim sBuff As String * 256
  38.     Dim lCount As Long
  39.     Const FORMAT_MESSAGE_ALLOCATE_BUFFER = &H100, FORMAT_MESSAGE_ARGUMENT_ARRAY = &H2000
  40.     Const FORMAT_MESSAGE_FROM_HMODULE = &H800, FORMAT_MESSAGE_FROM_STRING = &H400
  41.     Const FORMAT_MESSAGE_FROM_SYSTEM = &H1000, FORMAT_MESSAGE_IGNORE_INSERTS = &H200
  42.     Const FORMAT_MESSAGE_MAX_WIDTH_MASK = &HFF
  43.  
  44.     lCount = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM Or FORMAT_MESSAGE_IGNORE_INSERTS, 0, lLastDLLError, 0&, sBuff, Len(sBuff), ByVal 0)
  45.     If lCount Then
  46.         DLLErrorText = Left$(sBuff, lCount - 2) 'Remove line feeds
  47.    End If
  48.  
  49. End Function
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement