arrays - 如何在VBA中将文本文件读取到数组中

标签 arrays vba

我正在尝试将制表符分隔的文本文件提取到数组中,我已经知道如何将该文本文件读取到电子表格中,以下是我的代码,效果完美:

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/

相关文章:

arrays - 具有复杂步长的 numpy 数组切片是什么意思?

excel - 为什么使用IsEmpty()方法时使用Len()方法长度为0的单元格等于False?

excel - 我无法获得目标搜索例程的正确语法

excel - 制作输入框,以便用户可以输入他/她的名字并在每个消息框中使用

javascript - 在 JavaScript 中动画结束后跟踪并显示数组元素的到达顺序

iphone - 如何从 NSMutableArray (iPhone) 获取第一个值?

无法将 char 分配给 char 指针

excel - 使用 VBA 将附件插入 XML 标记

sql - ADO 记录集数据未显示在表单上

java - 数组列表到对象[][]