Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VBA check if file exists

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 
like image 318
Josephine Bautista Avatar asked May 03 '13 03:05

Josephine Bautista


People also ask

How do you check if file exists in VBA Excel?

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.

How do you check if a file exists in Excel?

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.

How do I check to see if a file exists?

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 .

Does workbook exist VBA?

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.


1 Answers

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 
like image 98
brettdj Avatar answered Sep 21 '22 17:09

brettdj