DIR is a very special function in VBA, its job is to return a string representing the name of a file, directory, or archive that matches a specified pattern. DIR function only returns the first file name or folder name from a location that matches the specified attributes.
To fetch other file names or folder names from that location that match previously specified attributes, you need to call the DIR Function again with no arguments. This property of DIR Function can be quite useful in iterating or enlisting files or directories present inside a location.
Please note that the DIR function can just give you the name of the file. But if you also need attributes of a file (like last modified date, size, etc.) then consider using FileObjectSystem.
Syntax of VBA DIR Function:
The syntax of DIR is as follows:
DIR(pathname, attributes)
Here, ‘pathname
’ specifies the location of a file, folder, or directory. If the ‘pathname
’ is not found, DIR returns a string of zero length.
‘attributes
’ is an optional argument. It can be anyone or summation of the following values:
Attribute Name | Description |
---|---|
vbNormal | Normal (Default). Specifies files with no attributes. |
vbReadOnly | Specifies read-only files as well as files with no attributes. |
vbHidden | Specifies hidden files as well as files with no attributes. |
vbSystem | Specifies System files as well as files with no attributes. |
vbVolume | Specifies volume label; If you use any other attribute with this one then, the volume label is ignored. |
vbDirectory | Specifies Directories or Folders. |
vbArchive | Specifies Archives or Backup Files. |
vbAlias | Specifies Files having different names. |
Few Important points about VBA DIR Function
- Both the arguments in DIR Function are optional.
- You can use the wildcard character (like: ‘?’ or ‘*’) with DIR to specify multiple files.
- ‘*’ allows you to match any string of any length (including zero-length)
- ‘?’ allows you to match any single character.
- You must call the DIR Function along with the ‘
pathname
’ parameter for the first time. Subsequent calls to DIR Function can be made with no arguments to retrieve the next item.
5 Beginner Level Examples of DIR Function in VBA
Example 1: Supplying a file path to DIR Function
Dir("C:SomeFile.txt")
would returnSomeFile.txt
Dir("C:Some*.txt")
would returnSomeFile.txt
(Provided there is no other file that starts with the word “Some”)Dir("C:SomeFil?.txt")
would returnSomeFile.txt
Example 2: Write a VBA code to retrieve the first .exe file from the Windows folder.
You can use the below code to do this:
Sub RetrieveFile()
File = Dir("C:Windows*.exe")
MsgBox File
End Sub
Explanation: This code retrieves the .exe file from the Windows folder and displays its name in a message box. If there are multiple .exe files inside the Windows Folder then this code will retrieve only the first one.
Example 3: Use DIR Function to check if a File exists or not.
Below is the code to check this:
Sub RetrieveFile()
File = Dir("C:WindowsCSUP.txt")
If Len(File) > 0 Then
MsgBox (File & " Exists")
Else
MsgBox ("File Doesn't Exists")
End If
End Sub
Explanation: In this code, we have supplied the filename to the DIR Function. If DIR returns a string whose length is greater than 0 that means “File Exists”. We have checked this by using an IF Function.
Example 4: Write a VBA Code to check if a directory is present or not. If the directory is not present then create that directory.
To accomplish this we can use the below code:
Sub RetriveFolder()
MyFolder = "C:TestDirectory"
Fldr = Dir(MyFolder, vbDirectory)
If Len(Fldr) > 0 Then
MsgBox (Fldr & " Already Exists")
Else
MkDir MyFolder
MsgBox ("Folder Created")
End If
End Sub
Explanation: In this code, we have supplied the folder path to the DIR Function. If DIR returns a string whose length is greater than 0 that means “Folder Exists” otherwise that Folder will be created.
Example 5: The Folder “C:Test” contains all hidden files. Write a VBA Code to retrieve the name of the first hidden file.
Sub RetrieveFile()
MyFile = Dir("C:Test*.*", vbHidden)
MsgBox MyFile
End Sub
Explanation: In this code, the DIR function will search the files with hidden attribute inside the “C:Test” folder. If this folder contains multiple hidden files then, DIR will return the first hidden file.
3 Advanced Level Examples of DIR Function in Excel
Example 6: Create a VBA code that can iterate through all the folders inside a path (immediate child folders only).
To do this we can use the following code:
Sub Iterate_Folders()
Dim ctr As Integer
ctr = 1
Path = "C:Windows " ' Path should always contain a '' at end
FirstDir = Dir(Path, vbDirectory) ' Retrieving the first entry.
Do Until FirstDir = "" ' Start the loop.
If (GetAttr(Path & FirstDir) And vbDirectory) = vbDirectory Then
ActiveSheet.Cells(ctr, 1).Value = Path & FirstDir
ctr = ctr + 1
End If
FirstDir = Dir() ' Getting next entry.
Loop
End Sub
Explanation: In this code, we have used a Do Until Loop and DIR Function to iterate through all the folders present inside a location. It writes the result in the “A:A
” range of the active sheet.
Notice that we have used DIR Function twice in this code, the first time with two arguments and the second time with no arguments to fetch the subsequent files.
Example 7: Create a VBA code that can iterate through all the files present at a location. (No need to list files under subfolders)
You can use the below code to accomplish this:
Sub Iterate_Files()
Dim ctr As Integer
ctr = 1
Path = "C:Windows " ' Path should always contain a '' at end
File = Dir(Path) ' Retrieving the first entry.
Do Until File = "" ' Start the loop.
ActiveSheet.Cells(ctr, 1).Value = Path & File
ctr = ctr + 1
File = Dir() ' Getting next entry.
Loop
End Sub
Explanation: In this code, we have used a looping statement along with DIR Function to iterate through all the files present inside a location. It writes the result in “A:A
” range of active sheet.
Example 8: Use the concept of the above two examples and write a VBA code that enlists all the files inside a current location and its subfolder.
For this example you can use the following code:
Sub Retrieve_File_listing()
Worksheets(1).Cells(2, 1).Activate
Call Enlist_Directories("C:UsersAnkitDesktopExcelTrick ", 1)
End Sub
Public Sub Enlist_Directories(strPath As String, lngSheet As Long)
Dim strFldrList() As String
Dim lngArrayMax, x As Long
lngArrayMax = 0
strFn = Dir(strPath & "*.*", 23)
While strFn <> ""
If strFn <> "." And strFn <> ".." Then
If (GetAttr(strPath & strFn) And vbDirectory) = vbDirectory Then
lngArrayMax = lngArrayMax + 1
ReDim Preserve strFldrList(lngArrayMax)
strFldrList(lngArrayMax) = strPath & strFn & ""
Else
ActiveCell.Value = strPath & strFn
Worksheets(lngSheet).Cells(ActiveCell.Row + 1, 1).Activate
End If
End If
strFn = Dir()
Wend
If lngArrayMax <> 0 Then
For x = 1 To lngArrayMax
Call Enlist_Directories(strFldrList(x), lngSheet)
Next
End If
End Sub
Explanation: This code first iterates through all the folders present inside a location and stores them in an array. Later it recursively calls the ‘Enlist_Directories
’ function to retrieve the file names.
So, this was all about VBA DIR Function in Excel.
VBA has some useful functions that can take your automation in Excel to the next level.
One such function is the VBA DIR function.
While by itself, it may seem like a simple function that does one specific thing.
But when you combine it with some other useful elements of the VBA coding language, you can create powerful stuff (covered in the examples later in this tutorial).
What Does VBA Dir Function Do?
Use VBA DIR function when you want to get the name of the file or a folder, using their path name.
To give you an example, if you have an Excel file in a folder, you can use the VBA DIR function to get the name of that Excel file (or any other type of file).
What if I want to get the names of all the Excel files in the folder (or all the files – be it Excel file or not)?
You can do that too!
When you use DIR function once, it returns the first file name in a folder. Now if you want to get the names of the second, third, fourth files as well, you can use the DIR function again (covered later as an example).
Dir returns the first file name that matches the pathname. To get any additional file names that match pathname, call Dir again with no arguments. When no more file names match, Dir returns a zero-length string (“”). Covered in Example 3 and 4 later in this tutorial.
Syntax of VBA DIR Function
Dir [ (pathname [ ,attributes ] ) ]
- pathname: This is an optional argument. This can be the file name, folder name, or directory name. If pathname is not found, VBA DIR function returns a zero-length string (“”)
- attributes: This is an optional argument. You can use this argument to specify some attributes and DIR function will return the file names based on those attributes. For example, if you want a list of all hidden files or read-only files (along with files with no attributes), you need to specify that in this argument.
Attributes available to use in VBA DIR function (you can use one or more of these):
Constant | Value | Description |
vbNormal | 0 | (Default) Specifies files with no attributes. |
vbReadOnly | 1 | Specifies read-only files in addition to files with no attributes. |
vbHidden | 2 | Specifies hidden files in addition to files with no attributes. |
VbSystem | 4 | Specifies system files in addition to files with no attributes. Not available on the Macintosh. |
vbVolume | 8 | Specifies volume label; if any other attributed is specified, vbVolume is ignored. Not available on the Macintosh. |
vbDirectory | 16 | Specifies directories or folders in addition to files with no attributes. |
vbAlias | 64 | Specified file name is an alias. Available only on the Macintosh. |
Using Wildcard Characters with DIR Function
If you’re working with Windows, you can also use the wildcard characters in the DIR function.
Note that you can not use these when working with VBA in Macintosh.
Using wildcards can be useful when:
- You want to get the file names of a particular file type (such as .XLSX or .PPTX)
- When you have a specific suffix/prefix in filenames and you want to get the names of these files/folders/directories. For example, if you want the names of all the files with the prefix 2019 in it, you can do that using wildcard characters.
There are three wildcard characters in Excel:
- * (asterisk) – It represents any number of characters. For example, 2019* would give you the names of all the files with the prefix 2019 in it.
- ? (question mark) – It represents one single character. For example, 2019? would give you the names of all the files that start with 2019 and has one more character in the name (such as 2019A, 2019B, 2019C, and so on)
Note: There is one more wildcard character – tilde (~). Since it’s not used a lot, I have skipped its explanation. You can read more about it here if interested.
VBA DIR Function – Examples
Now let’s dive in and see some examples of using the VBA DIR function.
Example 1 – Getting the File Name from its Path
When you have the path of a file, you can use the DIR function to get the name of the file from it.
For example, the below code returns the name of the file and shows it in a message box.
Sub GetFileNames() Dim FileName As String FileName = Dir("C:UserssumitDesktopTestExcel File A.xlsx") MsgBox FileName End Sub
The above code uses a variable ‘FileName’ to store the file name that is returned by the DIR function. It then uses a message box to display the file name (as shown below).
And what happens when the file doesn’t exist?
In that case, the DIR function would return an empty string.
The below code uses an If Then Else statement to check whether the file exists or not. If the file doesn’t exist, it shows a message box with a text “File Doesn’t Exist”, else it shows the file name.
Sub CheckFileExistence() Dim FileName As String FileName = Dir("C:UserssumitDesktopTestExcel File A.xlsx") If FileName <> "" Then MsgBox FileName Else MsgBox "File Doesn't Exist" End If End Sub
Example 2 – Check if a Directory Exists or Not (and create if it doesn’t)
The below code checks whether the folder ‘Test’ exists or not.
A message box is used to show a message in case the folder exists or when it doesn’t exist.
Sub CheckDirectory() Dim PathName As String Dim CheckDir As String PathName = "C:UserssumitDesktopTest" CheckDir = Dir(PathName, vbDirectory) If CheckDir <> "" Then MsgBox CheckDir & " exists" Else MsgBox "The directory doesn't exist" End If End Sub
You can refine this code further to check whether the folder exists or not, and if it doesn’t, then you can use VBA to create that folder.
Below is the code that uses the MkDir function to create a folder in case it doesn’t exist.
Sub CreateDirectory() Dim PathName As String Dim CheckDir As String PathName = "C:UserssumitDesktopTest" CheckDir = Dir(PathName, vbDirectory) If CheckDir <> "" Then MsgBox CheckDir & " folder exists" Else MkDir PathName MsgBox "A folder has been created with the name" & CheckDir End If End Sub
Example 3 – Get the Names of All File and Folders in a Directory
If you want to get a list of all the file and folder names in a directory, you can use the DIR Function.
The below code lists all the files and folder names in the Test folder (which is located at the following path – C:UserssumitDesktopTest).
I am using Debug.Print to show the names in the Immediate window. You can also use this to list the names in a message box or in a column in Excel.
Sub GetAllFile&FolderNames() Dim FileName As String FileName = Dir("C:UserssumitDesktopTest", vbDirectory) Do While FileName <> "" Debug.Print FileName FileName = Dir() Loop End Sub
The Do While loop in the above code continues till all the files and folders in the given path have been covered. When there are no more files/folders to cover, FileName becomes a null string and the loop stops.
Example 4 – Get the Names of All Files in a Folder
You can use the below code to get the names of all the files in a folder/directory (and not the names of the sub-folders).
Sub GetAllFileNames() Dim FileName As String FileName = Dir("C:UserssumitDesktopTest") Do While FileName <> "" Debug.Print FileName FileName = Dir() Loop End Sub
This code is just like the code used in Example 3, with one minor difference.
In this code, I have not specified vbDirectory in the DIR function. When you specify vbDirectory, it will give you the names of all the files as well as folders.
When you don’t specify vbDirectory, DIR function will only give you the names of the files.
Note: If you want to get the names of all the files in the main folder and the sub-folders, you can’t use the DIR function (as it’s not recursive). To do this, you can either use Power Query (no coding needed) or use the File System Object in VBA (with recursion).
Example 5 – Get the Names of All the Sub-Folders within a Folder
The below code would give you the names of all the sub-folders within the specified folder.
It uses the GetAtr function in VBA, which allows us to check whether the name returned by the DIR function is the name of a file or a folder/directory.
Sub GetSubFolderNames() Dim FileName As String Dim PathName As String PathName = "C:UserssumitDesktopTest" FileName = Dir(PathName, vbDirectory) Do While FileName <> "" If GetAttr(PathName & FileName) = vbDirectory Then Debug.Print FileName End If FileName = Dir() Loop End Sub
Again, I am using Debug.Print to get the names in the immediate window. You can get these in a message box or in Excel (by modifying the code accordingly).
Example 6 – Get the First Excel File from a Folder
With DIR function, you can specify the file extension or any suffix/prefix that you want in the file name that is returned.
The below code would display the name of the first Excel file in the Test folder.
Sub GetFirstExcelFileName() Dim FileName As String Dim PathName As String PathName = "C:UserssumitDesktopTest" FileName = Dir(PathName & "*.xls*") MsgBox FileName End Sub
Note that I have used *.xls* (asterisk sign on both sides). This will ensure that all the versions of Excel files are checked (.xls, xlsx, .xlsm, .xlsb).
Example 7 – Get Names of All Excel File in a Folder
Use the below code to get the names of all the Excel files in the Test folder.
Sub GetAllFileNames() Dim FolderName As String Dim FileName As String FolderName = "C:UserssumitDesktopTest" FileName = Dir(FolderName & "*.xls*") Do While FileName <> "" Debug.Print FileName FileName = Dir() Loop End Sub
While the DIR function returns the name of the first Excel file only, since we are calling it again in the loop, it goes through all the files and gives us the names of all the Excel files.
Hope you found this tutorial and the examples useful.
Let me know your thoughts in the comments section.
You May Also Like the Following Excel Tutorials:
- Excel VBA InStr Function.
- Excel VBA Split Function.
- Excel VBA TRIM Function
- VBA LCASE Function.
- VBA UCASE Function.
Return to VBA Code Examples
Dir Description
Returns the first filename that matches the pathname and attributes specified.
Simple Dir Examples
MsgBox Dir("")
This will return the first file name on the current path.
Dir Syntax
In the VBA Editor, you can type “Dir(” to see the syntax for the Dir Function:
The Dir function contains 2 arguments:
PathName: [Optional] A string expression representing a directory/folder/drive.
Attribute: [Optional] Specifies file attributes. If omitted, returns files that match pathname but have no attributes.
The Attribute argument settings are:
Constant | Value | Description |
---|---|---|
vbNormal | 0 | (Default) Specifies files with no attributes. |
vbReadOnly | 1 | Specifies read-only files in addition to files with no attributes. |
vbHidden | 2 | Specifies hidden files in addition to files with no attributes. |
vbSystem | 4 | Specifies system files in addition to files with no attributes. Not available on the Macintosh. |
vbVolume | 8 | Specifies volume label; if any other attribute is specified, vbVolume is ignored. Not available on the Macintosh. |
vbDirectory | 16 | Specifies directories or folders in addition to files with no attributes. |
vbAlias | 64 | Specified file name is an alias. Available only on the Macintosh. |
Examples of Excel VBA Dir Function
To list the folders&files on C drive, you can use the following code.
Sub Dir_Example()
Dim fileName As String
Dim fullName As String
Dim rng As Range
Dim i As Integer
Set rng = Range("A1")
fileName = Dir("C:", vbDirectory)
i = 1
Do
fullName = "C:" & fileName
rng.Offset(i, 0) = fileName
rng.Offset(i, 1) = FileDateTime(fullName)
rng.Offset(i, 2) = FileLen(fullName)
rng.Offset(i, 3) = GetAttr(fullName)
fileName = Dir
If fileName = "" Then Exit Do
i = i + 1
Loop
End Sub
The result will be similar with the following.
VBA Dir Function in Access VBA
The VBA Dir function works in Access VBA in the same way as it does in Excel VBA.
Function CreateDirectory(strP As String) As Boolean
If Len(Dir(strP, vbDirectory)) = 0 Then
MkDir strP
End If
CreateDirectory = True
Exit Function
ending:
CreateDirectory = False
End Function
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!
VBA Dir function in Excel is categorized as File and Directory function. This built-in VBA Dir function returns the first name of a file or directory that matches a pattern in Excel VBA.The VBA Dir function is specifically useful for listing all files located in a specified directory.
This function can be used in either procedure or function in a VBA editor window in Excel. We can use this VBA Dir Function in any number of times in any number of procedures or functions. In the following section we learn what is the syntax and parameters of the Dir function, where we can use this Dir Function and real-time examples in Excel VBA.
Table of Contents:
- Overview
- Syntax of VBA Dir Function
- Parameters or Arguments
- Where we can apply or use VBA Dir Function?
- Example 1: Check whether file exists or not?
- Example 2: List all .xls Files in a Folder using Wild card character(*)
- Example 3: List all Files in a Folder using Wild card character(?)
- Example 4: List all files in a ‘C’ Directory using File Attribute(vbDirectory)
- Instructions to Run VBA Macro Code
- Other Useful Resources
The syntax of the Dir Function in VBA is
Dir([PathName],[Attribute])
Note: The Dir Function returns a string value.
Parameters or Arguments:
The Dir function has two arguments in Excel VBA.
where
PathName: It is an optional parameter. The PathName argument represents a file, folder or directory. If specified path is not available, then DIR function will return a zero-length string.
Attribute: It is an optional parameter. The Attribute represents the file attributes. These file attributes can be one or a combination of the following values.
VBA CONSTANT | VALUE | DESCRIPTION |
---|---|---|
vbNormal | 0 | Normal (Default) |
vbReadOnly | 1 | Read-only |
vbHidden | 2 | Hidden |
vbSystem | 4 | System file |
vbVolume | 8 | Volume label |
vbDirectory | 16 | Directory or folder |
vbAlias | 64 | File name is an alias |
Note: We can use wildcard characters, when we want to specify multiple file attributes. We can use either * and ? as wildcard characters.
Wild Card Character | Description |
---|---|
* | Allows you to match any string of any length (including zero length) |
? | Allows you to match on a single character |
Where we can apply or use VBA Dir Function?
We can use this Dir Function in VBA MS Office 365, MS Excel 2016, MS Excel 2013, 2011, Excel 2010, Excel 2007, Excel 2003, Excel 2016 for Mac, Excel 2011 for Mac, Excel Online, Excel for iPhone, Excel for iPad, Excel for Android tablets and Excel for Android Mobiles.
Example 1: Check whether file exists or not
Here is a simple example of the VBA Dir function. This below example checks whether file exists or not.
'Check whether file exists or not Sub VBA_Dir_Function_Ex1() 'Variable declaration Dim sPath As String Dim sStatus As String sPath = "C:TempVBAF1String_Functions.xls" sStatus = Dir(sPath) If sStatus <> "" Then MsgBox "Specified file found.", vbInformation, "VBA Dir Function" Else MsgBox "Specified file not found.", vbInformation, "VBA Dir Function" End If End Sub
Output: Here is the screen shot of the first example output.
Example 2: List all .xls Files in a Folder using Wild card character(*)
Here is a simple example of the VBA Dir function. This below example lists all .xls Files in a folder using Wild card character(*) and returns all available .xls files.
'List all .xls Files in a Folder using Wild card character(*) Sub VBA_Dir_Function_Ex2() 'Variable declaration Dim sPath As String Dim sFile As String, fList As String sPath = "C:VBAF1VBA FunctionsVBA Text Functions*.xls" 'Read current file sFile = Dir(sPath) 'Loop through all files in a directory Do While sFile <> "" fList = fList & vbCrLf & sFile sFile = Dir() Loop MsgBox "List of all .xls files: " & fList, vbInformation, "VBA Dir Function" End Sub
Output: Here is the screen shot of the second example output.
Example 3: List all Files in a Folder using Wild card character(* and ?)
Here is a simple example of the VBA Dir function. This below example lists all .doc Files in a folder using Wild card character(* and ?) and returns all available .doc files.
'List all Files in a Folder using Wild card character(?) Sub VBA_Dir_Function_Ex3() 'Variable declaration Dim sPath As String Dim sFile As String, fList As String sPath = "C:VBAF1VBA FunctionsVBA Text Functions*.doc?" 'Read current file sFile = Dir(sPath) 'Loop through all files in a directory Do While sFile <> "" fList = fList & vbCrLf & sFile sFile = Dir() Loop MsgBox "List of all .xls files: " & fList, vbInformation, "VBA Dir Function" End Sub
Output: Here is the screen shot of the third example output.
Example 4: List all files in a ‘C’ Directory using File Attribute(vbDirectory)
Here is a simple example of the VBA Dir function. This below example lists all available files from ‘C’ Directory. It uses file attribute vbDirectory in the following example.
'List all files in a 'C' Directory using File Attribute(vbDirectory) Sub VBA_Dir_Function_Ex4() 'Variable declaration Dim sPath As String Dim sFile As String, fList As String sPath = "C:" 'Read current file sFile = Dir(sPath, vbDirectory) 'Loop through all files in a directory Do While sFile <> "" fList = fList & vbCrLf & sFile sFile = Dir() Loop MsgBox "List of all files in 'C' Directory: " & fList, vbInformation, "VBA Dir Function" End Sub
Output: Here is the screen shot of the fourth example output.
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 in Excel Blog
VBA Editor Keyboard Shortcut Keys List VBA Interview Questions & Answers
В этом учебном материале вы узнаете, как использовать Excel функцию DIR с синтаксисом и примерами.
Описание
Microsoft Excel функция DIR возвращает первое имя файла, которое соответствует указанному пути и атрибутам. Чтобы получить дополнительные имена файлов, которые соответствуют имени пути и атрибутам, вызовите DIR еще раз без аргументов.
Функция DIR — это встроенная в Excel функция, которая относится к категории функций файлов/каталогов. Её можно использовать как функцию VBA в Excel.
В качестве функции VBA вы можете использовать эту функцию в коде макроса, который вводится через редактор Microsoft Visual Basic Editor.
Синтаксис
Синтаксис функции DIR в Microsoft Excel:
Dir [( path [, attributes ])]
Аргументы или параметры
- path
- Необязательно. Это путь к файлу, папке или каталогу.
Еслиpath
не найден, функция DIR вернет строку нулевой длины. - attributes
- Необязательно. Это сумма атрибутов файла. Атрибуты файла могут быть одним из следующих значений или их комбинацией:
Константа VB Значение Пояснение vbNormal 0 Нормальный (по умолчанию ) vbReadOnly 1 Только для чтения vbHidden 2 Скрытый vbSystem 4 Системный файл vbVolume 8 Метка тома vbDirectory 16 Каталог или папка vbAlias 64 Имя файла является псевдонимом
Примечание
Вы можете использовать подстановочные знаки для указания нескольких файлов. Вы можете выбрать следующие шаблоны:
Подстановочный символ | Пояснение |
---|---|
* | Позволяет сопоставить любую строку любой длины (включая нулевую) |
? | Позволяет сопоставить один символ |
Возвращаемое значение
Функция DIR возвращает строковое значение.
Применение
- Excel для Office 365, Excel 2019, Excel 2016, Excel 2013, Excel 2011 для Mac, Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000
Тип функции
- Функция VBA
Пример (как функция VBA)
Функция DIR может использоваться только в коде VBA в Microsoft Excel.
Рассмотрим несколько примеров функции Excel DIR, чтобы понять, как использовать Excel функцию DIR в коде Excel VBA:
Dir(«C:tracert.txt») Результат: «tracert.txt» Dir(«C:tr*.txt») Результат: «tracert.txt» Dir(«C:tracer?.txt») Результат: «tracert.txt» |
Например:
Dim LResult As String LResult = Dir(«C:tracert.txt») |
В этом примере переменная с именем LResult теперь будет содержать имя файла tracert.txt.
Часто задаваемые вопросы
Вопрос: Как я могу использовать функцию DIR, чтобы проверить, существует ли файл?
Ответ: Это может выполняется с помощью формулы, в которой используется комбинация функций DIR, IF и LEN, например:
If Len(Dir(«c:Instructions.doc»)) = 0 Then Msgbox «Этот файл НЕ существует.» Else Msgbox «Этот файл существует.» End If |
Вопрос: Я не уверен, существует ли уже конкретный каталог.
Если его не существует, я бы хотел создать его с помощью кода VBA. Как я могу это сделать?
Ответ: Вы можете проверить, существует ли каталог, используя приведенный ниже код VBA:
If Len(Dir(«c:alexExcelExamples», vbDirectory)) = 0 Then MkDir «c:alexExcelExamples» End If |
В этом примере код сначала проверяет, существует ли каталог c:alexExcelExamples.
Если он не существует, то оператор MKDIR создаст новый каталог с именем Examples в каталоге c:alexExcel.
Excel VBA DIR Function
Dir is one of the functions available in VBA. Dir function is for referring Directories in VBA code.
The function that returns the file or directory name that matches with the given attribute or string otherwise returns the first file or folder. In simple words, if we have a folder ABC and inside ABC there is a file XYZ then we can access XYZ file using DIR function in VBA.
Formula For DIR Function in Excel VBA
DIR function has the following syntax in Excel VBA:
It has two parts Pathname and Attributes.
- Pathname: By the name, everyone can understand it is the path of the file where actually the file exists. If we do not input any path in pathname it will return an empty string.
- Attribute: It is an optional argument, we do not use much of this. We may use this when we want to open the file with the below attributes then VBA looks for those files.
vbArchive | Specifies Archives or Backup Files. |
vbNormal | Normal (Default) or no attributes. |
vbReadOnly | read-only files |
vbSystem | System files |
vbVolume | volume label; If you use any other attribute with this one then, volume label is ignored. |
vbDirectory | Directories or Folders. |
vbHidden | hidden files |
vbAlias | File name is an alias |
How to Use DIR Function in Excel VBA?
Below are the different examples to use DIR Function in Excel using VBA code.
You can download this VBA DIR Excel Template here – VBA DIR Excel Template
VBA DIR Function – Example #1
In this example, we will see how to access a file name using the DIR function in VBA.
Step 1: Go to the Developers tab and click on Visual Basic
Step 2: Open a Module from the Insert menu option as shown below.
Step 3: To start any macro, first we need to give a name to the macro with the keyword ‘sub’ as below.
Code:
Sub myexample1() End Sub
Remember we are writing our code in “Module1” when we input “sub myexample()”, automatically the “End sub” will appear.
Step 4: Define a string by using the keyword “Dim” which refers to dimension. In the below screenshot “mystring” is the string name.
Code:
Sub myexample1() Dim mystring As String End Sub
Remember whenever you define the names of data types or program names there should not be any space between two words. “Mystring” no space between “my” and “string”.
The file is available in sample folder which is available on the Desktop and the file name is “KT tracker mine”.
C:Userscba_13DesktopSample
Step 5: Now we need to store the file name in “mystring” using Dir function.
Code:
Sub myexample1() Dim mystring As String mystring = Dir("C:Userscba_13DesktopSample") End Sub
In the above screenshot in Dir function, I have given the file path excluding file name. As there is only one file it will return the file name.
Step 6: Now with the above step the file name stored in the string “mystring”. To display the file name, we need to display it through a message box. Create a message box.
Code:
Sub myexample1() Dim mystring As String mystring = Dir("C:Userscba_13DesktopSample") MsgBox (mystring) End Sub
We gave the instruction to display the data in “mystring” through message box, as “mystring” has file name it will display the file name through the message box.
Step 7: Now run the code by clicking on the Play button or by pressing the F5 key.
VBA DIR Function – Example #2
In this example, we will see how to open a file using the DIR function in Excel VBA.
Step 1: Open the VBA code screen and start by giving the program name as “example2” or any name you wish for.
Code:
Sub example2() End Sub
Step 2: Define two strings with the names “Foldername” and “Filename”.
Code:
Sub example2() Dim Foldername As String Dim Filename As String End Sub
Step 3: Now assign the folder path to the folder name.
Code:
Sub example2() Dim Foldername As String Dim Filename As String Foldername = "C:Userscba_13DesktopSample" End Sub
Step 4: Assign the file to the “filename” using the Dir function. Here we used the “Foldername” variable because it has the folder path. With the help of ampersand, we added the file name to the path.
Code:
Sub example2() Dim Foldername As String Dim Filename As String Foldername = "C:Userscba_13DesktopSample" Filename = Dir(Foldername & "KT Tracker mine.xlsx") End Sub
Now Dir function returns the file name and it will store in the variable “filename”.
Step 5: In the previous example, we used the message box to see the results. But, in this we want to open the file, so we will use the command “workbooks.open”.
Code:
Sub example2() Dim Foldername As String Dim Filename As String Foldername = "C:Userscba_13DesktopSample" Filename = Dir(Foldername & "KT Tracker mine.xlsx") Workbooks.Open Foldername & Filename End Sub
Step 6: Run the above code it will open the file available in the folder “C:Userscba_13DesktopSample” with the file name “KT Tracker mine”.
VBA DIR Function – Example #3
Now we will see the program to know whether a folder is available or not. I have the folder “Data” as shown below.
We have to check with the help of Dir function whether “Data” folder is available in the path C:Userscba_13DesktopSample.
Step 1: Create a program name and define two strings with the names FD and FD1.
Code:
Sub example3() Dim Fd As String Dim Fd1 As String End Sub
Step 2: Assign the folder path to variable “Fd”.
Code:
Sub example3() Dim Fd As String Dim Fd1 As String Fd = "C:Userscba_13DesktopSampleData" End Sub
Step 3: Now use the Dir function to return the folder name as shown below.
Code:
Sub example3() Dim Fd As String Dim Fd1 As String Fd = "C:Userscba_13DesktopSampleData" Fd1 = Dir(Fd, vbDirectory) End Sub
The Dir function result should be folder name and it will store in Fd1 string variable. If the “Data” folder is not available in the respective folder, it will not return any string.
Step 4: Now we need to check whether Fd1 has a “Data” folder or not. Use IF condition to check whether Fd1 has string “Data” or not. If it is available, then print the statement as “Exists”.
Code:
Sub example3() Dim Fd As String Dim Fd1 As String Fd = "C:Userscba_13DesktopSampleData" Fd1 = Dir(Fd, vbDirectory) If Fd1 = "Data" Then MsgBox ("Exits") End Sub
Step 5: In case if Fd1 does not match with “Data” folder will print the statement “Not Exists” in else condition.
Code:
Sub example3() Dim Fd As String Dim Fd1 As String Fd = "C:Userscba_13DesktopSampleData" Fd1 = Dir(Fd, vbDirectory) If Fd1 = "Data" Then MsgBox ("Exits") Else MsgBox ("Not Exits") End Sub
Step 6: End the “If” loop as shown in the below screenshot.
Code:
Sub example3() Dim Fd As String Dim Fd1 As String Fd = "C:Userscba_13DesktopSampleData" Fd1 = Dir(Fd, vbDirectory) If Fd1 = "Data" Then MsgBox ("Exits") Else MsgBox ("Not Exits") End If End Sub
Step 7: Run the code by pressing the F5 key or by clicking on the Play button to check whether the folder is available or not. If the folder “Data” is available in that folder, then it will return the message box with the message “Exists” as below.
Step 8: Just change the name of the folder as Data1.
Sub example3() Dim Fd As String Dim Fd1 As String Fd = "C:Userscba_13DesktopSampleData1" Fd1 = Dir(Fd, vbDirectory) If Fd1 = "Data" Then MsgBox ("Exits") Else MsgBox ("Not Exits") End If End Sub
Step 9: Run the code again. Now the result is “Not exists” as shown below.
Things to Remember
- The arguments in the Dir function are optional.
- If we want hidden files, folders or different type of directories then mention your requirement in the second argument.
- Use “” at the end of the folder name while giving in Dir function to go into the folder.
- If we want to call or open multiple files we can use the wild card character “*” or “?”.
Recommended Articles
This is a guide to VBA DIR Function. Here we discuss how to use DIR Function in Excel VBA along with some practical examples and downloadable excel template. You can also go through our other suggested articles –
- VBA Workbook
- INDIRECT Function in Excel
- VBA Count
- Excel XOR Function
title | keywords | f1_keywords | ms.prod | ms.assetid | ms.date | ms.localizationpriority |
---|---|---|---|---|---|---|
Dir function (Visual Basic for Applications) |
vblr6.chm1008898 |
vblr6.chm1008898 |
office |
eaf6fe6e-342a-5038-3914-bb5e58fcad5a |
12/12/2018 |
high |
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.
Syntax
Dir [ (pathname, [ attributes ] ) ]
The Dir function syntax has these parts:
Part | Description |
---|---|
pathname | Optional. String expression that specifies a file name; may include directory or folder, and drive. A zero-length string («») is returned if pathname is not found. |
attributes | Optional. Constant or numeric expression, whose sum specifies file attributes. If omitted, returns files that match pathname but have no attributes. |
Settings
The attributes argument settings are:
Constant | Value | Description |
---|---|---|
vbNormal | 0 | (Default) Specifies files with no attributes. |
vbReadOnly | 1 | Specifies read-only files in addition to files with no attributes. |
vbHidden | 2 | Specifies hidden files in addition to files with no attributes. |
vbSystem | 4 | Specifies system files in addition to files with no attributes. Not available on the Macintosh. |
vbVolume | 8 | Specifies volume label; if any other attribute is specified, vbVolume is ignored. Not available on the Macintosh. |
vbDirectory | 16 | Specifies directories or folders in addition to files with no attributes. |
vbAlias | 64 | Specified file name is an alias. Available only on the Macintosh. |
[!NOTE]
These constants are specified by Visual Basic for Applications and can be used anywhere in your code in place of the actual values.
Remarks
In Microsoft Windows and macOS, Dir supports the use of multiple character (*) and single character (?) wildcards to specify multiple files.
Because the Macintosh doesn’t support the wildcards, use the file type to identify groups of files. Use the MacID function to specify file type instead of using the file names. For example, the following statement returns the name of the first TEXT file in the current folder:
Dir("SomePath", MacID("TEXT"))
To iterate over all files in a folder, specify an empty string:
If you use the MacID function with Dir in Microsoft Windows, an error occurs.
Any attribute value greater than 256 is considered a MacID value.
You must specify pathname the first time you call the Dir function, or an error occurs. If you also specify file attributes, pathname must be included.
Dir returns the first file name that matches pathname. To get any additional file names that match pathname, call Dir again with no arguments. When no more file names match, Dir returns a zero-length string («»). After a zero-length string is returned, you must specify pathname in subsequent calls, or an error occurs.
You can change to a new pathname without retrieving all of the file names that match the current pathname. However, you can’t call the Dir function recursively. Calling Dir with the vbDirectory attribute does not continually return subdirectories.
[!TIP]
Because file names are retrieved in case-insensitive order on Windows and case-sensitive order on macOS, you may want to store returned file names in an array, and then sort the array.
See also
- Functions (Visual Basic for Applications)
[!includeSupport and feedback]
Функция Dir служит для проверки существования каталога или файла, отвечающих заданному образцу.
Функция поддерживает использование подстановочных знаков для нескольких символов (*) и одиночного символа (?) для указания нескольких файлов. Функция возвращает первое имя файла, имя которого соответствует аргументу PathName. Для получения остальных файлов, имена которых соответствуют PathName, следует повторно вызвать функцию Dir без аргументов. Последовательные вызовы функции без аргументов возможны до тех пор, пока имеются файлы или папки, соответствующие образцу первого вызова (с аргументами)
Примечание Рекурсивные вызовы функции Dir запрещены
Синтаксис функции в VBA:
Dir[ (PathName[, Attributes])]
Функция возвращает данные типа String, структурно представляющего имя файла или папки, которые удовлетворяют указанному шаблону имени файла, набору атрибутов файла или метке тома на диске. Если аргумент PathName не найден, то функция Dir возвращает пустую строку (““)
Примечание Если после возврата функцией пустой строки, снова вызвать функцию без аргументов, то возникает ошибка времени исполнения Invalid procedure call or argument
Параметры функции
PathName — Необязательный аргумент. Строковое выражение, указывающее имя файла. Также может содержать имя каталога или папки и диска. При использовании имен файлов или папок, содержащих пробелы следует использовать дополнительные кавычки —Dir (» «C:Русский Проектapp.exe“») или Dir (Chr (34) & «C:Русский Проектapp.exe» & Chr (34))
Примечание Хотя PathName указан, как необязательный аргумент, он обязателен при первом вызове функции, а также в случаях, если задан аргумент Attributes
Attributes — Необязательный аргумент, содержащее константу или числовое выражение, описывающее атрибуты файла. Если этот аргумент опущен, возвращаются все файлы, имена которых удовлетворяют содержимому аргумента PathName.
Допустимые значения Attributes
vbNormal=0 — Обычное состояние файла. Используется по умолчанию
vbReadOnly=1 — Атрибут только для чтения
vbHidden=2 — Скрытый атрибут
vbSystem=4 — Системный атрибут
vbVolume=8 — Метка тома
vbDirectory=16 — Каталог или папка
Примечание Можно также указывать комбинации атрибутов путем их суммирования
Например, vbHidden+vbDirectory выводит скрытые папки
Пример кода на языке программирования VBA (Visual Basic for Applications):
' Примеры использования функции
Dim retval
' При наличии выводит WIN.INI
retval=Dir ( «c:windowswin.ini»)
Print retval
' Возвращает имя файла с расширением txt
' При наличии нескольких файлов возвращается
' первый найденный файл
retval =
Dir ( «
c:
windows*.
txt»)
MsgBox retval