Advertisement

VBA 读取文本文件

阅读量:

广泛应用于我们的日常办公场景中。由于其脚本语言VBA的应用频率较高,在此汇总并优化之前编写的一段用于读取MAP文件并统计ECU存储空间使用情况的代码。

这段程序流程中会经历一系列操作步骤:首先会获取并加载处理的数据,并将其整合后输出到指定格式结构中以完成一次完整的数据处理流程。通过这种一次性读取与整合的方式能够减少在读取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   
    
    
    
    
    AI写代码
复制代码
     '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)) 
    
    
    
    
    AI写代码
复制代码
          '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
    
    
    
    
    AI写代码

全部评论 (0)

还没有任何评论哟~