您的位置:首页 > 编程语言 > VB

VBA 读取文本文件

2016-05-05 23:41 375 查看
         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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  VBA 脚本 excel