Vba excel dir file

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:

  1. * (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.
  2. ? (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).

File Name using VBA DIR Function

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.

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.

VBA DIR Example

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 return SomeFile.txt
  • Dir("C:Some*.txt") would return SomeFile.txt (Provided there is no other file that starts with the word “Some”)
  • Dir("C:SomeFil?.txt") would return SomeFile.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 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.
VBA Dir Function

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.
VBA Dir Function

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.
VBA Dir Function

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.
VBA Dir Function

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

The VBA DIR function is also known as the directory function. It is a built-in function in VBA that gives us the file name of a given file or a folder, but we need to provide the path for the file. The output returned by this function is a string as it returns the file’s name. This function has two arguments: the path name and the attributes.

The DIR function returns the first file name in the specified folder path. So, for example, in your D drive, if you have a folder name called 2019. In that folder, if you have an Excel file named “2019 Sales,” you can access this file using the DIR function.

The VBA DIR function is very helpful in getting the file name by using its path folder.

Table of contents
  • Excel VBA DIR Function
    • Syntax
    • Examples to use VBA DIR Function
      • Example #1 – Accessing the File Name using DIR Function
      • Example #2 – Open File by using DIR Function
      • Example #3 – Multiple Open Workbooks using DIR Function
      • Example #4 – Get all the File Names in the Folder
    • Recommended Articles

VBA DIR Function

You are free to use this image on your website, templates, etc, Please provide us with an attribution linkArticle Link to be Hyperlinked
For eg:
Source: VBA DIR Function (wallstreetmojo.com)

Syntax

This function has two optional arguments.

VBA Dir Formula

  • [Path Name]: As the name says, what the path to access the file is. It could be the file’s name, the folder’s name, or the directory. It will return an empty string value if any path is not assigned.
  • [Attributes]: This is an optional argument; you may not use this often in coding. You can specify the file’s attribute in the [Path Name], and the DIR function looks for only those files.

For example: If you want to access only hidden files, if you want to access only read-only files, etc., we can specify in this argument. Below are the attributes we can use.

VBA Dir Example 1

Examples to use VBA DIR Function

You can download this VBA Dir Excel Template here – VBA Dir Excel Template

Example #1 – Accessing the File Name using DIR Function

We will explain the simple example of accessing the file name using the DIR function. Follow the below steps.

Step 1: Create a macro name.

Step 2: Define the variable as String.

Code:

Sub Dir_Example1()

  Dim MyFile As String

End Sub

Step 3: Now, we will assign a value using this variable’s DIR function.

Code:

Sub Dir_Example1()

  Dim MyFile As String

  MyFile = Dir(

End Sub

Step 4: Copy and paste the file folder path on your computer. Mention the pathname in double-quotes.

Code:

Sub Dir_Example1()

  Dim MyFile As String

  MyFile = Dir("E:VBA Template

End Sub

Step 5: We have mentioned my path to the folder. Now we need to mention the file name and its extension as well. To do this, we first need to put a backslash after the path ().

After entering the backslash, we need to enter the full file name.

Code:

Sub Dir_Example1()

  Dim MyFile As String

  MyFile = Dir("E:VBA TemplateVBA Dir Excel Template.xlsm")

End Sub

Step 6: Show the value of the variable in the message box.

Code:

Sub Dir_Example1()

  Dim MyFile As String

  MyFile = Dir("E:VBA TemplateVBA Dir Excel Template.xlsm")

  MsgBox MyFile

End Sub

Now, run the code and see the message box’s result.

VBA Dir Example 1-1

So, the DIR function returned the file name with the file extension.

Example #2 – Open File by using DIR Function

Now, how do we open the file? This function can return the file name, but opening that file is a bit different. Follow the below steps to open the file.

Step 1: Create two variables as String.

Code:

Sub Dir_Example2()

  Dim FolderName As String
  Dim FileName As String

End Sub

Step 2: Now, for the FolderName variable, assign the folder path.

Code:

Sub Dir_Example2()

  Dim FolderName As String
  Dim FileName As String

  FolderName = "E:VBA Template"

End Sub

Step 3: Now, for the FileName variable, we need to get the file name by using the DIR function.

Code:

Sub Dir_Example2()

  Dim FolderName As String
  Dim FileName As String

  FolderName = "E:VBA Template"
  FileName = Dir(

End Sub

Step 4: Now, for Path Name, we have already assigned a path to the variable FolderPath, so we can directly supply the variable here.

Code:

Sub Dir_Example2()

  Dim FolderName As String
  Dim FileName As String

  FolderName = "E:VBA Template"
  FileName = Dir(FolderName

End Sub

Step 5: Now, we need to supply the file name. By using the ampersand symbol (&), assign the file name.

Code:

Sub Dir_Example2()

  Dim FolderName As String
  Dim FileName As String

  FolderName = "E:VBA Template"
  FileName = Dir(FolderName & "VBA Dir Excel Template.xlsm")

End Sub

Step 6: Now, use the WORKBOOKS.OPEN method.

Code:

Sub Dir_Example2()

  Dim FolderName As String
  Dim FileName As String

  FolderName = "E:VBA Template"
  FileName = Dir(FolderName & "VBA Dir Excel Template.xlsm")

  Workbooks.Open

End Sub

Step 7: File Name is a combination of FolderPath & FileName. So combine these two.

Code:

Sub Dir_Example2()

  Dim FolderName As String
  Dim FileName As String

  FolderName = "E:VBA Template"
  FileName = Dir(FolderName & "VBA Dir Excel Template.xlsm")

  Workbooks.Open FolderName & FileName

End Sub

Now, run this code. It will open the mentioned file name.

Open-File Example 2

Example #3 – Multiple Open Workbooks using DIR Function

We can access all the workbooks in the folder. We cannot directly mention all the file names to access every file, but we can use the wildcard character to refer to the file.

The asterisk (*) is one of those wildcard characters. It identifies any number of characters. So, for example, if you want to access all the macro files in the folder, you can use the asterisk as the wildcard, “*.xlsm*.”

Here * will match any file name with the file’s extension equal to “xlsm.”

Code:

Sub Dir_Example3()

  Dim FolderName As String
  Dim FileName As String

  FolderName = "E:VBA Template"
  FileName = Dir(FolderName & "*.xlsm*")

  Do While FileName <> ""
  Workbooks.Open FolderName & FileName
  FileName = Dir()
  Loop

End Sub

Now, the above code will open all the files in the folder path.

FileName = Dir() we have used this line because we have to make the existing file name nil to access the next file in the folder. The moment we make the existing file name nil when the loop runs for the second time, it will take the next file in the folder.

Example #4 – Get all the File Names in the Folder

Suppose you want the list of all the file names in the folder. We can also do this by using attributes.

Code:

Sub Dir_Example4()
  Dim FileName As String
  FileName = Dir("E:VBA Template", vbDirectory)

  Do While FileName <> ""
   Debug.Print FileName
   FileName = Dir()
  Loop
End Sub

Make the immediate window visible by pressing Ctrl + G.

Get all the File Names 1

Now, run the code. We will get all the file names in the immediate window.

Get all the File Names 2

Recommended Articles

This article has been a guide to VBA DIR. Here, we learn how to use the VBA DIR function in excel along with practical examples and a downloadable template. Below you can find some useful Excel VBA articles: –

  • Excel VBA LEN
  • UserForm in VBA
  • How to Code in VBA Excel?
  • On Error in VBA
  • VBA Project Password

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!
vba save as

Learn More!

Like this post? Please share to your friends:
  • Vba excel format column
  • Vba excel form activate
  • Vba excel for шаг
  • Vba excel for синтаксис
  • Vba excel for исключения