Home » excel » excel – Write to text file in VBA

excel – Write to text file in VBA

Posted by: admin May 14, 2020 Leave a comment

Questions:

I am trying to print a file after opening it to a file I create with the VBA. The part I am stuck at is writing to the file. Here is what I have so far.

Sub test()
Dim myFile As String
Dim testFile As String
Dim intChoice As Integer
Dim fs, f

myFile = Application.GetSaveAsFilename & "kml"

Open myFile For Output As #1

Application.FileDialog(msoFileDialogOpen).AllowMultiSelect = False
intChoice = Application.FileDialog(msoFileDialogOpen).Show
If intChoice <> 0 Then
    testFile = Application.FileDialog( _
        msoFileDialogOpen).SelectedItems(1)
End If


Set fs = CreateObject("Scripting.FileSystemObject")
Set f = fs.OpenTextFile(testFile)

Print #1, f

Close #1

End Sub
How to&Answers:

Read the textstream line-by-line and print as needed. Do this in a loop.

Set fs = CreateObject("Scripting.FileSystemObject")
Set f = fs.OpenTextFile(testFile)

Do While Not f.AtEndOfStream
    Print #1, f.ReadLine
Loop

Set f = Nothing
Set fs = Nothing

Or, you may be able to omit the loop and simply do Print #1, f.ReadAll.

Answer:

The simplest way to print a text file (in Windows) is to send it to Notepad with the “/p” switch. This will send it to the default printer.

Shell "Notepad /p C:\Users\Andrew\Documents\test.txt"

It appears that you are running this code from Excel. In which case you could also open the text-file in Excel and print it from there.