How can I execute a shell command using VBA?

2019-01-12 03:37发布

问题:

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?

回答1:

Example:

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

Link: Shell Invoked from VBA



回答2:

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