如何在VBA中将文本文件提取到数组中 [英] How to fetch text file into array in VBA

查看:1073
本文介绍了如何在VBA中将文本文件提取到数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将制表符分隔的文本文件读取到数组中,我已经知道如何将文本文件读取到电子表格中,以下是我的代码,该代码可以很好地工作:

I'm trying to fetch the tab delimited text file into arrays, I already know how to read that text file into spreadsheet, the following is my code which works perfectly:

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

所以不要提取值到电子表格,我想将它们写入二维数组,我该怎么做?我下面有一个代码,但它不起作用:

So instead of fetching values to the spreadsheet, I would like to write them to a two-dimentional array, how would I do that? I have a code below, but it doesn't work:

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

谢谢您的任何投入和想法!

Thanks for any inputs and thoughts!

推荐答案

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

这篇关于如何在VBA中将文本文件提取到数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆