'将如下宏代码粘贴到excel的VBA编辑器中,按F5运行即可,注意修改你的txt文件所在的目录。
Sub ReadTxt()
Dim Path As String, MyValue As String, fn As Long
Path = "C:\test" '假定你的24个txt文件处在C:\test 文件夹中,可以自行修改
fn = FreeFile
For i = 1 To 24
j = 0
Open "C:\test\" + Format(i, "000") + ".txt" For Input As fn
Do Until EOF(fn)
Line Input #fn, MyValue
j = j + 1
If j = 3 Then Exit Do
Loop
Close #fn
MyValue = Trim(MyValue)
If InStr(MyValue, ",") Then '假设各列的数据分隔符为中文逗号,如果是英文逗号,自行修改为InStr(MyValue, ",")
pos = inst(MyValue, ",")
If pos Then
pos = InStr(pos + 1, MyValue, ",")
If pos Then
pos = InStr(pos + 1, MyValue, ",")
If pos Then
MyValue = Mid(MyValue, pos + 1)
pos = InStr(MyValue, ",")
If pos Then MyValue = Left(MyValue, pos - 1)
End If
End If
End If
ElseIf InStr(MyValue, " ") Then '假设各列的数据分隔符为空格
Do
a = Len(MyValue)
MyValue = Replace(MyValue, " ", "")
Loop While a <> Len(MyValue)
pos = inst(MyValue, " ")
If pos Then
pos = InStr(pos + 1, MyValue, " ")
If pos Then
pos = InStr(pos + 1, MyValue, " ")
If pos Then
MyValue = Mid(MyValue, pos + 1)
pos = InStr(MyValue, " ")
If pos Then MyValue = Left(MyValue, pos - 1)
End If
End If
End If
ElseIf InStr(myvale, vbTab) Then '假设每一行的各列的分隔符为一个Tab制表符
Do
a = Len(MyValue)
MyValue = Replace(MyValue, vbTab + vbTab, vbTab)
Loop While a <> Len(MyValue)
pos = inst(MyValue, vbTab)
If pos Then
pos = InStr(pos + 1, MyValue, vbTab)
If pos Then
pos = InStr(pos + 1, MyValue, vbTab)
If pos Then
MyValue = Mid(MyValue, pos + 1)
pos = InStr(MyValue, vbTab)
If pos Then MyValue = Left(MyValue, pos - 1)
End If
End If
End If
End If
Cells(i, 1) = myvale '将提取的数据填充在第一列的各行中
Next
MsgBox "处理提取完毕!"
End Sub
温馨提示:答案为网友推荐,仅供参考