The VBA FileAttr Function

Description

The VBA FileAttr function returns an integer, representing the mode (or system file handle) of a file that has been opened using the VBA Open statement.

The syntax of the function is:

FileAttr( FileNumber, [ReturnType] )

Where the arguments are as follows:

FileNumber - The file number associated to the file that you are querying.
[ReturnType] -

A number, representing the type of information that you want to be returned. This can be either:

1 - Return the mode of the file.
2 - Return the operating system file handle (only available on 16-bit systems).
If omitted, the [ReturnType] uses the default value 1.

If the [ReturnType] argument is set to 1 (or is omitted), the FileAttr function returns an integer, representing the mode of the specified file. This may be any of the following:

Value Mode
1 Input
2 Output
4 Random
8 Append
32 Binary

VBA FileAttr Function Examples

In the example below, the VBA FileAttr function is used to return the mode of two open files.

' Find the modes of two open files.
Dim fmode1 As Integer
Dim fmode2 As Integer
' Open the files data1.txt and data2.txt.
Open "C:\Users\John\Documents\data1.txt" For Input As #1
Open "C:\Users\John\Documents\data2.txt" For Output As #2
' Get the mode of the file data1.txt.
fmode1 = FileAttr( 1 )
' fmode1 is now equal to 1 (indicates file open for Input).
' Get the mode of the file data2.txt.
fmode2 = FileAttr( 2 )
' fmode2 is now equal to 2 (indicates file open for Output).

Note that, in both of the above calls to the FileAttr function, the [ReturnType] argument is omitted and so the default value 1 is used (meaning the mode of the supplied file should be returned).

Therefore, after running the above VBA code:


VBA FileAttr Function Errors

If the FileAttr function is supplied with a FileNumber that does not exist, you will get the error:

Run-time error '52': Bad file name or number

If the [ReturnType] argument is set to 2, and the current system is not a 16-bit system, you will get the error:

Run-time error '5': Invalid procedure call or argument