You are on page 1of 4

File Access in VBA In Visual Basic for Applications, there are three types of file access.

These types are listed in the following table.

Type Access Sequential Random Access Binary

Note Used with simple text files. Used for files that are composed of a series of records of identical length. Used for files with no general format. You must know exactly how the data is written to the file in order to retrieve it.

File Access Functions Close EOF FreeFile

Function's Action Closes the file Tests for end of file Returns the next file number available for use by the Open statement. Reads data from a file at a specific record number Returns all characters (bytes) from an open file Reads a line of text into a list of variables Reads an entire line of text into a single variable Returns the current read/write position within an open file. Returns the size, in bytes, of a file opened using the Open statement Opens a file with a specified access type Writes data to a file at a specific record number Returns the current read/write position within a file opened using the Open statement Writes data to a file opened for sequential access

Sequential Access X X X

Random Access X X X

Binary Access X X X

Get Input$ Input # Line Input # Loc LOF Open Put Seek

X X X X X X X X X X X X X

X X

X X X X X

Write #

Using Sequential Access


Sequential access is used to work with files that are just plain text files. This is the file type that you will more than likely encounter the most in Visual Basic for Applications. As an example, if you wanted to read each line in an Autoexec.bat or Win.ini file you could use sequential access. With sequential access, each character in the file is assumed to represent either a text character or a text formatting sequence such as a tab or a new line character. Files such as CSV (comma separated), TXT (tab delimited) and PRN (space formatted) are all examples of files you would access sequentially. Advantages of Sequential Access: Files can be easily created or manipulated by text editors. Most applications can read/write files created with sequential access. It is easier to process in Visual Basic for Applications.

Disadvantages of Sequential Access: It is not well suited for storing large amounts of data because all values are stored as a character string. Usually requires more storage space than the other access types. You cannot read and write to a file that is opened for sequential access. You can only do one or the other at any given time.

Opening Files for Sequential Access


When you open a file for sequential access, you open it to perform one of the operations in the following table:

Operation Input Output Append

Description Input characters to the file. Output characters to the file. Append characters to the end of the file.

To open a file for any one of these operations use the Open statement: Open filename For [Input | Output | Append] As filenumber Len=buffersize When you use sequential access to open a file for Input, the file must already exist; otherwise Visual Basic for Applications generates a trappable error. When you try to open a nonexistent file for Output or for Append, the Open statement will actually create the file first and then open the empty file. Each time you open a file you must Close it before reopening the file for another type of operation.

Reading Files Opened for Sequential Access


To retrieve the contents of a text file, you first open the file for input, then use Line Input # or Input # to retrieve the contents of the file. Use Line Input # when you need to read a file one line at a time. With delimited files (such as tab or comma separated values), use Input # to read each line of the file into a list of variables.

Reading a File Line-by-Line


Use Line Input # with a file opened for sequential access if the data is stored in the file one line at a time. The Line Input # statement reads from a file one character at a time until it encounters a carriage return or carriage return-linefeed sequence. Carriage returns and carriage return-linefeed sequences are skipped rather than appended to the character string. Figure 1 is a text file you can use with the Line Input # statement to read from the file one line at a time. This is the first line of the file This is the second line of the file This is the third line of the file This is the fourth line of the file This is the last line of the file Figure 1: Sample Text File Textfile.txt Microsoft provides examples of Visual Basic for Applications procedures for illustration only, without warranty either expressed or implied, including, but not limited to the implied warranties of merchantability and/or fitness for a particular purpose. The Visual Basic procedures in this article are provided 'as is' and Microsoft does not guarantee that they can be used in all situations. While Microsoft Support Professionals can help explain the functionality of a particular macro, they will not modify these examples to provide added functionality, nor will they help you construct macros to meet your specific needs. If you have limited programming experience, you may want to consult one of the Microsoft Solution Providers. Solution Providers offer a wide range of fee-based services, including creating custom macros. For more information about Microsoft Solution Providers, call Microsoft Customer Information Service at (800) 426-9400. The following sample macro uses the Line Input # statement to read data from the sample text file in Figure 1: Sub ReadStraightTextFile() Dim LineofText As String 'Open the file for Input Open "C:\FILEIO\TEXTFILE.TXT" For Input As #1 'Read each line of the text file into a single string 'variable Do While Not EOF(1) Line Input #1, LineofText Debug.Print LineofText Loop 'Close the file Close #1 End Sub

Reading a Delimited Text File


Standard string or numeric data is assigned to variables as they appear in the text file. Delimiting commas or blank lines within the file are returned as Empty. Double quotation marks that surround each field in the input data are ignored and fields surround with "#"'s are interpreted as dates. When using Input #, data items in a file must appear in the same order as the variables in the variable list and they must be matched with variables of the same data type. If the data doesn't match the variable type you may encounter run-time errors. "Smith", "John", 22, "123 Main St.", "New York", "NY", 32432 "Doe", "Jane", 33, "324 Elm Ln.", "San Diego", "CA", 23542 "Adams", "Bill", 45, "4523 Oak Cir.", "Miami", "FL", 52343 "Jones", "Tom", 23, "235 Maple Dr.", "Houston", "TX", 23453 Figure 2: Sample Delimited Text File Delimit.txt This sample code below uses the Input # statement to read data from the sample text file in Figure 2 into variables. Sub ReadDelimitedTextFile() Dim LName As String, FName As String, Addr As String, City As String Dim state As String Dim age As Integer 'Open the file for Input Open "C:\FILEIO\DELIMIT.TXT" For Input As #1 'Read each line of the text file into the list of variables 'until the end of the file is reached Do While Not (EOF(1)) Input #1, LName, FName, age, Addr, City, state, zip Debug.Print LName, FName, age, Addr, City, state, zip Loop 'Close the file Close 1 End Sub

You might also like