How to use Print # statement in VBA?

The Print # statement in VBA (Visual Basic for Applications) is used to write data to a sequential file. It enables you to output text, numbers, or other data types to a file, which can be useful for creating logs, exporting data, or writing information to text files. The Print # statement is used in conjunction with file handling statements like Open and Close.

Here’s how to use the Print # statement

Open a File for Output

Before using Print #, you must open a file for output using the Open statement. You must also assign a file number to the file.

Syntax of Print #

VBA
Print #fileNumber, [outputList]
  • fileNumber: This is a unique number that you assign to the file when you open it. It’s used to refer to the file in all subsequent file handling operations.
  • outputList: This is a list of expressions to be written to the file. You can include strings, numbers, variables, or any other expressions. Items in the output list are separated by commas or semicolons.

Write to the File

Use Print # to write data to the file. You can format the output using commas, semicolons, and various formatting functions.

Close the File

After writing to the file, use the Close statement to close the file. This ensures that the data is properly saved and the file is released by the application.

Example

Here’s a simple example of writing text to a file:
VBA
Dim fileNumber As Integer
fileNumber = FreeFile()  ' Get a free file number

' Open a text file for output
Open "C:example.txt" For Output As #fileNumber

' Write some data to the file
Print #fileNumber, "Hello, World!"  ' Writes the text with a newline at the end
Print #fileNumber, "This is line 2"; " and some extra text."  ' Concatenates the strings

' Close the file
Close #fileNumber

Commas and Semicolons in Print #

  • Using a comma (,) in the outputList will tabulate the output, aligning it to predefined print zones.
  • Using a semicolon (;) will write the data continuously without automatically moving to a new line.

Error Handling

It’s good practice to include error handling in your code to manage any issues that might occur during file operations, such as file not found errors or access violations. The Print # statement is a convenient way to write data to text files in a controlled and formatted manner. It’s particularly useful for creating simple text-based logs or exporting data in a text format.

Unlock Your Potential

Excel

Basic - Advanced

Access

Access Basic - Advanced

Power BI

Power BI Basic - Advanced

Help us grow the project