Home Excel Powerpoint Word Outlook Error Codes

VBA Useful Codes

Welcome to the World of VBA
Home > VBAUsefulCodes

Read entire data from text file (.txt)

This following Code Reads data from a single text file. This function checks whether file exists. It reads data only if file exists.

Sub Read_File()
Debug.Print ReadTextFile("abc.txt")
End Sub

'Reads a text file and returns the text as string
'i_FileName contains full name (i.e. with path) of the file to be read
Public Function ReadTextFile(ByVal i_FileName As String) As String
  Dim myFNo As Integer  'file number to open file
  Dim myText As String  'string where text gets read into

  'only open file if it Exists
  If Dir(i_FileName, vbNormal) <> "" Then
    'obtain the next available file number
    myFNo = FreeFile
    'open file in binary mode
    Open i_FileName For Binary As #myFNo
    'initialize string to receive text with
    'as many spaces as the file has bytes
    myText = Space(LOF(myFNo))
    'read everything at once
    Get #myFNo, , myText
    'close file
    Close #myFNo
    'return text
    ReadTextFile = myText
  End If
End Function


Enter your e-mail below and get notified on the latest blog posts.


VBA Outlook KPI Excel Alt+F11 Dashboards Macros Recording Graphs Automation Developer WaterFall Powerpoint Charts Pivot Tables Forecast Charts

Follow Us