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
Today, I thought I’d demonstrate 2 distinct methods that can be used to validate whether a file exists or not.
- The VBA Dir Function
- The File System Object’s FileExist Method
Using The VBA Dir Function
'--------------------------------------------------------------------------------------- ' Procedure : File_Exist ' Author : Daniel Pineault, CARDA Consultants Inc. ' Website : http://www.cardaconsultants.com ' Purpose : Test for the existence of a file; Returns True/False ' True => File exists ' False => File does not exist ' Copyright : The following is release as Attribution-ShareAlike 4.0 International ' (CC BY-SA 4.0) - https://creativecommons.org/licenses/by-sa/4.0/ ' Req'd Refs: None required ' ' Input Variables: ' ~~~~~~~~~~~~~~~~ ' sFile : Fully qualified path and filename to check for ' ' Usage: ' ~~~~~~ ' ? File_Exist("C:TempFlow-Undo-Dont.jpg") ' Returns -> True ' ' Revision History: ' Rev Date(yyyy-mm-dd) Description ' ************************************************************************************** ' 1 2007-03-06 Initial Release ' 2 2022-11-24 Update Function header ' Update Error Handler '--------------------------------------------------------------------------------------- Function File_Exist(ByVal sFile As String) As Boolean On Error GoTo Error_Handler File_Exist = (Len(Dir(sFile)) > 0) Error_Handler_Exit: On Error Resume Next Exit Function Error_Handler: MsgBox "The following error has occurred" & vbCrLf & vbCrLf & _ "Error Source: File_Exist" & vbCrLf & _ "Error Number: " & Err.Number & vbCrLf & _ "Error Description: " & Err.Description & _ Switch(Erl = 0, "", Erl <> 0, vbCrLf & "Line No: " & Erl) _ , vbOKOnly + vbCritical, "An Error has Occurred!" Resume Error_Handler_Exit End Function
Usage Example
If File_Exist("C:TempFlow-Undo-Dont.jpg") = True Then 'Do something because the file exists End If
Or
If File_Exist("C:TempFlow-Undo-Dont.jpg") = False Then MsgBox "The file could not be found!", vbCritical Or vbOKOnly, "Operation Aborted" End If
Using The File System Object’s FileExist Method
'--------------------------------------------------------------------------------------- ' Procedure : FSO_File_Exist ' Author : Daniel Pineault, CARDA Consultants Inc. ' Website : http://www.cardaconsultants.com ' Purpose : Test for the existence of a file; Returns True/False ' True => File exists ' False => File does not exist ' Copyright : The following is release as Attribution-ShareAlike 4.0 International ' (CC BY-SA 4.0) - https://creativecommons.org/licenses/by-sa/4.0/ ' Req'd Refs: None required ' Also check out: https://www.devhut.net/vba-fso-files-folders-drives-and-more/ ' ' Input Variables: ' ~~~~~~~~~~~~~~~~ ' sFile : Fully qualified path and filename to check for ' ' Usage: ' ~~~~~~ ' ? FSO_File_Exist("C:TempFlow-Undo-Dont.jpg") ' Returns -> True ' ' Revision History: ' Rev Date(yyyy-mm-dd) Description ' ************************************************************************************** ' 1 2022-11-24 Initial Release '--------------------------------------------------------------------------------------- Function FSO_File_Exist(ByVal sFile As String) As Boolean On Error GoTo Error_Handler #Const FSO_EarlyBind = False #If FSO_EarlyBind = True Then Dim oFSO As Scripting.FileSystemObject Set oFSO = New FileSystemObject #Else Dim oFSO As Object Set oFSO = CreateObject("Scripting.FileSystemObject") #End If FSO_File_Exist = oFSO.FileExists(sFile) Error_Handler_Exit: On Error Resume Next Set oFSO = Nothing Exit Function Error_Handler: MsgBox "The following error has occurred" & vbCrLf & vbCrLf & _ "Error Source: FSO_File_Exist" & vbCrLf & _ "Error Number: " & Err.Number & vbCrLf & _ "Error Description: " & Err.Description & _ Switch(Erl = 0, "", Erl <> 0, vbCrLf & "Line No: " & Erl) _ , vbOKOnly + vbCritical, "An Error has occurred!" Resume Error_Handler_Exit End Function
If you go the route of FSO, I’d recommend implementing Self-Healing Object Variables, so be sure to checkout:
Self-Healing Object Variables
So what does a developer do when he can’t sleep at 3am? He decides to write an article about self-healing object variables! So What Are Self-Healing Object Variables? In plain English, these are variables that are intelligent enough that they initialize themselves once and retain their value for the entire session. If reset, they will…
Continue reading →
Usage Example
If FSO_File_Exist("C:TempFlow-Undo-Dont.jpg") = True Then 'Do something because the file exists End If
Or
If FSO_File_Exist("C:TempFlow-Undo-Dont.jpg") = False Then MsgBox "The file could not be found!", vbCritical Or vbOKOnly, "Operation Aborted" End If
Resources on the Subject
Dir function (Visual Basic for Applications)
Returns a String representing the name of a file, directory, or folder that matches a specified pattern or file attribute, or the volume label of a drive.
FileExists method (Visual Basic for Applications)
Returns True if a specified file exists; False if it does not.
VBA — FSO Files, Folders, Drives and More
Over the years, I’ve posted punctual articles relating to individual FSO solutions: and many, many more. Today, I thought I’d provide you with a complete breakdown of the File System Object (FSO) most common functions to give you a proper overview of just how useful it can be to you when you need to interact…
Continue reading →
Please Note:
This article is written for users of the following Microsoft Word versions: 97, 2000, 2002, and 2003. If you are using a later version (Word 2007 or later), this tip may not work for you. For a version of this tip written specifically for later versions of Word, click here: Determining If a File Exists.
Written by Allen Wyatt (last updated October 24, 2019)
This tip applies to Word 97, 2000, 2002, and 2003
As you are programming your macros, you may have a need to determine if a particular file exists on disk. For instance, the purpose of your macro may be to open and read from a text file. Before doing so, you will want to check to see if the file exists, in order to avoid an error.
The following function can be used to check for the existence of a file. All you need to do is pass it the full filename as a string, and the macro returns either True (if the file exists) or False (if it doesn’t).
Function FileThere(FileName As String) As Boolean FileThere = (Dir(FileName) > "") End Function
You can use the function similar to the following:
If FileThere("c:myfile.txt") Then ' ' Do stuff here ' Else MsgBox "File Not There!" End If
If you would like to know how to use the macros described on this page (or on any other page on the WordTips sites), I’ve prepared a special page that includes helpful information. Click here to open that special page in a new browser tab.
WordTips is your source for cost-effective Microsoft Word training.
(Microsoft Word is the most popular word processing software in the world.)
This tip (819) applies to Microsoft Word 97, 2000, 2002, and 2003. You can find a version of this tip for the ribbon interface of Word (Word 2007 and later) here: Determining If a File Exists.
Author Bio
With more than 50 non-fiction books and numerous magazine articles to his credit, Allen Wyatt is an internationally recognized author. He is president of Sharon Parq Associates, a computer and publishing services company. Learn more about Allen…
MORE FROM ALLEN
Documents Opening in the Wrong Program
Double-click a Word document on your desktop, and you expect Word to spring into action and load the document. What if …
Discover More
Selecting a Text Block
Word has an interesting way of allowing you to select a rectangular block of text, without reference to what may be …
Discover More
Determining a Worksheet’s Number
When you add a new worksheet to a workbook, it receives a meaningful name such as «Sheet4» or «Sheet17.» If you want to …
Discover More
More WordTips (menu)
Determining if a Text Selection Exists
Macros are often designed to be run on just a selected portion of a document. It is a good idea to make sure that the …
Discover More
Jumping to the Start or End of a Document
When creating macros, it is often necessary to move the insertion point around the document so that text can be processed …
Discover More
Deriving an Absolute Value
Want to know the absolute value of a number? It’s easy to derive in VBA by using the Abs function.
Discover More
VBA Check If File Exists If Not Create It in Excel. If not create a new file with 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:
- Overview
- Example to Check If File Exists If Not Create It using VBA Dir Function
- VBA Checking If File Exists If Not Create It using FileSystemObject(FSO) Object
- Instructions to Run VBA Macro Code
- Other Useful Resources
Example to Check If File Exists using VBA Dir Function
Let us see an example macro to check specified file exists or not. If it is not available create a new file using VBA Dir function to check file exists or not. First we are checking specified folder is available or not. If file is not available then creates a new file. In this case we creates a new Workbook. You can create any file like ppt, word, CSV, Notepad etc.
'VBA Checking If File Exists If Not Create It using Dir Function Sub VBAF1_Check_If_File_Exists_If_Not_Create_It_Using_Dir_Function() 'Variable declaration Dim sFolderPath As String Dim sFileName As String, sFilePath As String 'Define Folder Path sFolderPath = "C:VBAF1Files and Folders" 'Specify File Name which we we are looking for sFileName = "Sample.xlsx" 'Create File Path sFilePath = sFolderPath & sFileName 'Check Specified Folder exists or not If Dir(sFilePath) <> "" Then 'Check file is available or not MsgBox "File already exists!", vbInformation, "VBAF1" Exit Sub End If 'If file is not available Dim Wb As Workbook 'Create New Workbook file Set Wb = Workbooks.Add 'Save File Wb.SaveAs sFolderPath & sFileName 'Close Workbook Wb.Close 'Display Message MsgBox "New file has created successfully!", vbInformation, "VBAF1" End Sub
Output: You can find output of the above macro code.
VBA Checking If File Exists If Not Create It using FileSystemObject(FSO) Object
Let us another example macro to check specified file exists or not. If it is not available create a new file using VBA FileSystemObject(FSO) to check file exists or not.
'VBA Check If File Exists If Not Create It Sub VBAF1_Check_If_File_Exists_If_Not_Create_It_Using_FSO() 'Variable declaration Dim sFolderPath As String Dim sFileName As String, oFile As Object, bStatus As Boolean 'Define Folder Path sFolderPath = "C:VBAF1Files and Folders" 'Specify File Name which we we are looking for sFileName = "Sample2.xlsx" 'Create FSO Object Set oFSO = CreateObject("Scripting.FileSystemObject") 'Check Specified Folder exists or not If oFSO.FolderExists(sFolderPath) Then 'Check Specified file exists or not If oFSO.FileExists(sFolderPath & sFileName) Then 'If file is available MsgBox "File already exists!", vbInformation, "VBAF1" Exit Sub End If End If 'If file is not available Dim Wb As Workbook 'Create New Workbook file Set Wb = Workbooks.Add 'Save File Wb.SaveAs sFolderPath & sFileName 'Close Workbook Wb.Close 'Display Message MsgBox "New file 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!