0

I have problem with passing data from txt file to array. I have word document which needs to be filled with data from txt file.

Private Function ReadString() As String
Dim textArray() As String
Dim data As String
Open "C:\Data\XFile.ini" For Input As #1
    r = 0
    Do Until EOF(1)
    ReDim textArray(0 To r)
    Line Input #1, data
    textArray(r) = data
    r = r + 1
    Loop
    ReadString = textArray(77)
    ' MsgBox ReadString
    ' MsgBox "After"
    Close #1
End Function

I need data from line 78, but something is wrong in my code and data is not passed from file to array. If anybody can point out problem I would be very thankful.

1 Answer 1

3

You need to use ReDim Preserve to preserve the data in the array when you ReDim it. Otherwise, the array will be erased.

Private Function ReadString() As String
    Dim data As String, textArray() As String
    Dim n As Long
    ReDim textArray(0)
    Open "C:\Data\XFile.ini" For Input As #1

    Do Until EOF(1)
        ReDim Preserve textArray(count)
        n = n + 1
        Line Input #1, data
        textArray(n) = data
        r = r + 1
    Loop
    Close #1
    ReadString = textArray(77)
End Function

You could also use an ArrayList to store your data.

Private Function ReadString2() As String
    Dim data As String
    Dim list As Object
    Set list = CreateObject("System.Collections.ArrayList")

    Open "C:\Data\XFile.ini" For Input As #1
    Do Until EOF(1)
        ReDim Preserve textArray(count)
        Line Input #1, data
        list.Add data
    Loop
    Close #1
    ReadString = list(77)
End Function

To extract the whole array use textArray = list.ToArray.

Sign up to request clarification or add additional context in comments.

1 Comment

@YowE3K thanks again. I forgot that textArray was 0 based.

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.