类模块——举例

时间:2022-07-22
本文章向大家介绍类模块——举例,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

类模块一个常用的场景是把一类常用的方法包装起来,这样用起来的时候就方便了。

前面使用Open 进行的文件操作,使用起来不是很方便,但是FileSystemObject里的TextStream使用起来就比较方便了,知道了类之后,就可以使用类对Open的文件操作进行包装。

使用Open读取文件需要3个步骤:

  • Open Filename For Binary Access Read As #num_file
  • Get #num_file, , b
  • Close #num_file

在类模块中肯定也得这3步,但是,参数的传递完全可以不那么复杂了:

  • num_file这个参数,完全就可以包装到类模块内部,外部使用不需要出现这个参数。
  • Close #num_file这个方法也可以直接放到类模块的内部,因为类具有2个事件Class_Initialize和Class_Terminate,Class_Terminate在类被销毁也就是Set c = Nothing的时候会自动执行,所以Close #num_file就可以放到这个事件中让它自动执行。

插入一个类模块,修改名称为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操作文件就方便的多了。