The VBA GetAttr Function
The VBA GetAttr Function
Related Functions:
VBA FileDateTime
VBA FileLen
Description
The VBA GetAttr function returns an integer, representing the attributes of a supplied file, directory or folder.
GetAttr( PathName )
Where the PathName argument provides the path of the file, folder or directory that you want details of.
The function returns an integer, which is the sum of all the vbFileAttribute enumerator values that apply to the
supplied path.
Valu
vbFileAttribute Attribute
e
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 the last backup (not available on the
Macintosh)
vbAlias 64 Supplied filename is an alias (only available on the Macintosh)
The following example uses the VBA GetAttr function to return the attributes of a read-only text file.
' Get the attributes of the file data.txt.
Dim attr As Integer
attr = GetAttr( "C:\Users\John\Documents\data.txt" )
' attr is now equal to 1 (indicates a read-only file).
' Test if file is read only, using the bitwise And Operator.
Dim rdOnly As Integer
rdOnly = attr And vbReadOnly
' rdOnly is now equal to 1 (file is read only).
' Test if file is hidden, using the bitwise And Operator.
Dim hdn As Integer
hdn = attr And vbHidden
' hdn is now equal to 0 (file is not hidden).
After running the above VBA code, the variable attr is equal to 1, which represents the enumerator value
vbReadOnly.
The above code also uses the bitwise And operator, to test if the file is read only, and to test if it is hidden. This
returns:
A non-zero value for the read-only test (i.e. the file is read only);
A zero value for the hidden test (i.e. the file is not hidden).
The following example uses the VBA GetAttr function to return the attributes of a read-only directory.
After running the above VBA code, the variable attr is equal to 17, which represents the enumerator values
vbReadOnly + vbDirectory (=1+16).
The above code also uses the bitwise And operator, to test if the supplied path is a directory, is read only or is
hidden. This returns:
A non-zero value for the directory test (i.e. the path is a directory);
A non-zero value for the read-only test (i.e. the directory is read only);
A zero value for the hidden test (i.e. the directory is not hidden).