TXT文件數(shù)據(jù)格式
結(jié)果
Sub ReadTXTStrings()
Dim sLine As String'定義各個變量
Dim sFName As String
Dim iFNumber As Integer
Dim lRow As Long
Dim lColumn As Long
Dim vValues As Variant
Dim iCount As Integer
'txt文件纷铣,帶完整路徑(和excel同一個文件夾)
sFName = ThisWorkbook.Path & "\PD170611104100554111384.txt"
'先清空excel工作表的數(shù)據(jù)區(qū)域
Sheet2.UsedRange.Offset(1, 0).ClearContents
iFNumber = FreeFile 'FreeFile函數(shù)獲取txt文件的序號
Open sFName For Input As #iFNumber '打開txt文件
lRow = 1: k = 1 'txt數(shù)據(jù)首行 lRow
Do '循環(huán)讀取txt文件數(shù)據(jù),一行一行讀取
Line Input #iFNumber, sLine '讀取txt數(shù)據(jù)一個整行
If lRow > 9 Then'有效數(shù)據(jù)是從第10行開始
k = k + 1: lColumn = 1'確定excel工作表的行和列
vValues = Split(sLine, " ")'將整行數(shù)據(jù)按照空格分列,生成一個數(shù)組
For Each s In vValues'遍歷數(shù)組每一個元素
If Len(s) > 0 Then'如果數(shù)組元素不為空
With Sheet2'將數(shù)據(jù)寫入工作表
.Cells(k, lColumn) = s
lColumn = lColumn + 1'列數(shù)按1遞增
End With
End If
Next
'如果txt數(shù)據(jù)一整行都是空白宠默,那么退出DO循環(huán).最后一行有效數(shù)據(jù)接著就是一個空行,可以作為條件不再退出不再讀取txt剩余的無效數(shù)據(jù)咱士。
If Trim(sLine) = "" Then Exit Do
End If
lRow = lRow + 1'繼續(xù)讀取txt下一行數(shù)據(jù)
Loop Until EOF(iFNumber)
Close #iFNumber
End Sub
示例文件下載
鏈接: http://pan.baidu.com/s/1dFEfA73 密碼: egnw