Go Premium for a chance to win a PS4. Enter to Win


Passing Arguements to an VB.exe

Posted on 2002-04-01
Medium Priority
Last Modified: 2008-03-10
When I am calling an exe from my code, how do i pass arguements into an exe by using Shell(), if the exe is expecting arguements?  Is there some other way?

Question by:hxia

Accepted Solution

Joe_Griffith earned 200 total points
ID: 6910902
l = Shell("program.exe arg1 arg2", vbNormalFocus)

Expert Comment

by:Steve Sirica
ID: 6910915
Shell() is ok but I found something even better.  Give this a whirl:

    Private Type STARTUPINFO
       cb               As Long
       lpReserved       As String
       lpDesktop        As String
       lpTitle          As String
       dwX              As Long
       dwY              As Long
       dwXSize          As Long
       dwYSize          As Long
       dwXCountChars    As Long
       dwYCountChars    As Long
       dwFillAttribute  As Long
       dwflags          As Long
       wShowWindow      As Integer
       cbReserved2      As Integer
       lpReserved2      As Long
       hStdInput        As Long
       hStdOutput       As Long
       hStdError        As Long
    End Type
       hProcess         As Long
       hThread          As Long
       dwProcessId      As Long
       dwThreadID       As Long
    End Type
    Private Declare Function WaitForSingleObject Lib "kernel32" (ByVal _
       hHandle As Long, ByVal dwMilliseconds As Long) As Long
    Private Declare Function CreateProcessA Lib "kernel32" (ByVal _
       lpApplicationName As String, ByVal lpCommandLine As String, ByVal _
       lpProcessAttributes As Long, ByVal lpThreadAttributes As Long, _
       ByVal bInheritHandles As Long, ByVal dwCreationFlags As Long, _
       ByVal lpEnvironment As Long, ByVal lpCurrentDirectory As String, _
       lpStartupInfo As STARTUPINFO, lpProcessInformation As _
    Private Declare Function CloseHandle Lib "kernel32" _
       (ByVal hObject As Long) As Long
    Private Declare Function GetExitCodeProcess Lib "kernel32" _
       (ByVal hProcess As Long, lpExitCode As Long) As Long
    Private Const NORMAL_PRIORITY_CLASS = &H20&
    Private Const INFINITE = -1&

Public Function ExecCmd(cmdline As String) As Long
    Dim start    As STARTUPINFO
    Dim ret      As Long
    On Error GoTo Syntax_Error
    '* Initialize the STARTUPINFO structure:
    start.cb = Len(start)
    '* Start the shelled application:
    ret = CreateProcessA(vbNullString, cmdline, 0&, 0&, 1&, NORMAL_PRIORITY_CLASS, 0&, vbNullString, start, proc)

    '* Wait for the shelled application to finish:
    ret = WaitForSingleObject(proc.hProcess, INFINITE)
    Call GetExitCodeProcess(proc.hProcess, ret)
    Call CloseHandle(proc.hThread)
    Call CloseHandle(proc.hProcess)
    ExecCmd = ret

    Exit Function
    Call gsGenError
    Resume Exit_Sub
End Function

then just make the call kinda like this:
  dim lnReturn as long
  dim lsProg   as string
  lsProg = "abc.exe Parm2Pass"
  lnReturn = ExecCmd(lsProg)

What's nice about this is it will wait till execution of the called program completes to continue.  OF course you can get around that by tweaking the function.

Hope this is helpfull

LVL 44

Expert Comment

ID: 6910993
to pass 'command line' arguments to a VB application, in the Application, use the Command$ function to retrieve the passes parameters, as a String, which you then parese as necessary.

Private Sub Form_Load()

dim strArgs as String

strArgs = Command$

' now parse strArgs to get the command-line parameters you passed in

End Sub

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!


Expert Comment

ID: 6911518
u may use the command function.

The following example uses the Command function to get the command line arguments in a function that returns them in a Variant containing an array.

Function GetCommandLine(Optional MaxArgs)
   'Declare variables.
   Dim C, CmdLine, CmdLnLen, InArg, I, NumArgs
   'See if MaxArgs was provided.
   If IsMissing(MaxArgs) Then MaxArgs = 10
   'Make array of the correct size.
   ReDim ArgArray(MaxArgs)
   NumArgs = 0: InArg = False
   'Get command line arguments.
   CmdLine = Command()
   CmdLnLen = Len(CmdLine)
   'Go thru command line one character
   'at a time.
   For I = 1 To CmdLnLen
      C = Mid(CmdLine, I, 1)
      'Test for space or tab.
      If (C <> " " And C <> vbTab) Then
         'Neither space nor tab.
         'Test if already in argument.
         If Not InArg Then
         'New argument begins.
         'Test for too many arguments.
            If NumArgs = MaxArgs Then Exit For
            NumArgs = NumArgs + 1
            InArg = True
         End If
         'Concatenate character to current argument.
         ArgArray(NumArgs) = ArgArray(NumArgs) & C
         'Found a space or tab.
         'Set InArg flag to False.
         InArg = False
      End If
   Next I
   'Resize array just enough to hold arguments.
   ReDim Preserve ArgArray(NumArgs)
   'Return Array in Function name.
   GetCommandLine = ArgArray()
End Function

LVL 17

Expert Comment

ID: 6912228
kcm76, the problem with you function is that it won't handle long file names example:

YourEXE.EXE "File name may have spaces.txt" ThisOneGotNone.txt

This one handles combined parameters, some with quotes and some without.  The is an example of usage at the start of the Function.

Public Function GetQuotedParameters(CmdLine As String) As Variant

' Returns parameters from a command line in the form of a variant string array

' example:

'Dim Params
'params = GetQuotedParameters(Command$)
'If params(0) = "$$ERROR$$" Then
'    MsgBox "Command Line Format Error Use /? to display command line options+vbcrlf+parsms(1)"
'    End
'ElseIf params(0) = "/?" Then
'    MsgBox "Command Line Options: /E for edit; /P for Print /PT for print to"
'    End
'End If

' This function handles parameters with/without quotes like:
' if not quoted assumes that space, tab or comma terminating

' returns element (0) = "$$ERROR$$" if an error see elsement (1) for message

Const QUOTE = """"
Const ONESPACE = " "

On Error GoTo BadNews

Dim w$ ' working copy of the command line provided

Dim nextchar As String
Dim ra As Variant ' Returned Array
Dim pc  As Long ' param count

Dim spos As Long ' position of first quote
Dim epos As Long ' position of last quote or next space
Dim paramlength  As Long
Dim complete As Boolean
Dim currentchar As String
Dim Param$

w$ = Trim$(CmdLine)                     ' make sure no leading spaces
w$ = Replace(w$, Chr$(9), Space$(1))    ' Remove Tabs
w$ = Replace(w$, ",", Space$(1))        ' Remove commas

pc = -1 ' param counter

' Handle no parameters
If Len(w$) = 0 Then
    GetQuotedParameters = Array(0)
    GetQuotedParameters(0) = ""
    Exit Function
End If

' Handle case where quotes aren't used
If InStr(w$, QUOTE) = 0 Then
    GetQuotedParameters = Split(w, ONESPACE)
    Exit Function
End If

' Find first/next characters
spos = 1
        If spos > Len(w$) Then
            complete = True
            Exit Do
        End If
        currentchar = Mid(w$, spos, 1)
        If currentchar = ONESPACE Then
            spos = spos + 1 ' ignore spaces
            Exit Do
        ElseIf currentchar = QUOTE Then
            nextchar = QUOTE
            spos = spos + 1
        Else ' not quote or space must the the start of a parameter
            nextchar = ONESPACE
        End If
        If spos > Len(w$) Then
            complete = True
            Exit Do
        End If

        epos = InStr(spos, w$, nextchar)
        If epos = 0 Then
            epos = Len(w$) + 1
        End If
        paramlength = epos - spos
        If paramlength = 0 Then
            ' "" has been found
            Param$ = "": GoSub AddParam
            Param = Mid(w$, spos, paramlength)
            GoSub AddParam
        End If
        spos = epos + 1
        Exit Do
    If complete Then Exit Do

If pc < 0 Then
    ReDim ra(0)
    ra(0) = ""
    For pc = 0 To UBound(ra)
        ra(pc) = Trim$(ra(pc))
    Next pc
End If

GetQuotedParameters = ra

Exit Function

AddParam: ' store the parameter
    pc = pc + 1
    If pc = 0 Then
        ReDim ra(0)
        ReDim Preserve ra(pc)
    End If
    ra(pc) = Param


pc = Err.Number
Param = Err.Description

On Error Resume Next ' reset error trap to stop potential loop

ReDim ra(1)
ra(0) = "$$ERROR$$"
ra(1) = "Error: " + CStr(pc) + " ~ " + Param

End Function


Author Comment

ID: 6913040
Thanks All!


Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

When designing a form there are several BorderStyles to choose from, all of which can be classified as either 'Fixed' or 'Sizable' and I'd guess that 'Fixed Single' or one of the other fixed types is the most popular choice. I assume it's the most p…
This article describes how to use a set of graphical playing cards to create a Draw Poker game in Excel or VB6.
Show developers how to use a criteria form to limit the data that appears on an Access report. It is a common requirement that users can specify the criteria for a report at runtime. The easiest way to accomplish this is using a criteria form that a…
This lesson covers basic error handling code in Microsoft Excel using VBA. This is the first lesson in a 3-part series that uses code to loop through an Excel spreadsheet in VBA and then fix errors, taking advantage of error handling code. This l…
Suggested Courses

876 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question