如何在Excel VBA中读取文本文件并保持更新

如何在Excel VBA中读取文本文件并保持更新,vba,excel,Vba,Excel,我是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 trigge

我是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代码吗?

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

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
命令以只读更改。