What is the syntax to write text files using Write Command?

Why use Write Command method instead of FSO?
Write command does not require user to add any references. However, it does not work with drives, files, folders.

Note: Please enable Microsoft Scripting Runtime before running this code (click here for article)

Dim FilePath As String
Dim CellData As String
Dim LastCol As Long
Dim LastRow As Long

LastCol = <last column you want to write>
LastRow = <last row you want to write>

FilePath = "<file path of txt file>\<txt file name>.txt"
Open FilePath For Output As #2
CellData = ""

For i = 1 To LastRow
    For j = 1 To LastCol
        CellData = <whatever you want to write> 'commonly Cells(i, j).Value
        Write #2, CellData
    Next j
Next i

Close #2

MsgBox ("Writing Complete")

 

Advertisements