Return to VBA Code Examples

VBA Dir Function

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!