【问题标题】:Extract Data from Text File into Excel将文本文件中的数据提取到 Excel 中
【发布时间】: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 但我的输出只显示文件中的第一个数据。请参阅下面的附件。

sample text

Output

Desired Output

这是我所拥有的:

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 自己的数据输入功能虽然要强大得多

标签: vba excel


【解决方案1】:

我为你修改代码,它可以工作:

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
dim idx%

MyFolder = "C:\directory\"
MyFile = Dir(MyFolder & "*.txt")

nextrow = ActiveSheet.Cells(Rows.Count, "A").End(xlUp).Row + 1

Do While MyFile <> ""

    Open (MyFolder & MyFile) For Input As #1

    'nextrow = ActiveSheet.Cells(Rows.Count, "A").End(xlUp).Row + 1

    Do Until EOF(1)
        Line Input #1, textline 'read a line

        idx = InStr(textline, "DATE-TIME") ' if has date, set it but not move to the next ROW
        if idx > 0 then 
            ActiveSheet.Cells(nextrow, "A").value = Mid(textline, idx + 16)
        end if

        idx = InStr(textline, "CARD NUMBER")
        if idx > 0 then
            ActiveSheet.Cells(nextrow, "B").value = Mid(textline, filenum + 16)

            nextrow = nextrow + 1 'now move to next row

        end if

    Loop
    Close #1
    MyFile = Dir()

Loop
End Sub

【讨论】:

  • 嗨!棒极了!像魅力一样工作!非常感谢。你是最好的! :)
  • 是的,刚刚做到了。再次感谢。 :)
猜你喜欢
  • 2021-06-01
  • 2017-12-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-23
  • 1970-01-01
  • 2019-06-02
相关资源
最近更新 更多