1

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

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Excellent. Yes I had not tested the actual Print statement (I used Debug.Print to put it in the console, so I wasn't sure if ReadAll would work although I figured it probably would. Cheers!
1

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.

1 Comment

+1 for a neat trick :) but I don't think it answers the question (poor choice of words on OP's part, no worries!)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.