2017-04-19 50 views
0

这样我有包含以下行的文本文件:MS Word的VBA:包括文本文件中的行到一个数组

行1

线路2等

行3等

现在,我想读取文本文件,并将所有行包括到如下所示的数组中:

LineList = Array(“Line 1”,“Line2 etc”,“Line 3 etc”)

如何在ms word vba宏中执行此操作?

谢谢。

回答

1

您可以使用FileSystemObject逐行读取。我个人会使用一个集合而不是阵列,这样我就不必经常使用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 
+0

谢谢Jbjstam –

相关问题