Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/vba/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ms word VBA:将文本文件行包含到数组中_Vba_Ms Word - Fatal编程技术网

Ms word VBA:将文本文件行包含到数组中

Ms word VBA:将文本文件行包含到数组中,vba,ms-word,Vba,Ms Word,我有一个包含以下行的文本文件: 第1行 线路2等 第3行等 现在,我想读取文本文件并将all of行包含到如下数组中: LineList=数组(“第1行”、“第2行等”、“第3行等”) 如何在ms word vba宏中执行此操作 谢谢。您可以使用FileSystemObject逐行读取。就个人而言,我会使用集合而不是数组,这样我就不必经常使用ReDim Preserve: Sub S43490204() Dim filePath As String Dim fso Dim

我有一个包含以下行的文本文件:

第1行

线路2等

第3行等

现在,我想读取文本文件并将all of行包含到如下数组中:

LineList=数组(“第1行”、“第2行等”、“第3行等”)

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


谢谢。

您可以使用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

谢谢你,Jbjstam