【问题标题】:How to read text file in Excel VBA and keep updated如何在 Excel VBA 中读取文本文件并保持更新
【发布时间】:2016-12-03 04:11:30
【问题描述】:

我是 Excel VBA 的新手。我正在做一个项目,使用 Arduino 和 Gobetwino 将传感器数据记录到文本文件中。要继续,我需要使用宏将文本文件中的数据记录到 Excel 中,并在每次打开或运行宏时保持更新。另外,Gobetwino 会在文本文件中逐行写入数据,日期和内容如下:

11/28/2016 12:00:00 sensor triggered
11/29/2016 00:00:05 sensor triggered
11/29/2016 05:00:00 sensor triggered

我需要在 Excel 的第一行查看最新数据。

有人可以帮我为此编写 VBA 代码吗?

【问题讨论】:

  • 您需要在开始时重新加载整个文件还是在每个新行上重新加载?重新加载整个文件还是继续向电子表格中添加新行?
  • 对于保持更新部分:stackoverflow.com/questions/1586169/…。这已经有一个解决方案了:)。

标签: vba excel


【解决方案1】:

这样就可以了。您可以将其分配给按钮或快捷方式 - 它会在每次调用时反向刷新文件中的数据。

Sub reverseFile()

    ' put the file into the same dir as spreasheet
    Const FILE_NAME = "sensorData.txt"

    Dim fileNum As Integer
    Dim line As String
    Dim c As New Collection
    Dim a() As String
    Dim i As Long

    ' read file line-by-line
    fileNum = FreeFile()
    Open ThisWorkbook.Path & Application.PathSeparator _
            & FILE_NAME For Input As #fileNum

    While Not EOF(fileNum)
        Line Input #fileNum, line
        c.Add line
    Wend

    Close #fileNum

    ' reverse the input lines into array
    ReDim a(1 To c.Count)
    For i = LBound(a) To UBound(a): a(i) = c(c.Count - i + 1): Next i

    ' display results in the spreadsheet
    With Worksheets("Sheet1").[a1]
        .CurrentRegion.Clear
        .Resize(UBound(a), 1) = Application.Transpose(a)
    End With

End Sub

【讨论】:

  • 非常感谢!我也在学习VBA。你能告诉我这里是哪个函数保持数据更新吗?
  • 如果你再次调用它,它将刷新文件中的整个列表 - 即它总是重新加载一个完整的文件。这可以快速处理相当大的文件 - 您可能不会遇到最多约 5-700000 条记录的问题。但是如果你只想加载最新的更新 - 记住文件中的位置并使用Seek 命令只读更改。
猜你喜欢
  • 2019-01-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-29
相关资源
最近更新 更多