Write to text file in VBA

2019-07-23 08:43发布

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

标签: excel vba
2条回答
家丑人穷心不美
2楼-- · 2019-07-23 09:14

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.

查看更多
家丑人穷心不美
3楼-- · 2019-07-23 09:18

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.

查看更多
登录 后发表回答