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.