|
|
|
|
||
Making it do something<< Back to Classes index pageIntroductionNow we've seen how to create an object with properties, we can make the object do something. A function in a class module that does something is known as a method. Again, we'll use a simple example to demonstrate the basics. Instructions
What we've learnedJust adding the code for a public function Tax to our simple object has created a method that calculates the sales tax at a straight 10 per cent of whatever its value is at the time. Again, it's hardly testing our computer, but it could equally well be as complicated as we like. What this meansEven with this simple example, the programmer using the object clsSimpleMethod in his VBA code does not need to know any of the messy details of how the tax is calculated. He just uses the expression oSim.Tax in his code. Meanwhile, from a higher level of program maintenance point of view, if we want to change the rate of tax to, say, 12%, we only have to alter one number in the code in clsSimpleMethod and, then, every time anyone has used the expression oSim.Tax anywhere in the program, the answer will be automatically correct. You're probably thinking that, so far, this is really no different from using a public function in a normal code module, apart from the auto list prompting. We'll see in later examples why using classes is much more powerful. A more complicated caseIf the tax laws become more complicated so, say, the tax is 10% if the value is $100 or less and 12% if more, we can change the code in our class module clsSimpleMethod as follows.
Public Function Tax() As Currency
If Me.Value <= 100 Then
Tax = 0.1 * Me.Value
Else
Tax = 0.12 * Me.Value
End If
End Function
This would give you the results in the Debug Window
set os = New clsSimpleMethod os.value = 100 ? os.tax 10 os.value = 200 ? os.tax 24 Question
Feedback or questions: Contact DI Management. Return to Tips and Tutorials Page. |
|
|
| Copyright © 2000-5 DI Management Services Pty Limited ABN 78 083 210 584 Sydney, Australia. www.di-mgt.com.au. All rights reserved. | |
|
Home | What We Do | Services | Our Approach | About Us | Projects | Tips | Links | Cryptography | About This Site | Contact | Email Us |