|
[广告] VBA代码宝 - VBA编程加强工具 · VBA代码随查随用 · 内置多项VBA编程加强工具 ★ 免费下载 ★ ★ 使用手册★
Sub ImportLargeTextFile()
Dim filePath As String
Dim fileNumber As Integer
Dim fileContent As String
Dim lines As Variant
Dim headers As Variant
Dim data As Variant
Dim rowCount As Long
Dim colCount As Long
Dim i As Long, j As Long
Dim ws As Worksheet
Dim startTime As Double
' 记录开始时间
startTime = Timer
' 选择文件
filePath = Application.GetOpenFilename("Text Files (*.txt), *.txt", , "选择要导入的文本文件")
If filePath = "False" Then Exit Sub ' 用户取消选择
' 设置工作表
Set ws = ThisWorkbook.Sheets(1)
ws.Cells.Clear ' 清空工作表
' 打开文件并读取内容
fileNumber = FreeFile
Open filePath For Binary Access Read As #fileNumber
fileContent = Space(LOF(fileNumber))
Get #fileNumber, , fileContent
Close #fileNumber
' 将文件内容按行分割
lines = Split(fileContent, vbCrLf)
' 自动识别表头
headers = Split(lines(0), vbTab) ' 假设第一行是表头,分隔符为Tab
colCount = UBound(headers) + 1
' 将数据加载到数组
rowCount = UBound(lines)
ReDim data(1 To rowCount, 1 To colCount)
For i = 1 To rowCount
Dim fields As Variant
fields = Split(lines(i), vbTab)
For j = 0 To UBound(fields)
data(i, j + 1) = fields(j)
Next j
Next i
' 将表头写入工作表
ws.Range("A1").Resize(1, colCount).Value = headers
' 将数据写入工作表
ws.Range("A2").Resize(rowCount, colCount).Value = data
' 自动调整列宽
ws.Columns.AutoFit
' 显示完成信息
MsgBox "导入完成!" & vbCrLf & _
"总行数:" & rowCount & vbCrLf & _
"耗时:" & Format(Timer - startTime, "0.00") & "秒", vbInformation
End Sub |
|