Excel VBA 代码导入 TXT 数据
Sub ImportTxtFile()
' 定义变量
Dim FileToOpen As Variant
Dim FilePath As String
Dim FileName As String
Dim LastRow As Long
' 选择要导入的 txt 文件
FileToOpen = Application.GetOpenFilename('Text Files (*.txt), *.txt')
' 如果用户选择了文件,则开始导入
If FileToOpen <> False Then
' 提取文件路径和文件名
FilePath = Left(FileToOpen, InStrRev(FileToOpen, '\'))
FileName = Mid(FileToOpen, InStrRev(FileToOpen, '\') + 1)
' 打开文件并导入数据
With ActiveSheet.QueryTables.Add(Connection:='TEXT;' & FileToOpen, Destination:=Range('A1'))
.TextFileStartRow = 1
.TextFileCommaDelimiter = True
.Refresh
End With
' 删除空行
LastRow = Cells(Rows.Count, 'A').End(xlUp).Row
Cells(LastRow + 1, 'A').Select
Do Until ActiveCell.Value <> ''
Selection.EntireRow.Delete
Loop
' 提示导入成功
MsgBox '文件 ' & FileName & ' 已成功导入。'
End If
End Sub
原文地址: https://www.cveoy.top/t/topic/njBD 著作权归作者所有。请勿转载和采集!