How to Read a file and add each line to an array of strings
Posted on January 5, 2009
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 | 'File/Folder Handling - How to Read a file and add each line to an array of strings Option Explicit Public Function ReadArrayFromFile(FilePath As String) As String() Dim strArray() As String Dim itemCount As Long, fileNum As Long On Error GoTo ReadArrayFromFile_Error itemCount = -1 fileNum = OpenFile(FilePath) If fileNum = -2 Then Exit Function End If Do While Not EOF(fileNum) itemCount = itemCount + 1 ReDim Preserve strArray(itemCount) Input #fileNum, strArray(itemCount) Loop Call CloseFile(fileNum) ReadArrayFromFile = strArray ExitHere: On Error GoTo 0 Exit Function ReadArrayFromFile_Error: MsgBox "Error " & Err.Number & " (" & Err.Description & ") in procedure ReadArrayFromFile of Form Form1" End Function Public Function OpenFile(ByVal FilePath As String) As Long On Error GoTo OpenFile_Error If Len(Dir$(FilePath)) = 0 Then OpenFile = -1 Exit Function End If OpenFile = FreeFile Open FilePath For Input As #OpenFile ExitHere: On Error GoTo 0 Exit Function OpenFile_Error: OpenFile = -2 MsgBox "Error " & Err.Number & " (" & Err.Description & ") in procedure OpenFile of Form Form1" End Function Public Function CloseFile(ByVal FileNumber As Long) As Boolean On Error GoTo CloseFile_Error Close #FileNumber CloseFile = True ExitHere: On Error GoTo 0 Exit Function CloseFile_Error: CloseFile = False MsgBox "Error " & Err.Number & " (" & Err.Description & ") in procedure CloseFile of Form Form1" End Function |
Related posts:
- How to write a string array to a text file
- How to Open a File and return the File Number
- How to Close a File for a given File Number
- How to Retrieve the File Name from a Path
- How to Retrieve the Filepath from a Path
- Read last line from a text file
- How to I create a text file from part of another text file (for given line numbers like Line No. 2 to 7)
- How to Create an Error Log file
- How to Read Line By Line & Retrieve Each Word From Text File
- How to Colour a Listview Item or SubItem