HandsOn Continued

1. Change the calculation of the cost variable in the CalcCost procedure, as shown below:

cost = Format(slsPrice + (slsPrice * slsTax), "0.00")

2. To run the modified procedure, click any line between the Sub and End Sub keywords and press F5 or choose Run | Run Sub/UserForm.

After having tried out the CalcCost procedure, you may wonder why you should bother declaring variables if Visual Basic can handle undeclared variables so well. The CalcCost procedure is very short, so you don't need to worry about how many bytes of memory will be consumed each time Visual Basic uses the Variant variable. In short procedures however, it is not the memory that matters but the mistakes you are bound to make when typing variable names. What will happen if the second time you use the cost variable you omit the "o" and refer to it as cst?

strMsg = "The calculator total is " & "$" & cst & "."

Part I

And what will you end up with if, instead of slsTax, you use the word tax in the formula?

cost = Format(slsPrice + (slsPrice * tax), "0.00")

When you run the procedure with the above errors introduced, Visual Basic will not show the cost of the calculator because it does not find the assignment statement for the cst variable. And because Visual Basic does not know the sales tax, it displays the price of the calculator as the total cost. Visual Basic does not guess. It simply does what you tell it to do. This brings us to the next section, which explains how to make sure that errors of this sort don't occur.

^^ Note: Before you continue with this chapter, be sure to replace the names of the variables cst and tax with cost and slsTax.

0 0

Post a comment