How to Open a File with its Default Application in VBA

In my Access applications, I often have a need to open an external file in its default application.

For example:

  • .pdf: Open with the default PDF viewer
  • .png: Open with the default image viewer
  • .docx: Open with Microsoft Word

For years, I've been using a very reliable function from Dev Ashish to take care of this task: fHandleFile.

fHandleFile()

Here's Dev's introduction to the code:

(Q)    How do I start the application which is registered to handle a file extension in Win Registry?

(A)    You'll have to use the ShellExecute API.  Pass the filename to fHandleFile function.  If the file extension is "known", or registered, it should automatically call the parent application.  If the extension is unknown, it should bring up the Windows standard "Open With" dialog box.

To respect Dev's wishes, I will not reproduce the code here, but you can find it on The Access Web at: API: Start an app with ShellExecute.

NOTE: If the link above ever dies, the original page as it existed on 2023-03-14 is accessible via the Internet Archive's Wayback Machine.

Updating the API Call for 64-bit Compatibility

I'm not sure exactly how old the fHandleFile() function is, but it predates the release of Access 2010 meaning that 64-bit VBA did not even exist at the time.

To run the code in both 32-bit and 64-bit VBA environments in Office 2010 and later, you will want to update the API declaration from Dev's code as follows:

Private Declare PtrSafe Function apiShellExecute Lib "shell32.dll" _
                                        Alias "ShellExecuteA" _
                                        (ByVal hWnd As LongPtr, _
                                        ByVal lpOperation As String, _
                                        ByVal lpFile As String, _
                                        ByVal lpParameters As String, _
                                        ByVal lpDirectory As String, _
                                        ByVal nShowCmd As Long) As LongPtr

Cover image created with Microsoft Designer