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

我是Excel VBA的新手。 我正在使用Arduino和Gobetwino将传感器数据logging到文本文件中。 为了继续,我需要使用macros来将文本文件中的数据logging到Excel中,并在每次打开或运行macros时保持其更新。 另外,Gobetwino会将文本文件中的数据逐行写入date和内容如下:

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

这将做的伎俩。 您可以将其分配给一个button或快捷方式 – 每次调用时都会从文件中反向刷新数据。

 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