Class Definition

Related Topics

Syntax

[ | Private | Public | Friend ] _
Class name
    ...
End Class

Group

Declaration

Description

A class implements an object.

  • Has a set of Publicprocedures accessible from other modules, macros or code modules.
  • These public symbols are accessed by way of an object variable.
  • Has an optional set of Events that can be raised.
  • Has an optional Private Sub Class_Initialize which is called when an instance is created.
  • Has an optional Private Sub Class_Terminate which is called when an instance is destroyed.
  • To create an instance use:
    Dim Obj As classname
    Set Obj = New classname
    

Projects

A Class block can only be declared in a macro, Code module or a project's module.

Macro/code module

Starting with v10.35 one or more Class blocks can be declared in a macro or Code module in addition to variable and procedure declarations.

Option Explicit
Class Class1
    Public Data As String
    Private Sub Class_Initialize
        Data = "Hello"
    End Sub
End Class
Sub Main
    Dim c1 As New Class1
    Debug.Print c1.Data '"Hello"
    c1.Data = "Bye"
    Debug.Print c1.Data '"Bye"
End Sub

Access

If no access is specified then Friend is assumed.

Example

Option Explicit
Class File
    Dim FN As Integer
 
    Public Sub Attach(FileName As String)
        FN = FreeFile
        Open FileName For Input As #FN
    End Sub
 
    Public Sub Detach()
        If FN <> 0 Then Close #FN
        FN = 0
    End Sub
 
    Public Function ReadLine() As String
        Line Input '#'FN, ReadLine
    End Function
 
    Private Sub Class_Initialize()
        Debug.Print "Class_Initialize"
    End Sub
 
    Private Sub Class_Terminate()
        Debug.Print "Class_Terminate"
        Detach
    End Sub
End Class