Microsoft Access 2010 Bible

(Rick Simeone) #1

Chapter 28: Object-Oriented Programming with VBA


977


Public Sub Sell(UnitsSold As Integer)
Me.UnitsInStock = Me.UnitsInStock - UnitsSold
End Sub
Notice there’s nothing special about the Sell method. There’s no special declaration for
this procedure, nor is there reference to its status as a method of the class. Methods are an
example of how Access treats class modules differently from simple code modules. As long
as you haven’t declared the procedure (sub or function) with the Private keyword
(remember that the Public keyword is the default), Access treats the procedure as a
method of the objects created from the class module.
Because it’s a subroutine, the Sell method doesn’t return a value. If you declare it as a
function, it could return any valid Access data type. The Sell procedure requires an
argument specifying how many items were sold.

Note
Notice the use of the Me keyword in the previous code example. In this context, Me refers to the object
instance created from the class module.


You may have noticed an obvious bug in the Sell method. If the UnitsSold is larger
than the UnitsInStock, the UnitsInStock value will be a negative number after the
method runs. To fix this bug, you must add a couple of lines of code to the method:
Public Sub Sell(UnitsSold As Integer)
If UnitsSold > Me.UnitsInStock Then
Exit Sub
End If
Me.UnitsInStock = Me.UnitsInStock - UnitsSold
End Sub
This change causes the Sell method to simply exit and not deduct any units when the
UnitsSold value would result in a negative value for the UnitsInStock.

On the CD-ROM
Obviously, you can add much more to the Product class. I’ve included the complete class module in the
Chapter28.accdb example database as the clsProduct1 module in the Modules tab of the database.


l Discount: The Discount method is similar to Sell:
Public Sub Discount(Percent As Integer)
If Percent < 1 _
Or Percent > 99 Then
Exit Sub
End If
Me.UnitPrice = _
Me.UnitPrice - ((Percent / 100) * Me.UnitPrice)
End Sub
In this case, the method ends immediately if the Percent is less than 1 or larger than 99.
Otherwise, the object’s UnitPrice property is discounted by an expression derived from
the Percent and current UnitPrice.
Free download pdf