Escolar Documentos
Profissional Documentos
Cultura Documentos
In VBA you can create your own custom objects by defining classes &
inserting class modules. You can also create your own custom class events, in addition to
Excel's own inbuilt event procedures.
Classes act as templates for new objects. The custom object is used to store, process and make data available.
A Class contains data and code - data can be accessed with properties
(viz. Name property) and the code is referred to as methods (which
are defined as Subs and Functions in VBA). Classes are integral to the
Object-Oriented Programming (OOP) language. A class is created by
inserting a Class Module (in your VBA project) to which you give a
name. A Class Module allows you to create your own objects having their
own properties and methods much like other objects such as range, worksheet, chart, etc. The Class Module has
its own set of VBA code (which includes variables, constants and procedures), which defines its properties and
The properties of the class object are manipulated in a Class
methods.
In Visual Basic Editor (VBE), click Insert in the menu bar and then click Class Module. Alternatively, in the Project
Explorer in VBE, right click on the VBA Project name or any object or item under it, click Insert and then click Class
Module. Or, on the Standard Tool bar in VBE, click the Insert button and then click Class Module. This creates a
blank class with the name Class1. To remove or delete a Class Module, right click after selecting it in the Project
Explorer in VBE, and then click on Remove.
One way to create a class property is by declaring a Public Variable in the Class Module, and this property will be
read-write. The other way to create a class property is by using Property Procedures ie. create a private variable to
hold values and use property statements (viz. Property Let, Property Set and Property Get). Creating properties
using a Public Variable, though simple, may not usually be preferable because it is not flexible. Using property
statements will enable to set a read-only or write-only property in addition to read-write, whereas using a public
variable will create only read-write properties. Further, using property statements you can execute code to
calculate values as properties whereas using a public variable will not allow use of code to set or return the value
of a property. For example, in case of an Area property, the area of a rectangle changes per its length-width and in
case the length-width is dynamic it should not be stored as a fixed value.
Property Procedure is a set of VBA codes that creates and manipulates custom properties for a class module.
A Property procedure is declared by a Property Let, Property Get or
Property Set statement and ends with an End Property statement.
Property Let (write-only property) is used to assign a value to a
property and Property Get (read-only property - which can only be
returned but not set) returns or retrieves the value of a property.
Property Set (write-only property) is used to set a reference to an
object. Property procedures are usually defined in pairs, Property Let and Property Get OR Property Set and
Property Get. A Property Let procedure is created to allow the user to change or set the value of a property,
whereas the user cannot set or change the value of a read-only property (viz. Property Get).
A Property Get declaration takes one argument less than in the associated Property Let or Property Set declaration
and the Property Get declaration should be of the same data type as the data type of the last argument in the
associated Property Let or Property Set declaration. The Property Get declaration will use the same property name
as used in the associated Property Let or Property Set declaration.
A Property Let procedure can accept multiple arguments, and in this case the last argument contains the value to
be assigned to the property. This last argument in the argument list is the property value set by the calling
procedure. The name and data type of each argument in a Property Let procedure and its corresponding Property
Get procedure should be the same, except for the last argument in the Property Let procedure which is additional.
All arguments before the last argument are passed to the Property Let procedure. In the case of a Property Let
procedure with a single argument (at least one argument is required to be defined), this argument contains the
value to be assigned to the property and is the value set by the calling procedure. In this case the Property Get
procedure will have no argument. It is not a usual practice to pass multiple arguments in property procedures and
sub-procedures or Functions are used for this.
A Property Set procedure can accept multiple arguments, and in this case the last argument contains the actual
object reference for the property. All arguments before the last argument are passed to the Property Set
procedure. In the case of a Property Set procedure with a single argument (at least one argument is required to be
defined), this argument contains the object reference for the property. The data type of the last argument or the
single argument must be an Object type or a Variant.
The Property Set procedure is similar to and a variation of the Property Let procedure and both are used to set
values. A Property Set procedure is used to create object properties which are actually pointers to other objects,
whereas a Property Let procedure sets or assigns values to scalar properties like string, integer, date, etc. Using the
Property Set statement enables Properties to be represented as objects.
Property Get:
Property Get PropertyName(argument_1, argument_2, …, argument_n) As Type
Property Let:
Property Let PropertyName(argument_1, argument_2, …, argument_n+1)
Property Set:
Property Set PropertyName(argument_1, argument_2, …, argument_n+1)
strStuName = strN
End Property
Name = strStuName
End Property
End Property
Marks = dblStuMarks
End Property
Grade = strGrade
End Function
Sub clsStudentRun()
'this procedure instantiates an instance of a class, sets and calls class properties:
'use the Dim statement to create a variable and define it as a reference to the class.
Dim iStudent As clsStudent
'a new object reference is created by using the New keyword. Mention the name of the class you
want to instantiate, after the New keyword.
'following code line (together with the above Dim statement, it is a two-line code to instantiate
an instance of a class), instantiates the clsStudent object:
Set iStudent = New clsStudent
'alternate single-line code to instantiate an instance of a class, however in this case the clsStudent
object gets instantiated only when the class method is first called, ie. iStudent gets instantiated
only when first used:
'Dim iStudent As New clsStudent
'sets the Name property in the clsStudent object to be the string "Peter", and passes this data to
the strN variable in the Name property:
iStudent.Name = "Peter"
'sets the Marks property in the clsStudent object to the value 45, and passes this data to the
iMarks variable in the Marks property:
iStudent.Marks = 45
'call the Marks property in the clsStudent object
MsgBox iStudent.Marks
MsgBox iStudent.Name & " has got " & iStudent.Marks & " percent marks with a Grade " &
iStudent.Grade
End Sub
Image 1a
Image 1b
Example 2 - Create Class Properties by using Property Procedures, Property Let procedure accepting
multiple arguments.
'Example - Create Class Properties by using Property Procedures, Property Let procedure
accepting multiple arguments.
Private dblA As Double
'In the case of a Property Let procedure with a single argument (at least one argument is required
to be defined), this argument contains the value to be assigned to the property and is the value set
by the calling procedure. In this case the Property Get procedure will have no argument.
'It is not a usual practice to pass multiple arguments in property procedures and sub-procedures
or Functions are used for this.
dblA = ar
MsgBox "Arguments received - lngth: " & lngth & ", wdth: " & wdth & ", ar: " & ar
End Property
Area = dblA
End Property
Sub clsRectangleRun()
'This procedure instantiates an instance of a class, sets and calls class properties, passing multiple
arguments to Property Let procedure:
Dim l As Double
Dim w As Double
'setting the property value - passes this data to the ar variable in the Area property:
rect.Area(l, w) = l * w
MsgBox "Area of Rectangle with length " & l & ", width " & w & ", is " & a
End Sub
Example 3 - Create Read-Only Class Property with only the PropertyGet_EndProperty block.
'Example - Create Read-Only Class Property with only the PropertyGet_EndProperty block.
Private dRectL As Double
Private dRectW As Double
dRectL = l
End Property
Length = dRectL
End Property
dRectW = w
End Property
Width = dRectW
End Property
End Property
Sub clsRectAreaRun()
'This procedure instantiates an instance of a class, sets and calls class properties.
Dim a As Double
Dim b As Double
areaRect.Length = a
areaRect.Width = b
MsgBox areaRect.rArea
End Sub
Example 4 - Using Property Set statement to set a reference to an object.
A Property Set procedure is used to create object properties which are actually pointers to
other objects.
'Example - Using Property Set statement to set a reference to an object. A Property Set procedure
is used to create object properties which are actually pointers to other objects.
'declare a private variable (ie. varCar) to store a reference to the clsMotorCars object:
Private varCar As clsMotorCars
'create an object variable (ie. varCar) and point it to the clsMotorCars object passed to the
procedure:
Set varCar = objCar
End Property
'return the object variable (ie. varCar) created by the Property Set procedure:
Set Car = varCar
End Property
Sub propSetCars()
'Using Property Set statement to set a reference to an object. A Property Set procedure is used to
create object properties which are actually pointers to other objects.
'instantiate as a clsCar object ie. create a new instance of the clsCar object. A new object
reference is created by using the New keyword.
Dim ownCar As clsCar
Set ownCar = New clsCar
'Car has been instantiated as a clsMotorCars object (note that Car is a property of the ownCar
object). See below how to access the properties & methods of clsMotorCars object:
Set ownCar.Car = New clsMotorCars
End Sub
Image 2a
Image 2b
Image 2c
Sub methodColor()
activeRange.Interior.ColorIndex = Color
End Sub
Sub clsSetRangeRun()
'Example - Using Property Set statement to set a reference to a Range object.:
'Instantiate as a clsRange object ie. create a new instance of the clsSetRange object. A new object
reference is created by using the New keyword.
Dim rngActive As clsSetRange
Set rngActive = New clsSetRange
'Set activeRange property (which is an object property) of clsSetRange object to ActiveCell, and
pass this data to the oRng variable in the activeRange property:
Set rngActive.activeRange = ActiveCell
MsgBox "Interior color, ColorIndex " & rngActive.Color & ", entered in cell " &
rngActive.activeRange.Address
End Sub
Custom Class Events
You can create your own class events also. Events are actions performed, or occurences, which
trigger a VBA macro. A VBA code is triggered when an event occurs such as, clicking on a
button, opening the workbook, selecting a cell or changing cell selection in a worksheet, and so
on. Excel also has its own Event Procedures which are triggered by a predefined event and are
installed within Excel having a standard & predetermined name viz. like the Worksheet change
procedure is installed with the worksheet as "Private Sub Worksheet_Change(ByVal Target As
Range)". When content of a worksheet cell changes, VBA calls the Worksheet_Change event
procedure and runs the code it contains. Here we explain how to create your own custom events
in a class.
Raise an Event:
After declaring an event, use a RaiseEvent Statement to trigger the declared event. The event
procedure runs when an event is raised or triggered. The event is raised in a public procedure
within the class module where it is declared, using the Event keyword. The RaiseEvent statement
passes values for the event's arguments, which also get passed to the event procedure that runs on
raising the event.
Examples
'Example of Creating a Custom Event - use a Worksheet_Change procedure to trigger the custom
event:
Private rngVar As Range
Private intColor As Integer
Private strName As String
'Event declaration: Use the Event keyword to define a custom event (ie. CellSelect event) in a
class module (ie. clsRange class). It can have any number of arguments, and the event
declaration should be Public to make it visible outside the object module.
Public Event CellSelect(cell As Range)
Sub methodColor()
selectedRange.Interior.ColorIndex = Color
End Sub
'Use the WithEvents keyword to declare an object variable (rng) of type clsRange. By declaring
this object variable, the instance of the clsRange class which this object variable points to will
respond to the event by adding the object to the events list in the Code window. Only variables
declared at module level can be used with the WithEvents keyword.
'After the variable declaration, the event procedure stub can be created similar to standard vba
procedures - rng will be displayed in the Object drop-down list and all its events are listed in the
Procedure drop-down list.
Private WithEvents rng As clsRange
rng.Name = "FirstCell"
'note that rng.selectedRange & rng.Color values have been assigned, because they will lose
values while executing below code:
Dim i As Integer
i = rng.Color
rng.selectedRange.Select
Selection.Offset(0, 1).Value = "Cell Name: " & rng.Name
Selection.Offset(0, 2).Value = "Cell Address: " & Selection.Address
Selection.Offset(0, 3).Value = "Cell Interior ColorIndex: " & i
Selection.Offset(0, 4).Value = "Cell Content: " & Selection.Value
End Sub
On Error GoTo ErrorHandler 'Enable error-handling routine for any run-time error
'Instantiate as a clsRange object ie. create a new instance of the clsRange object. A new object
reference is created by using the New keyword.
Set rng = New clsRange
ErrorHandler:
Application.EnableEvents = True 'EnableEvents is changed back to True on any error
End Sub
Image 3a
Image 3b
Example 7 - Create a Custom Event:- initialization of the UserForm triggers the custom event.
'Example of Creating a Custom Event - initialization of the UserForm triggers the custom event:
Private tb As MSForms.TextBox
Private strSeq As String
'Event declaration: Use the Event keyword to define a custom event (ie. eTxtBx event) in a class
module (ie. clsTextBox class). It can have any number of arguments, and the event declaration
should be Public to make it visible outside the object module.
Public Event eTxtBx(objTxtBx As MSForms.TextBox)
'Use the WithEvents keyword to declare an object variable (tx) of type clsTextBox. By declaring
this object variable, the instance of the clsTextBox class which this object variable points to will
respond to the event by adding the object to the events list in the Code window. Only variables
declared at module level can be used with the WithEvents keyword.
'After the variable declaration, the event procedure stub can be created similar to standard vba
procedures - tx will be displayed in the Object drop-down list and all its events are listed in the
Procedure drop-down list.
Private WithEvents tx As clsTextBox
Private sq1 As String, sq2 As String
MsgBox "text copied from the " & sq1 & " to the " & sq2
End Sub
End Sub
tx.setTxtBx.BackColor = vbYellow
With Me.TextBox1
tx.Sequence = "First TextBox"
sq1 = tx.Sequence
End With
With Me.TextBox2
tx.Sequence = "Second TextBox"
sq2 = tx.Sequence
End With
End Sub
'Instantiate as a clsTextBox object ie. create a new instance of the clsTextBox object. A new
object reference is created by using the New keyword.
Set tx = New clsTextBox
'Set setTxtBx object property of clsTextBox object, and pass the TextBox object (Me.TextBox1)
to the objTxtBx variable in the setTxtBx property:
Set tx.setTxtBx = Me.TextBox1
End Sub
Image 4a
Image 4b
Image 4c
Example 8 - Create a Custom Event:- use the WithEvents keyword, within the class module, to declare
an object variable (Initialize UserForm to start).
'Example of Creating a Custom Event - use the WithEvents keyword, within the class module, to
declare an object variable:
'Use the WithEvents keyword to declare an object variable (cBox) of type MSForms.ComboBox.
By declaring this object variable here, the excel built-in events associated with this object
variable will respond, by adding the object to the events list in the Code window.
Public WithEvents cBox As MSForms.ComboBox
End Sub
End Sub
End Sub
Insert a UserForm, insert a ComboBox (ComboBox1) and a CommandButton
(CommandButton1) within the Form. Insert Code in the UserForm Module:
'enter item in the text area of the ComboBox, which you want to add in ComboBox:
Dim strTxt As String
strTxt = cB.cBox.Text
'call the class method cB.cBox_AddItem and pass value and Boolean variable:
Call cB.cBox_AddItem(strTxt, Cancel)
End Sub
'call the class method (setComboBox) and pass ComboBox object for its argument's (objCbx)
value:
cB.setComboBox Me.ComboBox1
End Sub