VBA GetAttr Function

GetAttr Description

Returns an integer that represents the attributes of a file, folder, or directory.

Simple GetAttr Examples

MsgBox GetAttr("C:\")
MsgBox GetAttr("D:\Test.txt")

This will return some integer according to settings of the file/folder/drive.

If the path name doesn’t exist, it will occur an Run-time error ’53’: File not found.

GetAttr Syntax

In the VBA Editor, you can type  “GetAttr(” to see the syntax for the GetAttr Function:

The GetAttr function contains an argument:

PathName: A string expression representing a file/folder/drive.

Return values

The value returned by GetAttr is the sum of the following attribute values:

Constant Value Description
vbNormal 0 Normal.
vbReadOnly 1 Read-only.
vbHidden 2 Hidden.
vbSystem 4 System file. Not available on the Macintosh.
vbDirectory 16 Directory or folder.
vbArchive 32 File has changed since last backup. Not available on the Macintosh.
vbAlias 64 Specified file name is an alias. Available only on the Macintosh.

Examples of Excel VBA GetAttr Function

MsgBox GetAttr("C:\Program Files (x86)")
MsgBox GetAttr("C:\")

While testing with various folder/file/drive, it will return various numbers like 1, 2, 5, 22 and so on.

For example, in case of 22, it means vbDirectory(16) + vbSystem(4) + vbHidden(2).

To get the attributes settings corresponding with each number, you can use the following function.

Function GetAttributeSettings(attr As VbFileAttribute) As String
    Dim strSettings As String
    strSettings = ""
    If (attr And vbDirectory) = vbDirectory Then strSettings = strSettings & "&Directory"
    If (attr And vbVolume) = vbVolume Then strSettings = strSettings & "&Volumn"
    If (attr And vbAlias) = vbAlias Then strSettings = strSettings & "&Alias"
    If (attr And vbArchive) = vbArchive Then strSettings = strSettings & "&Archive"
    If (attr And vbHidden) = vbHidden Then strSettings = strSettings & "&Hidden"
    If (attr And vbReadOnly) = vbReadOnly Then strSettings = strSettings & "&ReadOnly"
    If (attr And vbSystem) = vbSystem Then strSettings = strSettings & "&System"

    GetAttributeSettings = Mid(strSettings, 2)
End Function
MsgBox GetAttributeSettings(22)

Result: “Directory&Hidden&System”