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

Edit ArticleEdit Article
Comments

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

Notifications

All articles and code at CodeStack are now open-source and hosted on GitHub. If you want to contribute by modifying existing articles and code snippets, submitting new ones, reporting errors and bugs etc. please follow this blog post for more information. We appreciate any contribution.


Product of Xarial Product of Xarial