Read and Write Files

There are a number of different ways to read and write files in Visual Basic, and which you choose depends on what you are trying to do, as described in Table 3-13.

Table 3-13. File-access techniques in Excel Visual Basic

Technique

Use to

Look here

Intrinsic functions

Read or write simple datafiles

This section

FileSystemObject

Create files, folders, and control file attributes

Chapter 6

Workbooks, Workbook objects

Create, open, and save Excel workbook files; import datafiles into workbooks

Chapter 8

XMLMap object

Import or export XML datafiles from a workbook

Chapter 15

In short, you shouldn’t assume the Visual Basic intrinsic functions are the best way to read and write files in all situations. Actually, I prefer the FileSystemObject for most general file-access tasks, but it’s important to be thorough, so I’ll cover the intrinsic file-access functions here (Table 3-14).

Table 3-14. Visual Basic’s intrinsic file-access functions

Category

Function

Use to

Access

Close

Close an open file

 

FileCopy

Copy a file

 

FreeFile

Get a file number for Open

 

Lock...Unlock

Prevent others from accessing all or part of a file

 

LOF

Get the length of an open file in bytes

 

Open

Open a file

 

Reset

Close all open files

Attributes

FileAttr

Get the attributes of an open file

 

FileDateTime

Get the date that a file was created or changed

 

FileLen

Get the length of a file ...

Get Programming Excel with VBA and .NET 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.