0

I have a .dat file that just holds a list of names, each name is on a new line. How would I go about getting those names out of the file and putting them into a array?

3 Answers 3

1

you should read this
http://www.visualbasic.happycodings.com/Files_Directories_Drives/code54.html

Excerpt

Function FileLoadToArray(ByRef asLines() As String, ByVal sFileName As String) As String
    Dim iFileNum As Long, lFileLen As Long
    Dim sBuffer As String

    'Initialise Variables
    On Error GoTo ErrFailed

    'Open File
    iFileNum = FreeFile
    Open sFileName For Binary Access Read As #iFileNum
    'Get the size of the file
    lFileLen = LOF(iFileNum)
    If lFileLen Then
        'Create output buffer
        sBuffer = String(lFileLen, " ")
        'Read contents of file
        Get iFileNum, 1, sBuffer
        'Split the file contents
        asLines = Split(sBuffer, vbNewLine)
    End If

    Close #iFileNum
    'Return success
    FileLoadToArray = ""

    Exit Function

ErrFailed:
    Debug.Assert False
    Debug.Print Err.Description
    FileLoadToArray = Err.Description
    'Close file
    If iFileNum Then
        Close #iFileNum
    End If
End Function
Sign up to request clarification or add additional context in comments.

2 Comments

Reasonable answer apart from the method used to read a text file into a string. It has some problems - why not use the 3-line technique from the VB6 manual instead? More here stackoverflow.com/questions/1199143/…
It can fail if the file is to big. 150 Megs for example. In this case its better to do it line by line.
1

My VB6 is a bit rusty but I would think it was something like this, thanks to Google! :P

DIM FileNo AS Integer
DIM strNameList() AS STRING

FileNo = FreeFile
Open "file.dat" For Input As FileNo
Do Until EOF(FileNo)
   Line Input FileNo, strNameList(UBound(strNameList))
   REDIM Preserve strNameList(UBound(strNameList) + 1)
Loop
Close FileNo

Now strNameList will have the array of entries from the file...Phew...I hope this is correct despite my rustic skills....

1 Comment

You must add required # to Line - Line Input #FileNo
0

You can use a generic read-all-file function

Private Function ReadFile(sFile As String) As String
    Dim nFile       As Integer

    nFile = FreeFile
    Open sFile For Input Access Read As #nFile
    ReadFile = Input$(LOF(nFile), nFile)
    Close #nFile
End Function

with Split function like this

    Dim vSplit As Variant
    vSplit = Split(ReadFile("your_file.txt"), vbCrLf)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.