Creating the Class Methods

Apart from properties, objects usually have one or more methods. A method is an action that the object can perform. Methods allow you to manipulate the data stored in a class object. Methods are created with subroutines or function procedures. To make a method available outside the class module, use the Public keyword in front of the Sub or Function definition. The CEmployee object that you create in this chapter has one method that allows you to calculate the new salary. Assume that the employee salary can be increased or decreased by a specific percentage or amount.

©Custom Project 8-1 (Step 5): Writing Class Methods

1. Type the following CalcNewSalary function procedure in the CEmployee class module:

Public Function CalcNewSalary(choice As Integer, curSalary As Currency, _ amount As Long) As Currency Select Case choice

Case 1 ' by percent

CalcNewSalary = curSalary + ((curSalary * amount) / 100) Case 2 ' by amount

CalcNewSalary = curSalary + amount End Select End Function

The CalcNewSalary function defined with the Public keyword in a class module serves as a method for the CEmployee class. To calculate a new salary, a VBA procedure from outside the class module must pass three arguments: choice, CurSalary, and amount. The choice argument specifies the type of the calculation. Suppose you want to increase the employee salary by 5% or by $5.00. Choice 1 will increase the salary by the specified percent, and choice 2

Introduction to Access 2003 VBA Programming will add the specified amount to the current salary. The curSalary argument is the current salary figure for an employee, and the amount argument determines the value by which the salary should be changed.

About Class Methods

• Only those methods that will be accessed from outside of the class should be declared as Public. All others should be Private.

• Methods perform some operation on the data contained within the class.

• If a method needs to return a value, write a function procedure. Otherwise, create a subprocedure.

0 0

Post a comment