VBA, Check If Text File is Open
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.
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:
The line below returns the selected text file’s path:
If the file is being used the error handler below catches the error and tells the program to continue execution at the highlighted label:
The code will continue at this line if an error is thrown:
If the file is opened successfully the message box below is displayed:
The file and code related to this article can be downloaded here.