Start a document based on its filename

Starting any document file based on its file name only is very simple in Windows using the ShellExecute function. This tip shows how simple it is - you only really need one declare and one line of code!

Start a new project in VB. Add a Command button to the project's form, then add the following code:

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 

Private Sub Command1_Click() 
Dim lR As Long 
Dim sFile As String 
Dim iFile As Integer 

    ' Create a text file to test: 
    sFile = App.Path & "\SHELLTST.TXT" 
    On Error Resume Next 
    Kill sFile 
    On Error GoTo 0 
    iFile = FreeFile 
    Open sFile For Binary Access Write As #iFile 
    Put #iFile, , _
         "This is a text file used for testing the ShellExecute API function." 
    Close #iFile 

    ' Start the text file using its filename. Windows will 
    ' check what exe is associated with .TXT files (by default 
    ' this is Notepad) and start the application with the file 
    ' opened: 
    lR = ShellExecute(Me.hWnd, "Open", sFile, "", "", vbNormalFocus) 
    If (lR < 0) Or (lR > 32) Then 
        ' success 
        MsgBox "Failed to start '" & sFile & "'", vbInformation 
    End If 
End Sub 

When you click the command button, the app will create a small text file in the project's path, and then open it with the default application (normally Notepad).