What is the syntax to write text files using FSO?

Why use FSO over Write Command method? FSO allows coders to work with drives, folders, files.

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

Dim FilePath, CellData As String
Dim LastCol, LastRow As Long
Dim fso As FileSystemObject

Set fso = New FileSystemObject
Dim stream As TextStream

LastCol = ActiveSheet.UsedRange.Columns.Count
LastRow = ActiveSheet.UsedRange.Rows.Count

'create a textstream
Set stream = fso.OpenTextFile("<file path of txt file>\<txt file name>.txt”, ForWriting, True)
CellData = ""
For i = 1 To LastRow
    For j = 1 To LastCol
        CellData = ActiveCell(i, j).Value
        stream.WriteLine ("Location: " & i & ", " & j & "-->" & CellData)
    Next j
Next i





Published by