I have this code. It is supposed to check if a file exists and open it if it does. It does work if the file exists, and if it doesn't, however, whenever I leave the textbox blank and click the submit button, it fails. What I want, if the textbox is blank is to display the error message just like if the file didn't exist.
Runtime-error "1004"
Dim File As String File = TextBox1.Value Dim DirFile As String DirFile = "C:\Documents and Settings\Administrator\Desktop\" & File If Dir(DirFile) = "" Then MsgBox "File does not exist" Else Workbooks.Open Filename:=DirFile End If
Use the VBA Dir function to check if a file exists. The VBA Dir function returns the name of a valid file, so you can use it to test whether a file exists. When the VBA Dir function returns an empty string, it means the file does not exist.
You can run the macro by select Macro > Macros under the Tools menu. Then select the macro called CheckIfFileExists and click on the Run button. After you run the macro, the values in column B should indicate whether the files exist or not. You can press Alt + F11 to view the VBA code.
To check if a file exists, you pass the file path to the exists() function from the os. path standard library. If the file exists, the exists() function returns True . Otherwise, it returns False .
To check if a workbook exists in a specific folder, you can use the DIR function. DIR is a function that stands for the directory. You need to specify the path of the file along with the name and extension. If a file exists, it returns the file name, otherwise a blank value.
something like this
best to use a workbook variable to provide further control (if needed) of the opened workbook
updated to test that file name was an actual workbook - which also makes the initial check redundant, other than to message the user than the Textbox is blank
Dim strFile As String Dim WB As Workbook strFile = Trim(TextBox1.Value) Dim DirFile As String If Len(strFile) = 0 Then Exit Sub DirFile = "C:\Documents and Settings\Administrator\Desktop\" & strFile If Len(Dir(DirFile)) = 0 Then MsgBox "File does not exist" Else On Error Resume Next Set WB = Workbooks.Open(DirFile) On Error GoTo 0 If WB Is Nothing Then MsgBox DirFile & " is invalid", vbCritical End If
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With