aF.
aF.

Reputation: 66757

How can I execute a shell command using VBA?

I want to execute a shell command like the following using Visual Basic for Applications.

C:\Temp\gc.exe 1

How can I do it?

Upvotes: 12

Views: 68090

Answers (2)

rchacko
rchacko

Reputation: 2139

This shows the scenarios where you want to call an exe file and pass an argument to it using shell command. The following code checks the folder where chrome.exe residing and calling www.google.com, from there (assuming you installed chrome) by passing url as argument:

Public Sub Display_Google()
  Dim chromePath As String
  chromePath = "C:\Program Files\Google\Chrome\Application\chrome.exe"

  If FileExists(chromePath) Then
  Shell (chromePath & " -url" & " " & "www.google.com"), vbMaximizedFocus
  Else

  chromePath = "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"
  Shell (chromePath & " -url" & " " & "www.google.com"), vbMaximizedFocus
  End If
End Sub

Public Function FileExists(ByVal FileName As String) As Boolean
    On Error Resume Next
    FileExists = Not CBool(GetAttr(FileName) And (vbDirectory Or vbVolume))
    On Error GoTo 0
End Function

Upvotes: 1

Jim Counts
Jim Counts

Reputation: 12805

Example:

 retVal = Shell("C:\Temp\gc.exe 1", vbNormalFocus)

Link: Shell Invoked from VBA

Upvotes: 12

Related Questions