Writing the text content into the file using Visual Basic (VBA)

Edit ArticleEdit Article

This code snippet demonstrates how to write text into the specified file using Visual Basic (VBA). Function has an option to overwrite existing content or append it.

The below snippet will overwrite the data in the destination text file

WriteText("C:\MyFolder\MyFile.txt", "Text Data", False)

While this snippet will append the data

WriteText("C:\MyFolder\MyFile.txt", "Text Data", True)

Code will automatically create new file if it doesn't exist.

Exception will be thrown in case of any error (for example file cannot be accessed for writing).

Sub WriteText(filePath As String, content As String, append As Boolean)
    
    Dim fileNo As Integer
    fileNo = FreeFile
    
    If append Then
        Open filePath For Append As #fileNo
    Else
        Open filePath For Output As #fileNo
    End If
    
    Print #fileNo, content
    
    Close #fileNo
    
End Sub

Product of Xarial Product of Xarial