假设:
- 所有文本文件都位于同一文件夹中
- 文本文件是制表符分隔的
使用此 Excel VBA 代码:
Sub tgr()
Dim oShell As Object
Dim oFSO As Object
Dim arrData(1 To 65000) As String
Dim strFolderPath As String
Dim strFileName As String
Dim strText As String
Dim DataIndex As Long
Dim lAvgLoc As Long
Set oShell = CreateObject("Shell.Application")
On Error Resume Next
strFolderPath = oShell.BrowseForFolder(0, "Select a Folder", 0).Self.Path & Application.PathSeparator
Set oShell = Nothing
On Error GoTo 0
If Len(strFolderPath) = 0 Then Exit Sub 'Pressed cancel
Set oFSO = CreateObject("Scripting.FileSystemObject")
strFileName = Dir(strFolderPath & "*.txt*")
Do While Len(strFileName) > 0
strText = oFSO.OpenTextFile(strFolderPath & strFileName).ReadAll
lAvgLoc = InStr(1, strText, "Daily Avg", vbTextCompare)
If lAvgLoc > 0 Then
strText = Mid(strText, lAvgLoc)
strText = Trim(Mid(Replace(strText, vbCrLf, String(255, " ")), Evaluate("MIN(FIND({1,2,3,4,5,6,7,8,9,0},""" & strText & """&1234567890))"), 240))
DataIndex = DataIndex + 1
arrData(DataIndex) = DateValue(Replace(strFileName, ".txt", vbNullString)) & vbTab & strText
End If
strFileName = Dir
Loop
If DataIndex > 0 Then
With Sheets.Add
.Range("A1:F1").Value = Array("DATE", "AVG1", "AVG2", "AVG3", "AVG4", "AVG5")
With .Range("A2").Resize(DataIndex)
.Value = Application.Transpose(arrData)
.TextToColumns .Cells, xlDelimited, xlTextQualifierDoubleQuote, Tab:=True
.NumberFormat = "mm-dd-yy"
End With
Application.DisplayAlerts = False
.SaveAs strFolderPath & "Daily Averages.csv", xlCSV
Application.DisplayAlerts = True
End With
End If
Set oFSO = Nothing
Erase arrData
End Sub
如何使用宏:
- 制作宏将在其上运行的工作簿的副本
- 始终在工作簿副本上运行新代码,以防代码运行不顺畅
- 对于删除任何内容的任何代码来说尤其如此
- 在复制的工作簿中,按 ALT+F11 打开 Visual Basic 编辑器
- 插入 | 模块复制提供的代码并粘贴到模块中
- 关闭 Visual Basic 编辑器
- 在 Excel 中,按 ALT+F8 以调出要运行的可用宏列表
- 双击所需的宏(我将这个命名为 tgr)