Vba excel if not exist

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 SettingsAdministratorDesktop" & File
If Dir(DirFile) = "" Then
  MsgBox "File does not exist"
Else
    Workbooks.Open Filename:=DirFile
End If

ZygD's user avatar

ZygD

21k39 gold badges77 silver badges98 bronze badges

asked May 3, 2013 at 3:43

Josephine Bautista's user avatar

2

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 SettingsAdministratorDesktop" & 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

answered May 3, 2013 at 5:01

brettdj's user avatar

3

I use this function to check for file existence:

Function IsFile(ByVal fName As String) As Boolean
'Returns TRUE if the provided name points to an existing file.
'Returns FALSE if not existing, or if it's a folder
    On Error Resume Next
    IsFile = ((GetAttr(fName) And vbDirectory) <> vbDirectory)
End Function

answered Jan 30, 2015 at 14:19

iDevlop's user avatar

iDevlopiDevlop

24.6k11 gold badges89 silver badges147 bronze badges

13

For checking existence one can also use (works for both, files and folders):

Not Dir(DirFile, vbDirectory) = vbNullString

The result is True if a file or a directory exists.

Example:

If Not Dir("C:Temptest.xlsx", vbDirectory) = vbNullString Then
    MsgBox "exists"
Else
    MsgBox "does not exist"
End If

answered Nov 18, 2015 at 4:35

ZygD's user avatar

ZygDZygD

21k39 gold badges77 silver badges98 bronze badges

1

A way that is clean and short:

Public Function IsFile(s)
    IsFile = CreateObject("Scripting.FileSystemObject").FileExists(s)
End Function

answered Apr 3, 2020 at 4:37

Excel Hero's user avatar

Excel HeroExcel Hero

14.1k4 gold badges31 silver badges39 bronze badges

1

Function FileExists(ByRef strFileName As String) As Boolean
' TRUE if the argument is an existing file
' works with Unicode file names
    On Error Resume Next
    Dim objFSO As Object
    Set objFSO = CreateObject("Scripting.FileSystemObject")
    FileExists = objFSO.FileExists(strFileName)
    On Error GoTo 0
End Function

To make the function run faster, objFSO can be made a global variable and the code can be modified and saved in a module like this:

Option Explicit
Dim objFSO As Object
Function FileExists(ByRef strFileName As String) As Boolean
' TRUE if the argument is an existing file
' works with Unicode file names
    On Error Resume Next
    If objFSO Is Nothing Then Set objFSO = CreateObject("Scripting.FileSystemObject")
    FileExists = objFSO.FileExists(strFileName)
    On Error GoTo 0
End Function

For strFileName to be a unicode string, you can, for example, either get it from a cell value or define it in a special way, as Excel’s VBE doesn’t save string constants in Unicode. VBE does support Unicode strings already saved in string variables. You’re gonna have to look this up for further details.

Hope this helps somebody ^_^

answered Nov 19, 2021 at 0:46

Jalal's user avatar

JalalJalal

5466 silver badges12 bronze badges

Maybe it caused by Filename variable

File = TextBox1.Value

It should be

Filename = TextBox1.Value

answered May 3, 2013 at 3:52

matzone's user avatar

matzonematzone

5,6933 gold badges17 silver badges20 bronze badges

1

Speed of Various FileExists Methods

I needed to check file existence for many of my projects, so I wanted to determine the fastest option. I used the micro timer code (see Benchmarking VBA Code) to run the File Exist functions below the table against a local folder with 2865 files to see which was faster. Winner used GetAttr. Using FSO method for Test 2 was a bit faster with the object defined as a global than not, but not as fast as the GetAttr method.

------------------------------------------------------
% of Fastest                Seconds       Name
------------------------------------------------------
100.00000000000%             0.0237387    Test 1 - GetAttr
7628.42784145720%            1.8108896    Test 2 - FSO (Obj Global)
8360.93687615602%            2.0522254    Test 2 - FSO (Obj in Function)
911.27399562739%             0.2163246    Test 3 - Dir
969.96844814586%             0.2302579    Test 4 - Dir$
969.75108156723%             0.2302063    Test 5 - VBA.Dir
933.82240813524%             0.2216773    Test 6 - VBA.Dir$
7810.66612746275%            1.8541506    Test 7 - Script.FSO

Function FileExistsGA(ByVal FileSpec As String) As Boolean
  ' Karl Peterson MS VB MVP
  Dim Attr As Long
  ' Guard against bad FileSpec by ignoring errors
  ' retrieving its attributes.
  On Error Resume Next
  Attr = GetAttr(FileSpec)
  If Err.Number = 0 Then
    ' No error, so something was found.
    ' If Directory attribute set, then not a file.
    FileExistsGA = Not ((Attr And vbDirectory) = vbDirectory)
  End If
End Function

Function FSOFileExists(sFilePathNameExt As String) As Boolean
    Dim fso As Object
    Set fso = CreateObject("Scripting.FileSystemObject")
    FSOFileExists = fso.FileExists(sFilePathNameExt)
    Set fso = Nothing
End Function

Function FileExistsDir(sFilePathNameExt As String) As Boolean
    If Len(Dir(sFilePathNameExt)) > 0 Then FileExistsDir = True
End Function

Function FileExistsDirDollar(sFilePathNameExt As String) As Boolean
    If Len(Dir$(sFilePathNameExt)) > 0 Then FileExistsDirDollar = True
End Function

Function FileExistsVBADirDollar(sFilePathNameExt As String) As Boolean
    If Len(VBA.Dir$(sFilePathNameExt)) > 0 Then FileExistsVBADirDollar = True
End Function

Function FileExistsVBADir(sFilePathNameExt As String) As Boolean
    If Len(VBA.Dir(sFilePathNameExt)) > 0 Then FileExistsVBADir = True
End Function

Public Function IsFileSFSO(s)
    IsFileSFSO = CreateObject("Scripting.FileSystemObject").FileExists(s)
End Function

I realize that this does not fully answer the OP, but is provides information on which of the answers provided seems to be most efficient.

answered Nov 29, 2022 at 19:18

PhilB's user avatar

PhilBPhilB

764 bronze badges

I’ll throw this out there and then duck.
The usual reason to check if a file exists is to avoid an error when attempting to open it. How about using the error handler to deal with that:

Function openFileTest(filePathName As String, ByRef wkBook As Workbook, _
                      errorHandlingMethod As Long) As Boolean
'Returns True if filePathName is successfully opened,
'        False otherwise.
   Dim errorNum As Long

'***************************************************************************
'  Open the file or determine that it doesn't exist.
   On Error Resume Next:
   Set wkBook = Workbooks.Open(fileName:=filePathName)
   If Err.Number <> 0 Then
      errorNum = Err.Number
      'Error while attempting to open the file. Maybe it doesn't exist?
      If Err.Number = 1004 Then
'***************************************************************************
      'File doesn't exist.
         'Better clear the error and point to the error handler before moving on.
         Err.Clear
         On Error GoTo OPENFILETEST_FAIL:
         '[Clever code here to cope with non-existant file]
         '...
         'If the problem could not be resolved, invoke the error handler.
         Err.Raise errorNum
      Else
         'No idea what the error is, but it's not due to a non-existant file
         'Invoke the error handler.
         Err.Clear
         On Error GoTo OPENFILETEST_FAIL:
         Err.Raise errorNum
      End If
   End If

   'Either the file was successfully opened or the problem was resolved.
   openFileTest = True
   Exit Function

OPENFILETEST_FAIL:
   errorNum = Err.Number
   'Presumabley the problem is not a non-existant file, so it's
   'some other error. Not sure what this would be, so...
   If errorHandlingMethod < 2 Then
      'The easy out is to clear the error, reset to the default error handler,
      'and raise the error number again.
      'This will immediately cause the code to terminate with VBA's standard
      'run time error Message box:
      errorNum = Err.Number
      Err.Clear
      On Error GoTo 0
      Err.Raise errorNum
      Exit Function

   ElseIf errorHandlingMethod = 2 Then
      'Easier debugging, generate a more informative message box, then terminate:
      MsgBox "" _
           & "Error while opening workbook." _
           & "PathName: " & filePathName & vbCrLf _
           & "Error " & errorNum & ": " & Err.Description & vbCrLf _
           , vbExclamation _
           , "Failure in function OpenFile(), IO Module"
      End

   Else
      'The calling function is ok with a false result. That is the point
      'of returning a boolean, after all.
      openFileTest = False
      Exit Function
   End If

End Function 'openFileTest()

answered Dec 10, 2015 at 6:40

riderBill's user avatar

riderBillriderBill

7908 silver badges16 bronze badges

Here is my updated code. Checks to see if version exists before saving and saves as the next available version number.

Sub SaveNewVersion()
    Dim fileName As String, index As Long, ext As String
    arr = Split(ActiveWorkbook.Name, ".")
    ext = arr(UBound(arr))

    fileName = ActiveWorkbook.FullName

    If InStr(ActiveWorkbook.Name, "_v") = 0 Then
        fileName = ActiveWorkbook.Path & "" & Left(ActiveWorkbook.Name, InStr(ActiveWorkbook.Name, ".") - 1) & "_v1." & ext
    End If

   Do Until Len(Dir(fileName)) = 0

        index = CInt(Split(Right(fileName, Len(fileName) - InStr(fileName, "_v") - 1), ".")(0))
        index = index + 1
        fileName = Left(fileName, InStr(fileName, "_v") - 1) & "_v" & index & "." & ext

    'Debug.Print fileName
   Loop

    ActiveWorkbook.SaveAs (fileName)
End Sub

answered Mar 21, 2018 at 20:52

Andrew Prostko's user avatar

You should set a condition loop to check the TextBox1 value.

If TextBox1.value = "" then
   MsgBox "The file not exist" 
   Exit sub 'exit the macro
End If

Hope it help you.

answered May 3, 2013 at 4:05

Leng Keong's user avatar

Leng KeongLeng Keong

1431 silver badge3 bronze badges

The function that allows us to check if a file or folder exists is know as the DIR function.  The syntax for the DIR function is as follows:

DIR [( path [, attributes ])]

The PATH argument is basically an address which returns the name of your file or folder.  If the name is not found, DIR returns an empty string.

The ATTRIBUTES argument (which are optional) are listed in the below table.

ConstantVALUE Value Description
vbNormal 0 (Default) Files with no attributes
vbReadOnly 1 Read-only files
vbHidden 2 Hidden files
vbSystem 4 System files
vbDirectory 16 Directories or folders

The default is vbNormal, which are files with no specific attributes.  You can filter for files with a specific attribute by using the constants listed above.

An interesting thing you can use with the DIR function are wildcards.  Wildcards represent “any characters” and are useful when you want to capture multiple items in a search based on a pattern of characters.  There are two wildcard characters:

Asterisk (*) – This wildcard character will allow for any character(s) in any quantity.

Examples:  

Exc* (any text starting with “Exc”)

*el (any text ending with “el”)

Exc*el (any text starting with “Exc”, ending with “el”, and any character in between)

Question Mark (?) – This wildcards character will allow for any character in a single character position

Examples:   

??cel (The first and second characters can be anything, but the third through fifth characters must be “cel”)

Ex?el (The first and second characters must be “Ex”, the fourth and fifth characters must be “el”, but the third character can be anything)

Practical Examples

Task #1

We will use the DIR function to check if a file exists.  If the file doesn’t exist, we will display a “File does not exist” message to the user.  If the file exists, we will open the file.

Task #2

We will use the DIR function to check if a folder exists.  If the folder doesn’t exist, we will prompt the user to ask if they would like to create that folder.  If the responds with a “Yes”, we will create the folder for them.

Task #1 (Version 1) – Checking for the existence of a file

First, open the Visual Basic Editor (ALT-F11) and create an empty module (i.e. “LessonsFilesFolders”).

The DIR function returns a string, so we need to declare a variable named FileName to hold the returned value.

Dim FileName As String

The next step is to query a folder for a file and return the filename if it exists, or an empty string if the file does not exist.  We will store the response in the FileName variable we created in the previous step.

FileName = VBA.FileSystem.Dir(“your folder nameyour file name”)

In our example we will use the following code:

FileName = VBA.FileSystem.Dir(“C:UsersLGDesktopVBAS2_recordMacros_start.xlsx”)

If the file does not exist, the DIR function will return an empty string.  We will test for the empty string response with an IF statement.  If the file does not exist, we will display a message stating such.  If the file does exist, this first version will simply show the filename in a message box.

If FileName = VBA.Constants.vbNullString Then
    MsgBox "File does not exist."
Else
    MsgBox FileName
End If

The completed code should look like the following:

Sub FileExists()
Dim FileName As String
    FileName = VBA.FileSystem.Dir("C:UsersLGDesktopVBAS2_recordMacros_start.xlsx")
    If FileName = VBA.Constants.vbNullString Then
        MsgBox "File does not exist."
    Else
        MsgBox FileName
    End If
    
End Sub

Execute the code by pressing F5 and observe the response.

This confirms that the file exists in the defined folder.

Task #1 (Version 2) – Checking for the existence of a file using wildcards

Alter the code to use wildcards when searching for the filename.

FileName = VBA.FileSystem.Dir("C:UsersLGDesktopVBAS2_*start.xls?)

We will also alter the code; instead of displaying a message, we will open the requested file.

Workbooks.Open "C:UsersLGDesktopVBA" & FileName

The updated code should appear as follows:

Sub FileExists()
Dim FileName As String
    FileName = VBA.FileSystem.Dir("C:UsersLGDesktopVBAS2_*start.xls?")
    If FileName = VBA.Constants.vbNullString Then
        MsgBox "File does not exist."
    Else
        Workbooks.Open "C:UsersLGDesktopVBA" & FileName
    End If
    
End Sub

Execute the code by pressing F5 and observe that the file opens.

Task #2 – Check if a folder exists

In this task, we will check to see if a folder exists.  If the folder does not exist, we will prompt the user and ask if they would like to create the folder.

We will create two variables:

Path – Hold the full folderfilename information

Folder – Hold only the folder name

Dim Path as String
Dim Folder as String

We will set the Path variable to point to a folder that does not exist:

Path = “C:UsersLGDesktopVBAS12”

We will set the Folder variable to hold the folder location stored by the Path variable.  Because this is a folder, we will use the optional constant vbDirectory in the DIR function.

Folder = Dir(Path,vbDirectory)

As we did earlier, we will check to see if the response returns an empty string.  If the Folder variable contains an empty string, we will prompt the user to ask if they wish to create the folder.

We need to store the user’s response, so we will create a variable to hold the response.

Dim Answer as VbMsgBoxResult

If the folder does not exist, we will display a message and store the user’s response in the Answer variable.

Answer = MsgBox("Path does not exist. Would you like to create it?", vbYesNo, "Create Path?")

Now we will test the answer.  We will use a Case statement to test the response.

If the user responds with “Yes”, we will create the folder.  If the user responds with anything else, we will exit the subroutine.

Select Case Answer
    Case vbYes
        VBA.FileSystem.MkDir (Path)
    Case Else
        Exit Sub
End Select

If the folder does exist, we will inform the user of its existence with a message box response.

Else
    MsgBox "Folder exists."

The completed code should look like the following:

Sub Path_Exists()
Dim Path As String
Dim Folder As String
Dim Answer As VbMsgBoxResult
    Path = "C:UsersLGDesktopVBAS12"
    Folder = Dir(Path, vbDirectory)
 
    If Folder = vbNullString Then
        Answer = MsgBox("Path does not exist. Would you like to create it?", vbYesNo, "Create Path?")
        Select Case Answer
            Case vbYes
                VBA.FileSystem.MkDir (Path)
            Case Else
                Exit Sub
        End Select
    Else
        MsgBox "Folder exists."
    End If
End Sub

Execute the code by pressing F5.  Because the folder does not exist, we are presented with the following message prompt.

If we answer “Yes”, the folder is created.

If we execute the macro a second time, we see the following response.

This is because the folder was created in the previous test.

Conclusion

We have demonstrated how you can use the DIR function to test whether a file or folder exists and decide what actions you wish to perform depending on the outcome of the test.

Practice Workbook

Feel free to Download the Workbook HERE.

Excel Download Practice file

Published on: November 22, 2018

Last modified: February 20, 2023

Microsoft Most Valuable Professional

Leila Gharani

I’m a 5x Microsoft MVP with over 15 years of experience implementing and professionals on Management Information Systems of different sizes and nature.

My background is Masters in Economics, Economist, Consultant, Oracle HFM Accounting Systems Expert, SAP BW Project Manager. My passion is teaching, experimenting and sharing. I am also addicted to learning and enjoy taking online courses on a variety of topics.

Return to VBA Code Examples

VBA allows you to check if a file or folder exists by using the Dir function.

Using the Dir Command to Check If a File Exists

As we mentioned in the introduction, the Dir function allows us to check if a selected file exists on the computer. Here is the code:

Sub CheckFileExists ()

Dim strFileName As String
Dim strFileExists As String

    strFileName = "C:UsersNikolaDesktopVBA articlesTest File Exists.xlsx"
    strFileExists = Dir(strFileName)

   If strFileExists = "" Then
        MsgBox "The selected file doesn't exist"
    Else
        MsgBox "The selected file exists"
    End If

End Sub

We first assigned the file path to the variable strFileName. Then we use the Dir function to get the file name into the variable strFileExists. If the file exists in the directory, its name will be assigned to the string variable strFileExists.  If it does not exist then strFileExists will remain blank.  Finally, the message box appears informing us if the file exists or not.

Using the Dir Command to Check If a Folder Exists

Similarly to checking if a file exists, you can check if a folder exists. You just need to add one argument to the Dir command. Let’s look at the code:

Sub CheckFolderExists ()

Dim strFolderName As String
Dim strFolderExists As String

    strFolderName = "C:UsersNikolaDesktopVBA articlesTest Folder"
    strFolderExists = Dir(strFolderName, vbDirectory)

    If strFolderExists = "" Then
        MsgBox "The selected folder doesn't exist"
    Else
        MsgBox "The selected folder exists"
    End If

End Sub

We first assigned the folder path to the variable strFolderName. Then we use the Dir function to get the file name into the variable strFileExists. In order to check a folder, we need to add the second argument to the function – vbDirecotry. If the folder exists in the directory, its name will be assigned to the variable strFolderExists. If not strFolderExists will remain blank.

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
vba save as

Learn More!

VBA Check If Folder Exists If Not Create It in specified name using VBA in Excel. We are using 2 methods to check folder exists or not. Those are Dir VBA function and FileSystemObject object. In the following tutorial let us see an example macro code. And also see the step by step instructions to run vba code in the visual basic editor(VBE) window.

Table of Contents:

  • Objective
  • Example to Check If Folder Exists If Not Create It using VBA Dir Function
  • VBA Checking If Folder Exists If Not Create It using FileSystemObject(FSO) Object
  • Instructions to Run VBA Macro Code
  • Other Useful Resources

Example to Check If Folder Exists If Not Create It using VBA Dir Function

Let us see an example macro to check specified folder exists or not. If it is not available create a new folder using VBA Dir function to check folder exists or not. First we are checking specified folder is available or not. If it exists, then displays message on the screen. If doesn’t exists, creating new folder using VBA MkDir function. After successfully creating folder displaying message on the screen for user notification.

'VBA Checking If Folder Exists If Not Create It using Dir Function
Sub VBAF1_Checking_If_Folder_Exists_If_Not_Create_It_Using_Dir_Function()
    
     'Variable declaration
    Dim sFolderPath As String
    Dim oFSO As Object
    
    'Define Folder Path
    sFolderPath = "C:VBAF1Files and Folders"
        
    'Check Specified Folder exists or not
    If Dir(sFolderPath) <> "" Then
        'If file is available
        MsgBox "Folder already exists!", vbInformation, "VBAF1"
        Exit Sub
    End If
         
    'If folder is not available
    MkDir sFolderPath
    
    'Display Message
    MsgBox "New folder has created successfully!", vbInformation, "VBAF1"
    
End Sub

Output: You can find following output screenshot for your reference. You can see different outputs in the screen shot. If folder available it displays first message. 2nd message displays when folder is created newly.
VBA Check If Folder Exists If Not Create It

VBA Checking If Folder Exists If Not Create It using FileSystemObject(FSO) Object

Let us another example macro to check specified Folder exists or not. If it is not available create a new Folder using VBA FileSystemObject(FSO) object to check Folder exists or not. In the below example VBA MkDir function helping us to create new folder.

'VBA Checking If Folder Exists If Not Create It using FSO Object
Sub VBAF1_Check_If_Folder_Exists_If_Not_Create_It_Using_FSO_Object()
    
    'Variable declaration
    Dim sFolderPath As String
    Dim oFSO As Object
    
    'Define Folder Path
    sFolderPath = "C:VBAF1Files and Folders2"
    
    'Create FSO Object
    Set oFSO = CreateObject("Scripting.FileSystemObject")
    
    'Check Specified Folder exists or not
    If oFSO.FolderExists(sFolderPath) Then
        'If Folder is available
        MsgBox "Folder already exists!", vbInformation, "VBAF1"
        Exit Sub
    End If
    
    'If folder is not available
    MkDir sFolderPath
    
    'Display Message
    MsgBox "New folder has created successfully!", vbInformation, "VBAF1"
    
End Sub

Instructions to Run VBA Macro Code or Procedure:

You can refer the following link for the step by step instructions.

Instructions to run VBA Macro Code

Other Useful Resources:

Click on the following links of the useful resources. These helps to learn and gain more knowledge.

VBA Tutorial VBA Functions List VBA Arrays VBA Text Files VBA Tables

VBA Editor Keyboard Shortcut Keys List VBA Interview Questions & Answers Blog

  • #6

Hi,

On this I do have similar set of query..

I do have «Timesheet Tracker» workbook, which have user form and some fields to capture the daily activity data.

In current scenario, I do have 7 user who will access «Timesheet Tracker» workbook.

This «Timesheet Tracker» workbook I will kept in one path.
What I want to do is,
When user will open this «Timesheet Tracker» workbook, on specific path code will check, whether on that path application.user workbook is exist or not. If not, then create new workbook and named that workbook as application.user name

and save the respective data.

Can you please provide me the code for this…

  • #7

hi please respond on this…:rolleyes:

  • #8

Instead of resurrecting ancient threads, start your own — and refrain from unnecessary ‘bumping’. Closed.

Понравилась статья? Поделить с друзьями:
  • Vba excel if isna
  • Vba excel if is not null
  • Vba excel if is not error
  • Vba excel if in one line
  • Vba excel if formula in cell