Curious Minds

Clear answers to science and history questions

Import Text File VBA: Read Text Files in Excel

· 6 min read · Science

To import a text file in VBA, use the OpenTextFile method of the FileSystemObject (late-bound via CreateObject("Scripting.FileSystemObject")) or the native Open statement with Line Input. Both approaches let you read a text file line by line or in one go, then place the content into cells, variables, or process it further. The FileSystemObject method is generally easier for beginners because it handles file paths and encoding more gracefully, while the native Open statement is faster for very large files and requires no external references.

Background: Why VBA Needs Text File Import

Excel workbooks often need to ingest data from external sources such as CSV exports, log files, fixed-width reports, or plain-text configuration files. While Excel's built-in Power Query and Data Import wizards handle many cases, VBA gives you programmatic control: you can loop through hundreds of files, apply custom parsing rules, or integrate file reading into a larger automation workflow. The two main VBA mechanisms are the legacy Open statement (part of the VBA language itself) and the FileSystemObject (part of the Microsoft Scripting Runtime library, accessible via late binding without adding a reference).

A common misconception is that VBA can only read files with a .txt extension. In reality, the Open statement and FileSystemObject read any file as text if you specify text mode; the extension is irrelevant. Another misconception is that reading a file requires a reference to the Scripting Runtime. Late binding (CreateObject) avoids that reference entirely, making the code portable across machines.

How It Works: Two Core Methods

Method 1: FileSystemObject (late-bound)

  1. Create the object: Set fso = CreateObject("Scripting.FileSystemObject")
  2. Open the file for reading: Set ts = fso.OpenTextFile("C:\data\input.txt", 1, False) (1 = ForReading, False = don't create if missing)
  3. Read line by line: Do Until ts.AtEndOfStream : line = ts.ReadLine : Loop
  4. Close the file: ts.Close

Method 2: Native Open statement

  1. Get a free file number: fnum = FreeFile
  2. Open the file: Open "C:\data\input.txt" For Input As #fnum
  3. Read line by line: Do Until EOF(fnum) : Line Input #fnum, line : Loop
  4. Close: Close #fnum

Both methods read text sequentially. The FileSystemObject offers additional properties like AtEndOfStream and methods like ReadAll (reads entire file into one string). The native method is slightly faster for large files because it avoids COM overhead, but it lacks built-in encoding detection.

How to Choose Between the Methods

  • Use FileSystemObject when you want simpler syntax, need to check file existence (fso.FileExists), or want to read the whole file at once with ReadAll.
  • Use native Open when performance matters for very large files (hundreds of megabytes), when you want to avoid any external library dependency, or when you need to read binary data (using Get instead of Line Input).
  • Encoding matters: The native Open statement reads ANSI text by default; it does not handle UTF-8 or Unicode well without workarounds. FileSystemObject's OpenTextFile has a Format parameter (TristateTrue for Unicode, TristateFalse for ASCII, TristateUseDefault for system default) but does not natively support UTF-8 without the ADODB.Stream alternative.

For UTF-8 files, a common workaround is using ADODB.Stream with Charset = "utf-8", or reading the file as binary and decoding manually. This is a known limitation of both core methods.

Common Problems and Fixes

  • File not found error (53): Verify the path with Dir() or fso.FileExists before opening. Remember that relative paths resolve against the current directory, which may not be the workbook's folder. Use ThisWorkbook.Path to build absolute paths.
  • Permission denied (70): The file may be open in another program or marked read-only. Check file attributes.
  • Garbled characters: Encoding mismatch. If the file is UTF-8 but read as ANSI, accented characters appear as mojibake. Use ADODB.Stream or convert the file to ANSI first.
  • Trailing empty lines: Line Input stops at end-of-file, but some files end with a blank line that produces an empty string. Filter with If Len(line) > 0 Then if needed.
  • Very long lines: The native Line Input statement can handle lines up to about 2,047 characters; longer lines are truncated. FileSystemObject's ReadLine has no such hard limit but may be slower.
  • File locked by Excel itself: If you are reading a file that Excel has open, close it first or use a copy.

Step-by-Step Example: Import a CSV into a Worksheet

Suppose you have a file C:\data\sales.csv with comma-separated values and want to place each row into column A, splitting on commas. The following outline uses FileSystemObject:

  1. Set fso = CreateObject("Scripting.FileSystemObject").
  2. Set ts = fso.OpenTextFile("C:\data\sales.csv", 1).
  3. Set row = 1.
  4. Loop while Not ts.AtEndOfStream: read line = ts.ReadLine, split with parts = Split(line, ","), then write each part to Cells(row, col).
  5. Increment row.
  6. After the loop, ts.Close and release objects with Set ts = Nothing : Set fso = Nothing.

This pattern handles quoted fields poorly (a comma inside quotes will split incorrectly). For robust CSV parsing, use Split with a custom parser or import via Workbooks.OpenText, which respects quoting and delimiters.

Alternatives to Manual VBA Parsing

  • Workbooks.OpenText: Opens a text file directly as a workbook with delimiter and column formatting options. Useful when you want Excel's native parsing.
  • QueryTables.Add: Creates a query table from a text file, supporting refresh and external data ranges.
  • Power Query (Get & Transform): Available in modern Excel; can be automated via VBA but is primarily a UI-driven tool. Handles encoding, delimiters, and data types more robustly than manual VBA.
  • ADODB.Stream: Best for UTF-8 and Unicode files; reads entire file into a string with correct encoding.

Each alternative has trade-offs: OpenText is simple but creates a new workbook; QueryTables integrate with the worksheet but can be slow for large files; Power Query is powerful but less scriptable for fine-grained control.

Safety and Best Practices

  • Always close files in your code, even if an error occurs. Use On Error GoTo Cleanup and a cleanup label that closes the file number or object.
  • Validate file paths and existence before opening to avoid runtime errors.
  • Do not hard-code paths; use ThisWorkbook.Path or Environ("USERPROFILE") for portability.
  • When reading untrusted files, be aware that VBA text reading does not execute macros, but the content may contain formulas or injection strings. Sanitize before writing to cells if the file is external.
  • For large files, read in chunks or use the native Open statement to reduce memory overhead.

Frequently Asked Questions

Can VBA read a text file without opening it in Excel?

Yes. Both the Open statement and FileSystemObject read the file directly from disk; the file does not need to be open in Excel or any other application.

How do I read a UTF-8 text file in VBA?

The native Open statement and FileSystemObject do not natively support UTF-8. Use ADODB.Stream with Charset = "utf-8", or read the file as binary and decode manually. Alternatively, convert the file to ANSI or Unicode (UTF-16) before reading.

What is the difference between Line Input and ReadLine?

Line Input is a VBA statement that reads one line from a file opened with the Open statement. ReadLine is a method of the FileSystemObject's TextStream object. Both read a line of text, but they belong to different file-access models.

Why does my VBA code stop reading at a blank line?

It should not. Both Line Input and ReadLine return an empty string for a blank line and continue. If your loop stops, check that you are testing EOF or AtEndOfStream correctly, and that you are not using Input # (which behaves differently for delimited data).

Can I import a text file into a specific worksheet range?

Yes. After reading each line, write it to a cell using Worksheets("Sheet1").Cells(row, col).Value = line. For delimited data, split the line first and write each field to consecutive columns.

Is there a limit to the file size VBA can read?

VBA can read very large files, but memory and performance degrade. The native Open statement is more memory-efficient for line-by-line processing. Reading a multi-gigabyte file into a single string with ReadAll may exhaust available memory.

In this article
  1. Background: Why VBA Needs Text File Import
  2. How It Works: Two Core Methods
  3. How to Choose Between the Methods
  4. Common Problems and Fixes
  5. Step-by-Step Example: Import a CSV into a Worksheet
  6. Alternatives to Manual VBA Parsing
  7. Safety and Best Practices
  8. Frequently Asked Questions