0
這樣我有包含以下行的文本文件:MS Word的VBA:包括文本文件中的行到一個數組
行1
線路2等
行3等
現在,我想讀取文本文件,並將所有行包括到如下所示的數組中:
LineList = Array(「Line 1」,「Line2 etc」,「Line 3 etc」)
如何在ms word vba宏中執行此操作?
謝謝。
這樣我有包含以下行的文本文件:MS Word的VBA:包括文本文件中的行到一個數組
行1
線路2等
行3等
現在,我想讀取文本文件,並將所有行包括到如下所示的數組中:
LineList = Array(「Line 1」,「Line2 etc」,「Line 3 etc」)
如何在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 –