Version Compatibility: Visual Basic 5, Visual Basic 6
More information: A reference to the Microsoft Scripting Runtime is required. Refer to code's comments for usage and other details.
Instructions: Copy the declarations and code below and paste directly into your VB project.
Public Sub FileToArray(ByVal FileName As String, _
ByRef TheArray As Variant)
'PURPOSE: Puts all lines of file into a string array
'PARAMETERS: FileName = FullPath of File
' TheArray = StringArray to which contents
' Of File will be added.
'Example
' Dim sArray() as String
' FileToArray "C:\MyTextFile.txt", sArray
' For lCtr = 0 to Ubound(sArray)
' Debug.Print sArray(lCtr)
' Next
'NOTES:
' -- Requires a reference to Microsoft Scripting Runtime
' Library
' -- You can write this method in a number of different ways
' For instance, you can take advantage of VB 6's ability to
' return an array.
' -- You can also read all the contents of the file and use the
' Split function with vbCrlf as the delimiter, but I
' wanted to illustrate use of the ReadLine
' and AtEndOfStream methods.
'**********************************************************
Dim oFSO As New FileSystemObject
Dim oFSTR As Scripting.TextStream
Dim ret As Long
Dim lCtr As Long
If Dir(FileName) = "" Then Exit Sub
'Check if string array was passed
'If you want to permit other type of arrays (e.g.,
'variant) remove or modify this line
If VarType(TheArray) <> vbArray + vbString Then Exit Sub
On Error GoTo ErrorHandler
Set oFSTR = oFSO.OpenTextFile(FileName)
Do While Not oFSTR.AtEndOfStream
ReDim Preserve TheArray(lCtr) As String
TheArray(lCtr) = oFSTR.ReadLine
lCtr = lCtr + 1
DoEvents 'optional but with large file
'program will appear to hang
'without it
Loop
oFSTR.Close
ErrorHandler:
Set oFSTR = Nothing
End Sub
0 comments:
Post a Comment