ShellExecute VBA Example (For All FileTypes)

This post is in response to an email question I received.

Basically the person wanted to open an Excel file on their network using a command button in their application.

From a button or a shape on your worksheet:

…assign the following macro (VBA) code:

This code opens any type of file with the program specified to open the type of file:

'this "ShellExecute" API Call needs to be in a module!

Public 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


'this is the regular procedure - you'll attach the "OpenFile" macro to your worksheet object, button, or shape
Sub OpenFile()
    Dim RetVal As Long
    
    Dim strFileName As String
    Dim strFolderPath As String
    
    strFolderPath = ThisWorkbook.Path & "\"
    
    strFileName = "filetoopen.txt"
    
    Call ShellExecute(0, "Open", strFolderPath & strFileName & vbNullString, vbNullString, vbNullString, 1)

    
End Sub

This opens txt, pdf, docx, xlsx, etc files.

Let me know if you have any questions.


Posted

in

by

Tags: