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

Edit ArticleEdit Article

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

Join session by SOLIDWORKS and PDM API expret Artem Taturevych at 3DEXPERIENCE World 2025 on Feb 26 at 08:30 AM CST to explore 10 essential macros for automating drawings, assemblies, custom properties, and more


Product of Xarial Product of Xarial