【发布时间】:2018-08-01 14:12:55
【问题描述】:
我是 VBA 新手,因此完成任务非常困难。几天来一直在阅读和尝试来自不同线程的代码,但没有成功。所以我希望有人可以帮助我。
我有多个文本文件需要从中提取数据。但我只需要将某些数据(例如 DATE-TIME)放在第一列,将 CARD NUMBER 放在第二列。从这个线程得到代码 >> Extract a single line of data from numerous text files and import into Excel 但我的输出只显示文件中的第一个数据。请参阅下面的附件。
这是我所拥有的:
Sub ExtractData()
Dim filename As String, nextrow As Long, MyFolder As String
Dim MyFile As String, text As String, textline As String, filedate As String
Dim filenum As Integer
MyFolder = "C:\directory\"
MyFile = Dir(MyFolder & "*.txt")
Do While MyFile <> ""
Open (MyFolder & MyFile) For Input As #1
Do Until EOF(1)
Line Input #1, textline
text = text & textline
Loop
Close #1
MyFile = Dir()
Debug.Print text
filedate = InStr(text, "DATE-TIME")
nextrow = ActiveSheet.Cells(Rows.Count, "A").End(xlUp).Row + 1
ActiveSheet.Cells(nextrow, "A").value = Mid(text, filedate + 16, 17)
filenum = InStr(text, "CARD NUMBER")
nextrow = ActiveSheet.Cells(Rows.Count, "B").End(xlUp).Row + 1
ActiveSheet.Cells(nextrow, "B").value = Mid(text, filenum + 16, 10)
text = ""
Loop
End Sub
【问题讨论】:
-
查看How to use Regular Expressions (Regex) in Microsoft Excel both in-cell and loops 以按任何模式提取数据。正则表达式是处理此类事情的强大工具。
-
@PEH 谢谢,看看。
-
为什么要写 VBA?您要求将文件 导入 到 Excel 中。您可以使用
Data选项卡中的命令执行此操作,并使用 PowerQuery 清理、转换数据 -
BTW
Line Input,Close等不在 VBA 中使用。它们是 VB5 甚至更早版本的遗留物。从 VB6 时代开始,人们就在 Scripting Runtime 中使用FileSystemObject和其他类。检查this question。 Excel 自己的数据输入功能虽然要强大得多