我是Excel VBA的新手。我正在使用Arduino和Gobetwino进行一个项目,将传感器数据记录到文本文件中。要继续,我需要使用宏将文本文件中的数据记录到Excel,并在每次打开或运行宏时保持更新。此外,Gobetwino将在文本文件中逐行写入数据,包括日期和内容,如下所示:
utm-source = bing
utm-medium = cpc
utc_campaign = MO+Payday
utm_term = 'payday+loan'
utm_content = Payday+loans+(Phrase).
我需要在Excel的第一行查看最新数据。
有人可以帮我写这个VBA代码吗?
答案 0 :(得分:0)
这样就可以了。您可以将其分配给按钮或快捷方式 - 它将在每次调用时反向刷新文件中的数据。
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