2017-04-19 4 views
0

Solche Ich habe eine Textdatei, die die folgenden Zeilen enthalten:MS Word VBA: Textdatei Zeile in einem Array enthalten

Linie 1

Netz2 etc

Zeile 3 usw.

Jetzt Ich möchte die Textdatei lesen und die gesamte Zeile in ein Array wie das folgende einfügen:

LineList = Array ("Zeile 1", "Zeile2 usw.", "Zeile 3 usw.")

Wie kann ich das in ms Word Vba Makro tun?

Danke.

Antwort

1

Sie können ein FileSystemObject verwenden, um zeilenweise zu lesen. Persönlich würde ich eine Sammlung anstelle eines Arrays verwenden, so dass ich ReDim Preserve nicht ständig verwenden muss:

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 
+0

Vielen Dank Jbjstam –

Verwandte Themen