Launch a Program from a Macro in Excel

This article demonstrates how to launch a program from within an Excel macro using VBA code and is useful not only for launching WinWedge, but also launching any other applications you may need access to.

The VBA programming language in Excel provides a “Shell” function that you can use to launch other application programs however you need to know the exact file location of the program that you want to launch.

Suppose that you want to launch a program and force it to open a specific file? For example, suppose that you want to launch Microsoft Word from an Excel spreadsheet and have it automatically open a specific document file or suppose that you want to launch WinWedge from Excel and have WinWedge open a specific configuration file.

Most programs that work with documents (or configuration files) will accept the name of the document or configuration file on the command line used to launch the program and then automatically open the specified file as soon as the program loads into memory however there is a much easier way to accomplish the same thing using a special Windows API function called ShellExecute.

The ShellExecute command allows you to specify only the name of the file that you want to open and it will then automatically launch the correct application that is associated with the filename extension for the file and feed it the document (or configuration file) on the command line.

For example, the filename extension “.DOC” is normally associated with Microsoft Word therefore if you call the ShellExecute function and pass it the filename for a Word document that has the extension “.DOC”, the ShellExecute function will automatically launch Microsoft Word (no matter what folder it is installed in) and open the specified document. The same is true for WinWedge configuration files that have the .SW3 filename extension. In fact, you can even pass in a string containing a URL for a web page and the ShellExecute function will automatically open the default web browser and display the specified web page.

The following Excel VBA subroutine demonstrates the technique:

Declare Function ShellExecute Lib "shell32.dll" Alias "ShellExecuteA" _
(ByVal hwnd As Long, _
ByVal lpOperation As String, _
ByVal lpFile As String, _
ByVal lpParameters As String, _
ByVal lpDirectory As String, _
ByVal nShowCmd As Long) _
As Long

Sub LaunchDocument(FileToLaunch As String)
   x = ShellExecute(0, "open", FileToLaunch, vbNullString, vbNullString, 0)

   ' optional - if you want to give the program time to load and then switch
   ' the input focus back to Excel, you can use the following lines of code:

   ' Application.Wait Now + TimeValue("00:00:03") ' wait 3 seconds
   ' AppActivate Application.Caption ' switch focus back to Excel
End Sub

Contact Us