Using Property Let and Property Get to Control How Users Utilize Custom Objects

Public variables, as declared in the earlier example, have read/write properties. When they are used in a program, the values of the variables can be retrieved or changed. To assign read/write limitations, use Property Let and Property Get procedures.

Property Let procedures give you control of how properties can be assigned values. Property Get procedures give you control of how the properties are accessed. In the custom object example, there is a public variable for weekly hours. This variable is used in a method for calculating pay for the week, but doesn't take overtime pay into consideration. Variables for normal hours and overtime hours are needed, but the variables must be read only.

To accomplish this, the class module must be reconstructed. It needs two new properties, EmpNormalHrs and EmpOverTimeHrs. But because these two properties are to be confined to read-only, they are not declared as variables. Property Get procedures are used to create them.

If EmpNormalHrs and EmpOverTimeHrs are going to be read-only, they must have values assigned somehow. Their values are a calculation of the EmpWeeklyHrs. Because EmpWeeklyHrs is going to be used to set the property values of these two object properties, it can no longer be a public variable. There are two Private variables. These private variables, NormalHrs and OverHrs, are used within the confines of the class module:

Public EmpName As String Public EmpID As String Public EmpRate As Double

Private NormalHrs As Double Private OverHrs As Double

A Property Let procedure is created for EmpWeeklyHrs to break the hours down into normal and overtime hours:

Property Let EmpWeeklyHrs(Hrs As Double)

NormalHrs = WorksheetFunction.Min(40, Hrs) OverHrs = WorksheetFunction.Max(0, Hrs - 40)

0 0

Post a comment