How to use Width # statement in VBA?

In VBA (Visual Basic for Applications), the Width # statement is used to set the output line width for writing text to a file. It’s particularly relevant when you are using the Print # statement to write data to a text file and you want to control the width of each line in the file.

Here’s how you can use the Width # statement:

Basic Syntax

Width #filenumber, width
  • filenumber: This is the file number used in the Open statement for the file.
  • width: This is the width of the lines in characters.

Example Usage

Suppose you have opened a file for output with a file number of 1. You want each line in this file to be 50 characters wide. Here’s how you might do it:

Open "C:\MyFile.txt" For Output As #1
Width #1, 50
Print #1, "This is a test."
Close #1

In this example, the line in “MyFile.txt” will be 50 characters wide. The text “This is a test.” will be followed by enough spaces to make the total line length 50 characters.

Details to Consider

If the width is set to a value less than the length of the string being printed, Print # will split the string across multiple lines.

The Width # setting remains in effect for the specified file until it is closed or until another Width # statement is executed for the same file.

Default Width

If you don’t specify Width # for a file, VBA uses a default width of 80 characters.

Use in Writing Data to Files

The Width # statement is especially useful when you need to create fixed-width text files, where each line of text needs to be a specific number of characters.

Error Handling

Always include error handling when dealing with file operations. Make sure the file is successfully opened before using Width #.

Width # is a tool that gives you more control over how data is formatted in text files, making it useful in situations where you need to adhere to specific data formatting requirements, such as generating reports or interfacing with systems that require fixed-width file formats.

Unlock Your Potential


Basic - Advanced


Access Basic - Advanced

Power BI

Power BI Basic - Advanced

Help us grow the project

Leave a Reply

Your email address will not be published. Required fields are marked *