Close Statement |
Named Arguments
No
Syntax
Close [filenumber]
filenumber
Use: Optional
Data Type: Integer
The file number used when opening the file in the Open statement.
Description
Closes a file opened with the Open statement.
Rules at a Glance
If filenumber is omitted, all open files are closed.
If the file you are closing was opened for output or append, the remaining data in the I/O buffer is written to the file. The memory buffer is then reclaimed.
When the Close statement is executed, the file number used is freed for further use.
The hash (#) sign in front of the file number is optional.
filenumber can either be a numeric constant (e.g., #1) or a numeric variable.
Example
Dim intFileNo as Integer intFileNo = FreeFile() Open sFileNameString For Output As #intFileNo Write #intFileNo, sOutputString Close #intFileNo
Programming Tips and Gotchas
You can close more than one file at once with the Close method, by specifying the file numbers as a comma-delimited list, as shown below:
Close #1, #3, #4
The Close statement doesn't check first to see if there is a file associated with the given file number. Therefore, no error occurs if you use the Close statement with a nonexistent file number. The drawback to this is that you may think you have closed a file inadvertently when in fact you haven't, thereby leaving the file open, as this snippet demonstrates:
Dim sFilename As String sFilename = "testtext.txt" Open sFilename For Output As #1 Write #1, sFilename Close #2 'just to prove ...
Get VB & VBA in a Nutshell: The Language now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.