Opening a text file

VBA's Open statement (not to be confused with the Open method of the Workbooks object) is used to open a file for reading or writing. Before you can read from or write to a file, you must open it.

The Open statement is quite versatile and has a rather complex syntax:

Open pathname For mode [Access access] [lock] _ As [#]filenumber [Len=reclength]

♦ pathname: (Required) The pathname part of the Open statement is quite straightforward. It simply contains the name and path (optional) of the file to be opened.

♦ mode: (Required) The file mode must be one of the following:

■ Append: A sequential access mode that either allows the file to be read, or data to be appended to the end of the file.

■ Input: A sequential access mode that allows the file to be read but not written to.

■ Output: A sequential access mode that allows the file to be read or written to. In this mode, a new file is always created. (An existing file with the same name is deleted.)

■ Binary: A random access mode that allows data to be read or written to on a byte-by-byte basis.

■ Random: A random access mode that allows data to be read or written in units determined by the reclength argument of the Open statement.

♦ access: (Optional) The access argument determines what can be done with the file. It can be Read, Write, or Read Write.

♦ lock: (Optional) The lock argument is useful for multiuser situations. The options are Shared, Lock Read, Lock Write, and Lock Read Write.

♦ filenumber: (Required) A file number ranging from 1 to 511. You can use the FreeFile function to get the next available file number. (Read about FreeFile in the upcoming section, "Getting a file number.")

♦ reclength: (Optional) The record length (for random access files) or the buffer size (for sequential access files).

0 0

Post a comment