楼主 kevinchengcw |
Q: 如何根据文本特点将数据文本复原为数据表? A: 经常在文件导出后生成的是文本文件,在二次处理时数据难以像在Excel中处理那样方便,所以会经常想将文本再次转换成Excel文档,本文引用提问中一例演示将有规律的文本转化回表格的一种方式,代码如下:
- Sub test()
- Dim FSO, txtFile
- Dim Str, Resource, pName, DateFrom, DateTo As String
- Set FSO = CreateObject("scripting.filesystemobject") '创建FSO项目用于操作文本文件
- Set txtFile = FSO.opentextfile(ThisWorkbook.Path & "\Consumption Details.txt", 1) '利用FSO项目打开当前目录下的源数据文本文件
- Str = "" '以下初始化各个变量值
- Resource = ""
- pName = ""
- DateFrom = ""
- DateTo = ""
- Do Until txtFile.AtEndOfStream '循环直至文本文件结尾
- Str = Trim(txtFile.readline) '从文本文件中读取一行内容并去除两端的空格,然后赋值给字符串变量
- If Str <> "" And Left(Str, 1) <> "_" And Left(Str, 11) <> "PART NUMBER" And Str <> "0.00" Then '如果变量不存在无意义行的特征(注:根据文本文档中文本行的特征总结出的特征),则执行下述操作
- If Left(Str, 20) = "PRODUCTION RESOURCE:" Then '判断是否是以"PRODUCTION RESOURCE:"开头的文本,如果是则
- Resource = Trim(Split(Replace(Str, "PRODUCTION RESOURCE:", ""), "NAME:")(0)) '将其替换为空后,以"NAME:"为分隔分成两段,前段去掉两端空格赋值给变量Resource(即Production Resource)
- pName = Trim(Split(Replace(Str, "PRODUCTION RESOURCE:", ""), "NAME:")(1)) '后段赋值给变量pName(即Name内容)
- ElseIf Left(Str, 10) = "DATE FROM:" Then '否则,如果是以"DATE FROM:"开头,则利用同样的方式取得前后两个日期值赋值给变量DateFrom和DateTo(即起止日期段)
- DateFrom = Split(Replace(Replace(Str, "DATE FROM:", ""), " ", ""), "TO:")(0)
- DateTo = Split(Replace(Replace(Str, "DATE FROM:", ""), " ", ""), "TO:")(1)
- Else '如果都不是以上两种情况,则说明取得的是数据段,依据文本特点进行分段处理(注意去除两端空格)后放入对应单元格中
- With Worksheets("sheet2")
- .Cells(.Cells(.Rows.Count, 1).End(3).Row + 1, 1) = Resource
- .Cells(.Cells(.Rows.Count, 1).End(3).Row, 2) = pName
- .Cells(.Cells(.Rows.Count, 1).End(3).Row, 3) = DateFrom
- .Cells(.Cells(.Rows.Count, 1).End(3).Row, 4) = DateTo
- .Cells(.Cells(.Rows.Count, 1).End(3).Row, 5) = Trim(Left(Str, 21))
- .Cells(.Cells(.Rows.Count, 1).End(3).Row, 6) = Trim(Mid(Str, 22, 35))
- .Cells(.Cells(.Rows.Count, 1).End(3).Row, 7) = Trim(Mid(Str, 57, 9))
- .Cells(.Cells(.Rows.Count, 1).End(3).Row, 8) = Trim(Mid(Str, 66, 14))
- .Cells(.Cells(.Rows.Count, 1).End(3).Row, 9) = Trim(Mid(Str, 80, 11))
- .Cells(.Cells(.Rows.Count, 1).End(3).Row, 10) = Trim(Right(Str, 14))
- End With
- End If
- End If
- Loop
- txtFile.Close '关闭文本文件
- Set txtFile = Nothing '清空项目
- Set FSO = Nothing
- End Sub
附原文件示例。 在sheet2中运行test宏即可看到处理结果。 Consumption Deatils.rar |