类模块一个常用的场景是把一类常用的方法包装起来,这样用起来的时候就方便了。
前面使用Open 进行的文件操作,使用起来不是很方便,但是FileSystemObject里的TextStream使用起来就比较方便了,知道了类之后,就可以使用类对Open的文件操作进行包装。
使用Open读取文件需要3个步骤:
在类模块中肯定也得这3步,但是,参数的传递完全可以不那么复杂了:
插入一个类模块,修改名称为CFile:
Private lFileLen As Long
Private num_file As Integer
'读取len(b)个byte
Function Read(b() As Byte) As Long
Dim ilen As Long
ilen = UBound(b) - LBound(b) + 1
Dim iseek As Long
iseek = VBA.Seek(num_file)
If iseek + ilen > lFileLen Then
ilen = lFileLen - iseek + 1
End If
iseek = iseek + ilen
Get #num_file, , b
Read = ilen
End Function
'以字节方式读取文本
Function OpenFile(Filename As String) As Long
num_file = VBA.FreeFile
Open Filename For Binary Access Read Write As #num_file
lFileLen = VBA.FileLen(Filename)
End Function
Function CloseFile()
Close #num_file
End Function
Private Sub Class_Terminate()
CloseFile
End Sub
外部使用:
Sub TestCFile()
Dim cf As CFile
Set cf = New CFile
cf.OpenFile ThisWorkbook.Path & "\test.txt"
Dim b(10) As Byte
cf.Read b
Dim str As String
str = VBA.StrConv(b, vbUnicode)
Debug.Print str
Set cf = Nothing
End Sub
这种对象形式的使用方法比起直接用Open操作文件就方便的多了。