Classes are constructed in class modules, which are created by choosing the command Insert | Class Module in the VBA editor. When creating classes, you need to provide for its initialization, and describe the properties and methods with which the object will be endowed.
The process of creating a class can be described as the following sequence of steps:
- Select the command Insert | Class Module. A new class module window will open.
- Press the key, and in the Properties window set the Name property to the name of the class. The name of the class module must match the name of the class.
- A class is initialized using the optional procedure Class_Initialize. In this procedure, you can specify the values assigned to fields when an instance of the class is constructed.
- It is also possible to declare the Class_Terminate procedure to describe the process of removing the object from memory when work with it is completed.
As an example, let us create a class Point, which models a point in a plane.
In this class there are only two fields: x and y, which define the coordinates of the point. The Public access modifier specifies that the fields are available to all external code and can be read and modified by any of them.
Class module Point
Public x As Integer ' Field x Public y As Integer ' Field y