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 Sub 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.

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 percent or by five dollars. Choice 1 will increase the salary by the specified percent, and choice 2 will add the specified amount to the current salary. The curSalary argument is the current salary figure for an employee, and amount determines the value by which the salary should be changed.

Tip 11-5: 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 Sub procedure.

0 0

Post a comment