top of page

Getting file / folder attributes

  • Writer: John
    John
  • 2 days ago
  • 2 min read

Updated: 10 hours ago

This post is one of a series providing implementation examples of Windows API Functions, Types, Enums and Consts using VBA. The code in this post can be used as-is, however, if you regularly (or even just occasionally) work with Windows API declarations in VBA, you may want to see the posts Automatically add Windows API declaration(s) and Using 'F1' to view Windows API web pages which explain some of the functionality that can be added to the VBE by VBE_Extras.

Using the GetAttr VBA Function you can get various attributes for a file or folder including whether it is read-only, hidden, a system file and whether it is a file or folder. You can get a little more detail using the Attributes property of the FileSystemObject. But for even more attributes, you can use the GetFileAttributes Windows API Function which will retrieve any of the attributes listed on the File Attributes Constants page which are summarised in this Enum (see the web page for the meaning of each attribute) ...



The core code required to get the attributes for any particular file or folder (in addition to the above Enum) is the following ...



Note that the code uses the "W" variant of the GetFileAttributes Function. This is to handle any Unicode (or "wide" ... hence "W") characters present in the the file or folder name and path. Using the "A" variant ("A" standing for "ANSI") of the GetFileAttributes Function would mean that the Function would fail if any non-ANSI characters were present in the file or folder name and path.


An example of using the above is ...



... which isn't terribly helpful all by itself. However, this code can then be added to ... to get whether a file or folder has a specific attribute (in this case whether it is compressed) you can do such as ...



Or to get all attributes for a file or folder as a string you can use this code ...



The GetFILE_ATTRIBUTEAsString Function, by the way, wasn't typed into the VBE manually ... VBE_Extras created it for me using the Add a "GetEnumAsString()" Function command.


An example usage (actually multiple) for this is ...



As per the code comment, you might first want to create the "SomeTextFile.txt" file on your Desktop.


If you want to work with the SetFileAttributes Windows API Function to update the file / folder attributes, see the post Setting file / folder attributes.

bottom of page