Tuesday, November 13, 2012

Creating A Text File With Vba

Sub WriteTextFile()
     ' Writing a text file using File System Object in VBA
     ' This code requires a reference (In the VBE Tools > References) to Microsoft Scripting Runtime
    
    Dim FSO As FileSystemObject
    Dim FSOFile As TextStream
    Dim FilePath As String
    Dim NoOfLoop As Integer
    
    FilePath = "c:\Vilas.txt" ' create a test.txt file or change this
    
    Set FSO = New FileSystemObject
     ' opens  file in write mode
    Set FSOFile = FSO.OpenTextFile(FilePath, 2, True)
     'loop round adding lines
    For NoOfLoop = 1 To 10
         ' write your code here
        FSOFile.WriteLine ("How are you " & NoOfLoop)
    Next NoOfLoop
    
    FSOFile.Close
End Sub

No comments: