Astra

Excel VBA Open File with Default Program

Estimated reading: 2 minutes

The following Excel VBA code will open the file with the default program if the file path is provided. 

Sub Open_File()
    Dim file_Path As String
    'change to the file path you want to open
    file_Path = "C:\Users\USER\Desktop\Solved Excel.JPG"
    
    'Open the file with its default program
    Shell "explorer.exe """ & file_Path & """", vbNormalFocus
End Sub

Result: Run the code by pressing F5, and the file Solved Excel.jpg will be opened in the Photos app.

Excel VBA Open File with Default Program

What if the file path given is invalid or the default program wasn’t installed on the computer?

Modify the code as given below to check if the file path given in the code really exists 

Sub Open_File_With_Default_Program()
    Dim file_Path As String
    'change to the file path you want to open
    file_Path = "C:\Users\USER\Desktop\Solved Excel.JPG"
    
   ' Check if the file exists
    If Dir(file_Path) = "" Then
        MsgBox "File not found: " & file_Path, vbExclamation, "Error"
        Exit Sub
    End If
    
    'Open the file with its default program
    Shell "explorer.exe """ & file_Path & """", vbNormalFocus
    
End Sub

Note: Please check the reference before running the code

Excel VBA Open File with Default Program

Leave a Reply

Your email address will not be published. Required fields are marked *

Share this Doc
Jump to Topics
SOLVED EXCEL
Scroll to Top