将文本文件导入到Excel数据表中

Dim r%
Sub ImportFromTextFile()
Dim fso As Object, sFile As Object, blnExist As Boolean
Dim FileName As String, i As Integer, iCol As Integer, LineText As String
Const ForReading = 1
Set fso = CreateObject("Scripting.FileSystemObject") '创建FileSystemObject对象
FileName = "H:\nama_exi_p.tsv" '指定文本文件名
blnExist = fso.FileExists(FileName) '判断文件是否存在,如果不存在,则退出过程
If Not blnExist Then MsgBox "文件不存在!": Exit Sub
Set sFile = fso.OpenTextFile(FileName, ForReading) '创建并打开名为sFile的TextStream对象
Do While Not sFile.AtEndOfStream '如果不是文本文件的尾端,则读取数据
LineText = sFile.ReadLine
Call getNum1(LineText)
Loop
sFile.Close
Set fso = Nothing
Set sFile = Nothing
End Sub
Sub getNum1(str As String)
r = r + 1
Set reg = CreateObject("VBScript.RegExp")
With reg
.Global = True
.IgnoreCase = True
.Pattern = "(\S+)\s+(\S+)\s+(\S+)"
End With

Set mc = reg.Execute(str)
For Each m In mc

Cells(r, 1) = m.submatches.Item(0)
Cells(r, 2) = m.submatches.Item(1)
Cells(r, 3) = m.submatches.Item(2)
Next
End Sub

猜你喜欢

转载自www.cnblogs.com/zhujie-com/p/11932911.html