Creating and writing to a file
print#
writes a line to a file. Unlike
write#
, it does not enclose
strings in apostrophes.
By default,
print#
adds a
line break after the text that was written.
The following example creates a file (
open
) and writes three lines into it with
write#
. After finishing writing to the file, the file is closed with
close
.
option explicit
sub main() ' {
dim fileName as string
fileName = environ$("temp") & "\VBA-print-test.txt"
dim f as integer
f = freeFile()
open fileName for output as #f
print# f, "Line one"
print# f, "Line two"
print# f, "Line three"
close f
debug.print("Check " & fileName)
end sub ' }
Omitting new line at line's end
In order to omit the line break, the print statement needs to be ended with a semicolon:
option explicit
sub main() ' {
dim fileName as string
fileName = environ$("temp") & "\without-newlines.txt"
dim f as integer
f = freeFile()
open fileName for output as #f
print# f, "first line: " ;
print# f, "one " ;
print# f, "two " ;
print# f, "three" ' Note: no semicolon to add new line
print# f, "second line: " ;
print# f, "foo " ;
print# f, "bar " ;
print# f, "baz" ' write another new line
close f
debug.print("Check " & fileName)
end sub ' }