Output to a file - known amount of data

Keywords: 
Situation: 

Your program needs to output data. You know exactly how many elements, and what type each one is.

Actions: 

Use the File open, process, close pattern to open and close the file. Processing uses the Write or Print statements.

Explanation: 

Use the File open, process, close pattern to open and close the file. Processing might be like this:

Dim tip As Single
Dim total as Single
...
'Open file
Open ThisWorkbook.Path & "\tip.csv" For Output As #1
'Output
Write #1, tip, total
'Close file
Close #1

Write writes out data in CSV (comma separated values) format. For example:

6,46

If you want to make a report to be read by a human, use the Print statement, and add labels:

Dim tip As Single
Dim total as Single
...
'Open file
Open ThisWorkbook.Path & "\tip.txt" For Output As #1
'Output
Print #1, "Tip: " & tip & vbCrLf
Print #1, "Total: " & total & vbCrLf
Close #1

vbCrLf is a predefined VBA string constant what will add a carriage return. Like pressing the Enter key in an editor.

If you want to make a Web page, add HTML to your labels:

Dim tip As Single
Dim total as Single
'Open file
...
'Output
Open ThisWorkbook.Path & "\tip.html" For Output As #1
Print #1, "<p>Tip: " & tip & "</p>" & vbCrLf
Print #1, "<p>Total: " & total & "</p>" & vbCrLf
Close #1

The vbCrLfs will have no visible effect when the page is viewed in a browser. However, they will make the HTML easier to understand for anyone wanting to make changes in the future.

To output bold text, try:

Print #1, "<p><strong>Total</strong>: " & total & "</p>" & vbCrLf
 
Referenced in: