Open a web page, text file, pdf file, etc.

Published on February 5, 2010

In many VBA applications it is useful to direct the user to a support web page, pdf file, or to a text file your application creates. Use the OpenDefaultApp function below to open any file in its default application. The function mimics double clicking on the file icon in a My Computer window or on your desktop; to open a web page just pass it the web address. The ShellExecute function declaration is required, however you may skip the Enum definition and always use a WindowState of 1.

Public Enum AppWindowState
End Enum

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

Public Function OpenDefaultApp( _
strFileName As String, _
WindowState As AppWindowState) As Boolean
    Dim lHWnd As Long
    Dim lResult As Long

    lResult = ShellExecute( _
lHWnd, "open", strFileName, _
vbNullString, vbNullString, WindowState)

    OpenDefaultApp = (lResult > 32)
End Function

Sub OpenTest()
    ' Open a web page
    OpenDefaultApp _
"", _

    ' Open a text file
    OpenDefaultApp _
Environ$("USERPROFILE") & "\My Documents\test.txt", _

End Sub
Like this article? Share it!

Leave a Comment

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Privacy Policy