0% found this document useful (0 votes)
58 views6 pages

How To Use The DIR Function

The DIR function in VBA returns the name of the first file or directory that matches the specified path and optional attributes. It can be used to test if a file exists, list all files and directories within a folder, and find files with a particular file extension. The DIR function searches for matches using the path and wildcard characters like * and ?. Subsequent calls to DIR with no arguments return additional matches.

Uploaded by

Yamini Shinde
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
58 views6 pages

How To Use The DIR Function

The DIR function in VBA returns the name of the first file or directory that matches the specified path and optional attributes. It can be used to test if a file exists, list all files and directories within a folder, and find files with a particular file extension. The DIR function searches for matches using the path and wildcard characters like * and ?. Subsequent calls to DIR with no arguments return additional matches.

Uploaded by

Yamini Shinde
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 6

How to use the DIR Function (VBA)

This Excel tutorial explains how to use the Excel DIR function with syntax and
examples.

Description
The Microsoft Excel DIR function returns the first filename that matches
the pathname and attributes specified. To retrieve additional filenames that
match pathname and attributes, call DIR again with no arguments.
The DIR function is a built-in function in Excel that is categorized as a File/Directory
Function. It can be used as a VBA function (VBA) in Excel. As a VBA function, you can
use this function in macro code that is entered through the Microsoft Visual Basic Editor.

Syntax
The syntax for the DIR function in Microsoft Excel is:

Dir [( path [, attributes ] ) ]

Parameters or Arguments
path
Optional. It the path to a file, folder, or directory. If the path is not found, the DIR
function will return a zero-length string.
attributes
Optional. It is the sum of the file attributes. File attributes can be one or a
combination of the following values:

VB Constant Value Explanation

vbNormal 0 Normal (Default)

vbReadOnly 1 Read-only

vbHidden 2 Hidden

vbSystem 4 System file

vbVolume 8 Volume label

vbDirectory 16 Directory or folder


VB Constant Value Explanation

vbAlias 64 File name is an alias

Note
vbNormal - files with no specific attributes
vbReadOnly - read only files, in addition to files with no attributes
vbHidden - hidden files, in addition to files with no attributes
vbSystem - system files, in addition to files with no attributes (not available on the
Macintosh)
vbVolume - volume label
vbDirectory - directories or folders, in addition to files with no attributes
vbAlias - specified filename is an alias (only available on the Macintosh)
If omitted, the [Attributes] argument is set to vbNormal.

You can use wildcard characters to specify multiple files. The patterns that you can
choose from are:

Wildcar
Explanation
d

* Allows you to match any string of any length (including zero length)

? Allows you to match on a single character

Dir ("")

Returns
The DIR function returns a string value.

Example (as VBA Function)


The DIR function can only be used in VBA code in Microsoft Excel.
Let's look at some Excel DIR function examples and explore how to use the DIR
function in Excel VBA code:

Dir("C:\instructions.doc")
Result: "instructions.doc"

Dir("C:\in*.doc")
Result: "instructions.doc"

Dir("C:\instruction?.doc")
Result: "instructions.doc"

For example:

Dim LResult As String

LResult = Dir("C:\instructions.doc")

In this example, the variable called LResult would now contain the filename of
the instructions.doc file.

Frequently Asked Questions

Question: How can I use the DIR function to test whether a file exists?
Answer: This can be done with a formula that utilizes a combination of the DIR
function, IF function, and LEN function.
For example:

If Len(Dir("c:\Instructions.doc")) = 0 Then
Msgbox "This file does NOT exist."
Else
Msgbox "This file does exist."
End If
Question: I'm not sure if a particular directory exists already. If it doesn't exist, I'd like to
create it using VBA code. How can I do this?
Answer: You can test to see if a directory exists using the VBA code below:

If Len(Dir("c:\TOTN\Excel\Examples", vbDirectory)) = 0 Then


MkDir "c:\TOTN\Excel\Examples"
End If

In this example, the code would first check to see if


the c:\TOTN\Excel\Examples directory exists. If it doesn't exist, the MKDIR
statement would create a new directory called Examples under
the c:\TOTN\Excel directory.

VBA Dir Function Examples


Example 1 - Search for a File

' Find the file "C:\Documents\data.txt"

Dim fName As String
fName = Dir( "C:\Documents\data.txt" )

' The variable "fName" now contains the string "data.txt" (if the file
' is found) or an empty text string otherwise.

If fName = "" Then

' File not found!

Else

' File found. Open file to extract data.

End If

The above call to the VBA Dir function returns the file name "data.txt" if this file is found in the
directory "C:\Documents" or returns an empty string if the file is not found.

Example 2 - List All Files and Directories


The following VBA code uses the Dir function to list all the files and directories within "C:\".

' List the files and directories within "C:\".

Dim fList As String
Dim fName As String
fName = Dir( "C:\", vbDirectory )
' The variable fName now contains the name of the first file or directory within "C:\".

Do While fName <> ""

' Store the current file or directory name in the string fList.
fList = fList & vbNewLine & fName

' Get the next file or directory within "C:\".


fName = Dir()
' The variable fName now contains the name of the next file or directory within "C:\".

Loop

' Display the list of directories in a message box.


MsgBox( "File List:" & fList )

The above VBA code causes the following message box to be displayed, listing the names of all
the files and directories in "C:\".

Note that the initial call to the Dir function provides the Path and [Attributes] arguments, and
these values are remembered in the subsequent calls to the Dir function.

Example 3 - List All .CSV Files in a Directory


The following VBA code uses the Dir function to list all .csv files in the directory C:\DataFiles\.

Note: this example uses the wildcard *, which only works on computers running Microsoft
Windows.

' Find all .csv files in directory "C:\DataFiles\"

Dim fList As String
Dim fName As String

fName = Dir( "C:\DataFiles\*.csv" )


' The variable fName now contains the name of the first .csv file within "C:\DataFiles\".

Do While fName <> ""

' Store the current file in the string fList.


fList = fList & vbNewLine & fName

' Get the next .csv file within "C:\DataFiles\".


fName = Dir()
' The variable fName now contains the name of the next .csv file within "C:\DataFiles\".

Loop

' Display the list of .csv files in a message box.


MsgBox( "List of .csv Files:" & fList )

The above VBA code causes the following message box to be displayed, listing the names of all
the .csv files in the directory "C:\DataFiles\".

Note that, as in the previous example, the Path argument is provided to the initial call to the Dir
function, and this value is remembered in the subsequent calls to the function.

You might also like