When you are working with text files, it is a good idea to check for errors when opening the file. Without the proper error handling the program might terminate unexpectedly. The file and code related to this article can be downloaded here.
Below are a two reasons why the program might terminate execution upon opening a file:
The file is already in use by another program.
The Index number used to open the file is currently in use. For more information about the Index number used in opening text files please see Excel VBA Reading Text Files.
The code below asks the user to select a text file to open. If the file is already open by another program a message box is displayed.
Sub Example5() Dim intResult As Integer Dim strPath As String Application.FileDialog(msoFileDialogOpen).AllowMultiSelect = False intResult = Application.FileDialog(msoFileDialogOpen).Show If intResult <> 0 Then strPath = Application.FileDialog(msoFileDialogOpen).SelectedItems(1) On Error GoTo lblError: Open strPath For Input As #1 MsgBox ("Opening the file was successful") End If Close #1 Exit Sub lblError: MsgBox ("There was an error opening the file. Implement the necessary actions") Err.Clear Close #1 End Sub
The lines below creates an open file dialog and asks the user to select a text file. For more information about open file dialogs please see Excel VBA, Open File Dialog: