我正在尝试将制表符分隔的文本文件提取到数组中,我已经知道如何将该文本文件读取到电子表格中,以下是我的代码,效果完美:
While Not EOF(iFile)
Line Input #iFile, LineText
Dim arr
arr = Split(CStr(LineText), vbTab)
For j = 1 To UBound(arr)
Worksheets("TxtRead").Cells(i, j).Value = arr(j - 1)
Next
i = i + 1
Wend
Close #iFile
因此,我不想将值提取到电子表格中,而是想将它们写入二维数组,我该怎么做?我有下面的代码,但它不起作用:
Dim MemoryArray()
While Not EOF(iFile)
Line Input #iFile, LineText
Dim arr
arr = Split(CStr(LineText), vbTab)
For j = 1 To UBound(arr)
Worksheets("TxtRead").Cells(i, j).Value = arr(j - 1)
MemoryArray(i - 1, j - 1) = arr(j - 1)
Next
i = i + 1
Wend
Close #iFile
感谢您的任何意见和想法!
最佳答案
Sub Tester()
Dim arr
arr = FileToArray("D:\Stuff\test.txt")
Debug.Print arr(1, 1), arr(10, 10) 'print some values
End Sub
Function FileToArray(fpath) As Variant
Dim txt As String, arr, d, r, c, rv(), u
'read in the entire file
With CreateObject("scripting.filesystemobject").opentextfile(fpath)
txt = .readall()
.Close
End With
arr = Split(txt, vbCrLf) 'split lines to an array
u = UBound(Split(arr(0), vbTab)) 'assume all lines have same # of fields
ReDim rv(1 To UBound(arr) + 1, 1 To u + 1) 'size the output array
'fill the output array
For r = 0 To UBound(arr)
d = Split(arr(r), vbTab)
For c = 0 To u
rv(r + 1, c + 1) = d(c)
Next c
Next r
FileToArray = rv
End Function
关于arrays - 如何在VBA中将文本文件读取到数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40228691/