0

Such I have a text file that contain the below lines:

Line 1

Line2 etc

Line 3 etc

Now, I want to read the text file and include the all of line into an array like this:

LineList = Array("Line 1", "Line2 etc", "Line 3 etc")

How can I do this in ms word vba macro?

Thanks.

1 Answer 1

1

You can use a FileSystemObject to read line by line. Personally I'd use a Collection rather than an array so that I don't have to constantly use ReDim Preserve:

Sub S43490204()
    Dim filePath As String
    Dim fso
    Dim oCollection As New Collection

    filePath = "lines.txt"

    Set fso = CreateObject("Scripting.FileSystemObject")
    Set txtStream = fso.OpenTextFile(filePath, 1, False) '1 = ForReading

    On Error GoTo closeTarget

    Do While Not txtStream.AtEndOfStream
        oCollection.Add txtStream.ReadLine
    Loop

closeTarget:
    txtStream.Close

    'I'm not sure why you'd want an array instead of a collection
    Dim myArr() As String: myArr = GetStringArrayFromCollection(oCollection)

    For i = LBound(myArr) To UBound(myArr)
        Debug.Print " - " + myArr(i)
    Next i

End Sub

Function GetStringArrayFromCollection(oCollection As Collection) As String()
    Dim arr() As String
    Dim i As Integer

    ReDim arr(0 To oCollection.Count - 1)

    For i = 1 To oCollection.Count
        arr(i - 1) = oCollection(i)
    Next i

    GetStringArrayFromCollection = arr

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

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.