VBA Shell

In VBA, there are a few different ways to use a Shell. One way is the Shell function which is built into VBA in the Interaction module. Shell objects can also be used from the Windows Script Host Object Model and the Microsoft Shell Controls and Automation library.

VBA.Interaction.Shell Function

The Shell function from the Interaction module can be used to run an executable program file located on the user's file system. The Shell function runs an executable program and returns the program's task ID if successful as a Double. The Shell function returns 0 if unsuccessful. The Shell function takes two arguments, PathName and WindowStyle. PathName is a Variant/String that represents the path to an executable. WindowStyle is a member of the VbAppWinStyle Enum and determines the window style of the program being run. The Shell function works asynchronously so the function will not wait for the program to execute and VBA will continue executing code immediately after calling Shell.

Note: The Shell function works asynchronously.

Syntax: Shell(PathName, [WindowStyle As VbAppWindowStyle = vbMinimizedFocus]) As Double

VbAppWinStyle Members

Constant Value Description
vbHide 0 Window is hidden and given focus. Not available on Mac.
vbNormalFocus 1 Window has its original size and position and is given focus.
vbMinimizedFocus 2 Window is minimized and given focus.
vbMaximizedFocus 3 Window is maximized and given focus.
vbNormalNoFocus 4 Window has its most recent size and position. Focus stays on the currently active window.
vbMinimizedNoFocus 6 Window is minimized. Focus stays on the currently active window.
Public Sub OpenNotepad()

    Dim TaskID As Double

    TaskID = VBA.Interaction.Shell("notepad.exe", vbMaximizedFocus)

    Debug.Print TaskID

End Sub

Windows Script Host Object Model

The Windows Script Host Library can be used to access the WshShell object.

Public Sub OpenNotepad()

    Dim wSh    As Object 'IWshRuntimeLibrary.WshShell
    Dim wExec  As Object 'IWshRuntimeLibrary.WshExec

    Set wSh = CreateObject("WScript.Shell") 'New IWshRuntimeLibrary.WshShell
    Set wExec = w.Exec("notepad.exe")

    Debug.Print wExec.ProcessID

End Sub

Microsoft Shell Controls and Automation

The Microsoft Shell Controls and Automation library can be used to access the Shell object.

Note: Late-bound objects do not initialize properly with this library so Early-binding should be used.

Public Sub OpenNotepad()

    'Requires reference to Microsoft Shell Controls And Automation library

    Dim ShellApp As Shell32.Shell
    Set ShellApp = CreateObject("Shell.Application")

    ShellApp.ShellExecute "notepad.exe"

End Sub