Passing Arguements to an VB.exe

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?

Who is Participating?
l = Shell("program.exe arg1 arg2", vbNormalFocus)
Steve SiricaSenior Web Application EngineerCommented:
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

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

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Chandramouli kArchitectCommented:
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

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

hxiaAuthor Commented:
Thanks All!

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.