5.5.3-代码解析:sub_TXT文件解析¶
本示例的输入文本文件含有的内容,比较规范,如图5-2所示。我们只需要一行一行解读,将每一行内容写入数据库中。另外将解读后的文本文件备份即可(实际操作:复制文件到指定位置,删除原文件)。
代码如下
1 Sub sub_TXT文件解析(inputAddress, eachFileName, backupAddress)
2 Application.DisplayAlerts = False
3
4 fileAddress = inputAddress & "\" & eachFileName
5 Set fso = CreateObject("Scripting.FileSystemObject")
6
7 ' 数据库文件
8 currentPath = ThisWorkbook.Path
9 dbExcel = currentPath & "\数据库.xlsx"
10 Set wb = Workbooks.Open(dbExcel)
11 Set shtDB = wb.Worksheets(1)
12 rngPoint = shtDB.Range("A:A")
13 inputCol = shtDB.Cells(1, Columns.Count).End(xlToLeft).Column + 1
14
15 ' 解读文本文件
16 Const ForReading = 1
17 Set strNewFileOpen = fso.openTextFile(fileAddress, ForReading, tristateTrue)
18
19 shtDB.Cells(1, inputCol) = Split(eachFileName, ".")(0)
20
21 Do While Not strNewFileOpen.AtEndOfStream
22 rowContent = strNewFileOpen.ReadLine
23 If rowContent <> "" Then
24 pointName = Split(rowContent, ",")(0)
25 devValue = Split(rowContent, ",")(3)
26 inputRow = Application.Match(pointName, rngPoint, 0)
27 shtDB.Cells(inputRow, inputCol) = devValue
28 End If
29
30 Loop
31
32 strNewFileOpen.Close
33
34 wb.Save
35 wb.Close
36
37 ' 备份文件
38 backupFileAddress = backupAddress & "\" & eachFileName
39 FileCopy fileAddress, backupFileAddress
40 Kill fileAddress
41 End Sub
关键代码解读
1)第2行: Application.DisplayAlerts = False。关闭报警信息
2)第13行:shtDB.Cells(1, Columns.Count).End(xlToLeft).Column。获取当前数据库的第1行已写入数据的最大列,这是为了继续向数据库中写入数据,确定拟写入的列数,如同5-18所示
3)第17行:Set strNewFileOpen = fso.openTextFile(fileAddress, ForReading, tristateTrue)。读取文本文件,为后续每行读取做准备
4)第21-30行:Do While Not strNewFileOpen.AtEndOfStream…Loop。对文本文件进行遍历读取。rowContent = strNewFileOpen.ReadLine为每一行的内容
5)第32行:strNewFileOpen.Close。关闭文本文件,与前面的fso.openTextFile对应
7)第40行:Kill fileAddress。删除该文件
