Locating a Free File Number

Visual Basic lets you open multiple files at once, as long as you assign each file a different file number. You need to keep track of the next available number, especially if you open files in a function that has no way of knowing whether other functions have opened files. Visual Basic provides the FreeFile() function, which can be used to determine the next available file number. By using this function, you're guaranteed that the file number you use hasn't already been used by an open file. Here's the format of FreeFile():

FreeFile[(intRangeNumber)]

The optional intRangeNumber parameter lets you specify that you want the returned file number to be in a specific range: 1-255 or 256-511. The default range, if you specify no intRangeNumber parameter, is 1-255. Almost all Visual Basic programmers keep the default because rarely, if ever, do programs need to open more than 256 files. Without the intRangeNumber parameter, you do not need to include the function's parentheses.

The following lines use FreeFile() to obtain a file number and then open a file with that number:

    
    intFileNumber = FreeFile
    Open "AccPay.Dat" For Output As intFileNumber
     
    

Use FreeFile() whenever you want to ensure that a file number isn't already in use. This might not be necessary for small applications that use only a few files. However, even in small applications, it helps to use FreeFile() to ensure that you don't accidentally use the same file number for more than one file at a time.

caution

Avoid the shortcut of using FreeFile within the Open statement, as shown here:

Open strFileName For Output As FreeFile()

Although this works, you have no way of knowing the file number for later operations on the file.

Top Home