Execute any type of file from excel vba

lukeshuttlewood

Board Regular
Joined
Jul 27, 2004
Messages
90
Is it possible to execute files from Excel VBA?

I know this can be done using hyperlinks via the worksheet object but the code is pretty messy.

Does anyone know a simple way of executing for example, a PDF, Bmp, Doc - any file type as if it were opened from the desktop by a user.


CHeers
Luke
 

Excel Facts

Last used cell?
Press Ctrl+End to move to what Excel thinks is the last used cell.

rjp

Board Regular
Joined
Jan 5, 2006
Messages
148
Put this into a module, I found it on the web but have lost the original source.

Code:
'ShellExecute() works like Shell() but uses the Windows API so that
'the correct helper application is launched when running data files.
'eg. ShellExecute *.doc will open MS Word & the document
Private 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 LaunchFile(fPath As String, fName As String)

    If LCase(Right(fName, 4)) = ".xls" Then
        Workbooks.Open fPath & fName
    Else
        retVal = ShellExecute(1, "Open", fName, vbNullString, fPath, 3)
        If retVal = 31 Then
            'File Type not recognised - warn user
            MsgBox "Couldn't launch " & fName & " as Windows does not know how to open this type of file.", vbInformation + vbOKOnly, "Launch Failed"
        End If
    End If

End Sub

Just call LaunchFile with the path to the file (fPath) including a trailing "\" and the filename (fName). Notice that .xls files are handled differently, can't remember if that's because I run this from a modal userform or not!

Kudos to the original author (and subsequent leechers!)
 

Forum statistics

Threads
1,136,370
Messages
5,675,367
Members
419,566
Latest member
moni2277

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Top