今天在论坛中,看到有人求助如何用EXCEL读取txt 文本里面的数据,http://www.excelba.com/BBs/Show.asp?bid=1&aid=2332感觉可以做一个通用的自定义函数来获得,便把回付的贴子内容记录在此。
Function GetFileText(xPath As String, Optional xRow As Integer = 1, _
Optional yCol As Integer = 1, Optional zLen As Integer = 0)
'*******************************************
'时间:2008-10-26
'作者:bengdeng
'功能:读取指定文件中指定行、列与长度的文件
'参数:xPath 文件的完整地址,必需
' xRow 指定行,可选,忽略或小于0时,则从第一行开始
' yCol 指定列,可选,忽略或小于0时,则从第一个字符开始
' zLen 指定长度,可选,如忽略或小于等于0则指为读取到行尾
'注意:如果在工具/引用中引用Windows Script Host Object Model
' 则FSO与TS后的数据类型可用,不引用则不可用,不过程序正常运行
'发布:http://www.excelba.com
'*******************************************
On Error GoTo Err
Dim FSO 'As FileSystemObject
Dim TS 'As TextStream
Dim II As Integer
Set FSO = CreateObject("Scripting.FileSystemObject")
Set TS = FSO.OpenTextFile(xPath, 1)
For II = 1 To xRow - 1
TS.SkipLine
Next
GetFileText = TS.ReadLine
If yCol < 1 Then yCol = 1
If zLen <= 0 Then
GetFileText = Mid(GetFileText, yCol, Len(GetFileText))
Else
GetFileText = Mid(GetFileText, yCol, zLen)
End If
Exit Function
Err:
GetFileText = "#Value"
End Function
下面给出如何利用上面自定义函数读取自定义函数所以文件的目录中,文件名为123.txt的文件中的内容。
Sub Text()
'省略后面三个参数,则为读取首行全部内容
MsgBox GetFileText(ThisWorkbook.Path & "\123.txt")
'省略后面两个参数,则为读取指定行的全部内容
MsgBox GetFileText(ThisWorkbook.Path & "\123.txt", 2)
'省略最后的参数,则为读取指定行从指定字符开始到行尾的内容
MsgBox GetFileText(ThisWorkbook.Path & "\123.txt", 2, 3)
'读取指定行指定字符开始指定长度的字符串
MsgBox GetFileText(ThisWorkbook.Path & "\123.txt", 2, 3, 4)
End Sub