VBA 读取文本文件

来源:互联网 发布:四川文化产业网络教学 编辑:程序博客网 时间:2024/05/07 02:49

         Excel在我们的日常办公中,用到非常多。因此,对于它的脚本VBA的使用,难免也比较频繁。在此总结、整理下之前写过的一段VBA读取MAP文件,统计ECU存储空间使用情况的部分代码。

该段程序,先使用Collection集合类装载读取的数据,最后统一写入将数据按照期望的格式,写入Excle表格中。这样一次性读取、写入,可以避免多次在读MAP文件和写Excel文件之间切换,增加系统资源开销。

    Open ThisWorkbook.Path & "\XXX.MAP" For Input As #1          lineNum = 0    FundStrtLineNum = 0    bFoundStart = False    '读取TXT文件    Do While Not EOF(1)        lineNum = lineNum + 1        Line Input #1, txt        If txt = "Memory map:" Then            FundStrtLineNum = lineNum            bFoundStart = True        End If        If bFoundStart Then            If lineNum >= (FundStrtLineNum + 3) And lineNum <= (FundStrtLineNum + 35) Then               txt = Trim(txt)               txt = reg.Replace(txt, " ")               tmpArray = Split(txt, " ")               'Collection集合类装载数组               collect.Add tmpArray            End If        End If    Loop    Close #1   
    'Write Data    Dim thissht As Worksheet    Set thissht = ThisWorkbook.Worksheets("MemMap")    Debug.Print "the current sheet index is:" & thissht.Index    thissht.Range("A:K").NumberFormatLocal = "@"    '阻止数字变成科学计数法        Dim loopi As Integer    Dim loopj As Integer    For loopi = 1 To collect.Count        For loopj = LBound(collect(loopi)) To UBound(collect(loopi)) 
             'LBound:得到数组的最小下标 UBound:返回最大下标            If loopj <> 1 Then                thissht.Range("D3").Offset(loopi - 1, loopj).Value = "'" & collect.Item(loopi)(loopj)            Else                thissht.Range("D3").Offset(loopi - 1, loopj).Value = collect.Item(loopi)(loopj)            End If        Next    Next



0 0
原创粉丝点击