Specifying the Close Statement

You need to close all the files that you've opened with the Open statement. The statement for closing a file is - not surprisingly - Close. This statement takes the open file number as its only parameter. Here's the complete format for Close:

Close # intFileNumber[, intFileNumber2][,...intFileNumberX]

You can specify any number of file numbers to close in a single Close statement. If you don't specify a file number, all opened files are closed. This can be useful for terminating your applications.

The code in Listing 12.1 opens two sequential files - one for reading and one for writing - using the next available file numbers and then closes both files when done.

Listing 12.1. FreeFile() can request a file number from Visual Basic.

    1: Dim intReadFile As Integer, intWriteFile As Integer
    2: ' Handle input file
    3: intReadFile = FreeFile ' Get first file #
    4: Open "AccPay.Dat" For Input As intReadFile
    5: ' Handle output file
    6: intWriteFile = FreeFile ' Get next file #
    7: Open "AccPayOut.Dat" For Output As intWriteFile
    8: '
    9: ' Code goes here to send the contents
    10: ' of the input file to the output file
    11: ' (You'll learn how to do this later in the lesson)
    12: Close intReadFile
    13: Close intWriteFile

You never have to use an actual file number in this example, because FreeFile() in lines 3 and 6 returns the available file numbers and the code stores those values as named integers.

note

If you don't close all open files, you run a risk, albeit a small one today due to improved hardware, that the file will incur damage. Generally, if power goes out when a file is open, the file's contents might be in jeopardy. Therefore, don't keep a file open longer than you need it to be open. If you don't close a file, the system closes it when your application terminates.

You can close as many files as you want with a single Close statement. The following simple line closes all open files:

Close

On the other hand, the following lines close only two files that might be open:

Close 3

Close 6

You may want to close certain files in the middle of a program when you're finished with them but still need to access other open files.

Top Home