In VBA (Visual Basic for Applications), the Write # statement is used for writing data to a sequential file with each value separated by a comma and enclosed in quotes if it’s a string. This is particularly useful for creating CSV (Comma-Separated Values) files or other text files where data needs to be easily parsed.
Here’s how you can use the Write # statement:
Difference Between
Write # inserts delimiters (commas) and encloses strings in quotes automatically. It’s ideal for creating CSV files.
Print # writes data in a more free-form manner, without adding delimiters or quotes unless you explicitly include them.
Basic Syntax
VB
Write #filenumber, [outputlist]
- filenumber: This is the file number used in the Open statement.
- outputlist: This is an optional list of expressions to be written to the file. The expressions in the list can be numeric, string, or date expressions.
Example Usage
Suppose you want to write some data to a CSV file:VB
This code will create a file named Example.csv with three lines of data. The data fields are separated by commas, and string values are enclosed in quotes.
Dim fName As String
fName = "C:Example.csv"
' Open the file for output
Open fName For Output As #1
' Write data to the file
Write #1, "Name", "Age", "City"
Write #1, "Alice", 30, "New York"
Write #1, "Bob", 25, "Los Angeles"
' Close the file
Close #1