Reading the content of text file using Visual Basic (VBA)

Edit ArticleEdit Article
Comments

The below code snippet demonstrates how to read the text content from the specified file.

Dim content As String
content = ReadText("C:\MyFolder\MyFile.txt")

Code will generate an exception if file doesn't exist or cannot be read.

Function ReadText(filePath As String) As String
    
    Dim fileNo As Integer

    fileNo = FreeFile
    
    Dim content As String
    
    Dim isFirstLine As Integer
    isFirstLine = True
    
    Open filePath For Input As #fileNo
    
    Do While Not EOF(fileNo)
        
        Dim line As String
        
        Line Input #fileNo, line
        
        content = content & IIf(Not isFirstLine, vbLf, "") & line
        isFirstLine = False
        
    Loop
    
    Close #fileNo
    
    ReadText = content
    
End Function

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