Sub test()
thesentence = InputBox("Type the filename with full extension", "Raw Data File")
Range("A1").Value = thesentence
If Dir("thesentence") <> "" Then
MsgBox "File exists."
Else
MsgBox "File doesn't exist."
End If
End Sub
In this when i pickup the text value from the input box, it doesn’t work. If however, if remove "the sentence"
from If Dir()
and replace it with an actual name in the code, it works. Can somebody help?
asked Jul 20, 2012 at 6:25
Note your code contains Dir("thesentence")
which should be Dir(thesentence)
.
Change your code to this
Sub test()
thesentence = InputBox("Type the filename with full extension", "Raw Data File")
Range("A1").Value = thesentence
If Dir(thesentence) <> "" Then
MsgBox "File exists."
Else
MsgBox "File doesn't exist."
End If
End Sub
answered Jul 20, 2012 at 6:31
CylianCylian
10.8k4 gold badges43 silver badges55 bronze badges
4
Use the Office FileDialog
object to have the user pick a file from the filesystem. Add a reference in your VB project or in the VBA editor to Microsoft Office Library
and look in the help. This is much better than having people enter full paths.
Here is an example using msoFileDialogFilePicker
to allow the user to choose multiple files. You could also use msoFileDialogOpen
.
'Note: this is Excel VBA code
Public Sub LogReader()
Dim Pos As Long
Dim Dialog As Office.FileDialog
Set Dialog = Application.FileDialog(msoFileDialogFilePicker)
With Dialog
.AllowMultiSelect = True
.ButtonName = "C&onvert"
.Filters.Clear
.Filters.Add "Log Files", "*.log", 1
.Title = "Convert Logs to Excel Files"
.InitialFileName = "C:InitialPath"
.InitialView = msoFileDialogViewList
If .Show Then
For Pos = 1 To .SelectedItems.Count
LogRead .SelectedItems.Item(Pos) ' process each file
Next
End If
End With
End Sub
There are lots of options, so you’ll need to see the full help files to understand all that is possible. You could start with Office 2007 FileDialog object (of course, you’ll need to find the correct help for the version you’re using).
answered Jul 20, 2012 at 7:19
ErikEErikE
48.4k23 gold badges150 silver badges194 bronze badges
1
Correction to fileExists from @UberNubIsTrue :
Function fileExists(s_directory As String, s_fileName As String) As Boolean
Dim obj_fso As Object, obj_dir As Object, obj_file As Object
Dim ret As Boolean
Set obj_fso = CreateObject("Scripting.FileSystemObject")
Set obj_dir = obj_fso.GetFolder(s_directory)
ret = False
For Each obj_file In obj_dir.Files
If obj_fso.fileExists(s_directory & "" & s_fileName) = True Then
ret = True
Exit For
End If
Next
Set obj_fso = Nothing
Set obj_dir = Nothing
fileExists = ret
End Function
EDIT: shortened version
' Check if a file exists
Function fileExists(s_directory As String, s_fileName As String) As Boolean
Dim obj_fso As Object
Set obj_fso = CreateObject("Scripting.FileSystemObject")
fileExists = obj_fso.fileExists(s_directory & "" & s_fileName)
End Function
answered May 29, 2013 at 19:14
amackay11amackay11
7191 gold badge10 silver badges17 bronze badges
3
just get rid of those speech marks
Sub test()
Dim thesentence As String
thesentence = InputBox("Type the filename with full extension", "Raw Data File")
Range("A1").Value = thesentence
If Dir(thesentence) <> "" Then
MsgBox "File exists."
Else
MsgBox "File doesn't exist."
End If
End Sub
This is the one I like:
Option Explicit
Enum IsFileOpenStatus
ExistsAndClosedOrReadOnly = 0
ExistsAndOpenSoBlocked = 1
NotExists = 2
End Enum
Function IsFileReadOnlyOpen(FileName As String) As IsFileOpenStatus
With New FileSystemObject
If Not .FileExists(FileName) Then
IsFileReadOnlyOpen = 2 ' NotExists = 2
Exit Function 'Or not - I don't know if you want to create the file or exit in that case.
End If
End With
Dim iFilenum As Long
Dim iErr As Long
On Error Resume Next
iFilenum = FreeFile()
Open FileName For Input Lock Read As #iFilenum
Close iFilenum
iErr = Err
On Error GoTo 0
Select Case iErr
Case 0: IsFileReadOnlyOpen = 0 'ExistsAndClosedOrReadOnly = 0
Case 70: IsFileReadOnlyOpen = 1 'ExistsAndOpenSoBlocked = 1
Case Else: IsFileReadOnlyOpen = 1 'Error iErr
End Select
End Function 'IsFileReadOnlyOpen
answered Jul 21, 2012 at 13:52
whytheqwhytheq
34k64 gold badges170 silver badges265 bronze badges
4
Function FileExists(fullFileName As String) As Boolean
FileExists = VBA.Len(VBA.Dir(fullFileName)) > 0
End Function
Works very well, almost, at my site. If I call it with «» the empty string, Dir returns «connection.odc«!! Would be great if you guys could share your result.
Anyway, I do like this:
Function FileExists(fullFileName As String) As Boolean
If fullFileName = "" Then
FileExists = False
Else
FileExists = VBA.Len(VBA.Dir(fullFileName)) > 0
End If
End Function
answered Oct 22, 2015 at 11:12
1
Function FileExists(fullFileName As String) As Boolean
FileExists = VBA.Len(VBA.Dir(fullFileName)) > 0
End Function
answered Jun 14, 2015 at 2:09
Ronnie RoystonRonnie Royston
16k6 gold badges73 silver badges88 bronze badges
0
I’m not certain what’s wrong with your code specifically, but I use this function I found online (URL in the comments) for checking if a file exists:
Private Function File_Exists(ByVal sPathName As String, Optional Directory As Boolean) As Boolean
'Code from internet: http://vbadud.blogspot.com/2007/04/vba-function-to-check-file-existence.html
'Returns True if the passed sPathName exist
'Otherwise returns False
On Error Resume Next
If sPathName <> "" Then
If IsMissing(Directory) Or Directory = False Then
File_Exists = (Dir$(sPathName) <> "")
Else
File_Exists = (Dir$(sPathName, vbDirectory) <> "")
End If
End If
End Function
answered Jul 20, 2012 at 6:31
DanDan
44.9k17 gold badges88 silver badges157 bronze badges
2
Very old post, but since it helped me after I made some modifications, I thought I’d share. If you’re checking to see if a directory exists, you’ll want to add the vbDirectory argument to the Dir function, otherwise you’ll return 0
each time. (Edit: this was in response to Roy’s answer, but I accidentally made it a regular answer.)
Private Function FileExists(fullFileName As String) As Boolean
FileExists = Len(Dir(fullFileName, vbDirectory)) > 0
End Function
answered Dec 19, 2018 at 3:55
based on other answers here I’d like to share my one-liners that should work for dirs and files:
-
Len(Dir(path)) > 0 or Or Len(Dir(path, vbDirectory)) > 0 'version 1 - ... <> "" should be more inefficient generally
- (just
Len(Dir(path))
did not work for directories (Excel 2010 / Win7))
- (just
-
CreateObject("Scripting.FileSystemObject").FileExists(path) 'version 2 - could be faster sometimes, but only works for files (tested on Excel 2010/Win7)
as PathExists(path)
function:
Public Function PathExists(path As String) As Boolean
PathExists = Len(Dir(path)) > 0 Or Len(Dir(path, vbDirectory)) > 0
End Function
answered Aug 12, 2019 at 9:21
Andreas CovidiotAndreas Covidiot
4,1785 gold badges50 silver badges95 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.
Published on: November 22, 2018
Last modified: February 20, 2023
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.
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 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
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!
Learn More!
-
#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…
-
#8
Instead of resurrecting ancient threads, start your own — and refrain from unnecessary ‘bumping’. Closed.