Step 2 - Creating the CCalculator ClassStep 1 - Variable DeclarationsNow we get down to designing the interface for the CCalculator class which will provide all the functionality for our calculator. The class will accept numbers and operations (Add,Multiply,Divide and Subtract). On initialisation it will expect a number followed by an operation followed by a number etc. This continues until either the class is destroyed or the Cancel method is called. At this point it starts again expecting a number,operation, number etc. Each time a valid result is produced it is placed into the mdblResult variable which can be accessed through the Result property. This way interim results to calculations can be obtained. First we need to declare some variables in the General Declarations section of our class to keep track of which numbers or operations the user has inputted into our class. Place the following code into the General Declarations section of the CCalculator class module. Private mdblResult as Double Private mstrOperation As String Private mflgAdd As Boolean Private mflgSubtract As Boolean Private mflgMultiply As Boolean Private mflgDivide As Boolean Private mdblNumbers(1) As Double Private Enum CCalcEntryPoint CCFirstNumber = 0 CCSecondNumber = 1 End Enum
Private Enum CCalcErrors CCNumberRequired = vbObjectError + 512 + 1 CCOperatorRequired = vbObjectError + 512 + 2 End Enum ' Flags to check whether a number or an operation is due next Private mflgNumber As Boolean Private mflgFirstNumber As Boolean Private mflgOperation As Boolean The first variable mdblResult holds the result of the calculations performed by our calculator class. Each time a number is added to the class we will check to see whether it is the first number entered since either the class was initialised or since the Cancel method was called. If it isn't then we can assume we have at least two numbers and we perform whatever operation the user requested on the numbers (Add,Subtract,Multiply or Divide) The second variable mstrOperation holds the operation that was last selected ("+", "-", "*", or "/") The next four variables (mflgAdd, mflgSubtract, mflgMultiply and mflgDivide) are flags to set which operation was last requested. Hopefully this will all make sense further down the line although I'm making no guarantees…J We then create an array (mdblNumbers) with two elements to initially hold the first and second numbers that the user inputs. After two numbers have been input then the second element holds the interim result of each calculation and new numbers are added to the first element. This way we can hold the running total generated by our object in the second element of the array and return it through the Result property whenever the user of our object requests it. We have a couple of Enums. The first ( CCalcEntryPoint) to hold the element number in our mbblNumbers variable and the second (CCalcErrors) to hold error numbers generated by our class. Notice that the numbers generated use the constant vbObjectError + 512 which guarantees that the number is in the range allowed for user defined errors. The first Enum is probably a bit over the top but it gives you a (rather useless) example of the things that Enums can be used for.The final three variables are flags to enable us to check whether the user last entered a number or an operation and to raise an error if they are input in the wrong order. Step 2. The Class Initialise The code sets three flags so that.
The class initialise routine is ran once when the class is first instantiated (created) by using either Dim/Private/Public myVariable as CCalculator or Dim/Private/Public myVariable as New CCalculator. The first method requires you to create an instance of the class using set myVariable = new Ccalculator. This is the preferred method since it gives you control over when your class is instantiated. The second method automatically creates an instance of the class when you call one of its properties or methods. This leaves you far less control over where in your code the class is created since it is dependant on the route taken through your code.Private Sub Class_Initialize() mflgNumber = True mflgOperation = False mflgFirstNumber = True End Sub
Step 3. The properties and methods The first property that we define is the number property. This is a write-only property because it only has a Property Let procedure. You can expose properties of your class to the outside world by declaring a public variable but this does not provide you with any control over how the property is used so you should always expose properties using Property Get (for reading properties), Property Let (for providing write access to properties) or Property Set (similar to Property Let except that a reference to an object is returned rather than a standard data type) Public Property Let Number(Value As Double) ' Read only property containing the numbers we are performing calculations on If Not mflgNumber Then Err.Raise CCNumberRequired, "CCalculator:NumberGet", "Requires an operator next" If mflgFirstNumber Then mdblNumbers(CCFirstNumber) = Value ' Reset the first number flag mflgFirstNumber = Not mflgFirstNumber Else mdblNumbers(CCSecondNumber) = Value ' Calculate the interim result Call Calculate End If mflgNumber = False mflgOperation = True End Property The first thing our Property Let procedure does is check to ensure that the class is expecting a number next. Values will be input in the order number, operation, number etc… If the number is the first number input then the number is added to the first element of our mdblNumbers array. Then the first number flag is reset. It will only be reset again on Class initialise or if the Cancel method is called.If the number is the second number input then the number is assigned to the second element in the mdblNumbers array and then since we now have at least two numbers the Calculate method is calledWe then need a Result property to hold the result of calculations performed by our calculator object. Public Property Get Result() As Double ' Return the result of the calculations Result = mdblResult End Property This property is read-only (i.e there is only a Property Get procedure) and it passes out the value of the private variable mdblResult.The Add, Subtract, Multiply and Divide methods all perform pretty much the same functions. Public Sub Add() If Not mflgOperation Then Err.Raise CCOperatorRequired, "CCalculator:Add", "Requires a number next" mstrOperation = "+"
' Set the flags mflgAdd = True mflgSubtract = False mflgMultiply = False mflgDivide = False mflgNumber = True mflgOperation = False End Sub Public Sub Subtract() If Not mflgOperation Then Err.Raise CCOperatorRequired, "CCalculator:Add", "Requires a number next" mstrOperation = "-"
' Set the flags mflgAdd = False mflgSubtract = True mflgMultiply = False mflgDivide = False mflgNumber = True mflgOperation = False End Sub Public Sub Multiply() If Not mflgOperation Then Err.Raise CCOperatorRequired, "CCalculator:Add", "Requires a number next" mstrOperation = "*"
' Set the flags mflgAdd = False mflgSubtract = False mflgMultiply = True mflgDivide = False mflgNumber = True mflgOperation = False End Sub Public Sub Divide() If Not mflgOperation Then Err.Raise CCOperatorRequired, "CCalculator:Add", "Requires a number next" mstrOperation = "/"
' Set the flags mflgAdd = False mflgSubtract = False mflgMultiply = False mflgDivide = True mflgNumber = True mflgOperation = False End Sub The methods set the mstrOperation private string variable to either "+", "-", "*" or "/" depending on the operation to be performed and set the respective operation flag to TRUE depending on the operation being performed. They then set the flags which the object uses to determine whether it is expecting a number or an operation next.Public Sub Cancel() mstrOperation = ""
' Reset the flags mflgAdd = False mflgSubtract = False mflgMultiply = False mflgDivide = False
mflgNumber = True mflgOperation = False mflgFirstNumber = True
End Sub The Cancel method returns the object to the state it was in when it was initialised. This method is used in the same way as the cancel key on a calculator to reset the calculations and allow a new calculation to be entered. Public Sub Calculate() Select Case mstrOperation Case Is = "+" mdblResult = mdblNumbers(CCFirstNumber) + mdblNumbers(CCSecondNumber) mdblNumbers(CCFirstNumber) = mdblResult
Case Is = "-" mdblResult = mdblNumbers(CCFirstNumber) - mdblNumbers(CCSecondNumber) mdblNumbers(CCFirstNumber) = mdblResult
Case Is = "*" mdblResult = mdblNumbers(CCFirstNumber) * mdblNumbers(CCSecondNumber) mdblNumbers(CCFirstNumber) = mdblResult
Case Is = "/" mdblResult = mdblNumbers(CCFirstNumber) / mdblNumbers(CCSecondNumber) mdblNumbers(CCFirstNumber) = mdblResult
End Select End Sub The calculate method is called from the Number Property Let procedure when there are two numbers to work with and thereafter each time a new number is added until either the object is destroyed using set objCalc = Nothing or when the Cancel method is called. The value of the calculation is stored in the first element of the mdblNumbers array providing a running total of the current calculation which can be obtained by calling the Result property of the CCalculator object.Testing You can test this class from the immediate window. First make sure that the Start Mode in the Project Properties/Component dialogue is set to ActiveXComponent. Start the project and open the immediate window. Press Ctrl/Break to enter break mode. You will now be able to type into the immediate window.
You can instantiate the calculator object by typing Set x = new Ccalculator You can now call properties and methods using ? or debug.print to print out values returned. An example is included below.. set x = new cCalculator x.number = 5 x.add x.number = 7 ? x.result 12 x.multiply x.number = 5.3 ? x.result 63.6 x.divide x.number = 7 ? x.result 9.08571428571429
[Main Tutorial Page][ActiveX Calc Tutorial TOC] |
Quick searches: Site Search | Advanced Site Search |
|
By using this site you agree to its terms and conditions VB Explorer and VBExplorer.com are trademarks of Exhedra Solutions, Inc. |