option buttons: optShort, optTall, optGrande
text box:
|
label: lblPrice (barely visible)
|
remarks | code |
At the very beginning of your code, you should always have the
Option Explicit line, which is your way of promising
Visual Basic that before you use any variable, you'll declare
it. (see p. 158 in the red book and the April 13 lab
handout) Any variable declarations (Dim lines) you put here are for global variables (see April 13 lab handout), since they're not inside a procedure. In this case, the Dim line declares one global variable called size for storing strings. |
Option Explicit
|
Here's the first of the five subroutines in this code; note the
header and trailer lines. This Sub, called btnCalculatePrice_Click, is an event handler, where the "event" is clicking the Calculate Price button. The code in this Sub is run each time the user clicks the button control named btnCalculatePrice_Click. The IDE sets up the header and trailer lines for this Sub when you create and double-click the button control on your form Note the three variable declarations at the start of this Sub. These are local variables and can only be used inside this Sub. There are two variable assignments, one for shots and another for price. Between them is a call to another Sub called calcPrice, defined below. The last line looks a lot like a variable assignment, but what's doing is changing a property of a control. In this case, the Caption property of the label control called lblPrice.
|
Private Sub btnCalculatePrice_Click() Dim shots As Integer Dim subTotal As Single Dim price As Single shots = txtShots.Text Call calcPrice(subTotal, shots, size) price = subTotal + subTotal * 0.086 lblPrice.Caption = "$" & Round(price, 2) End Sub |
This Sub, unlike the last one, is not an event handler. The
programmer had to type the header line in by hand. Again, we see some local variable declarations, and most of the code is composed of conditionals, three little conditionals (Ifs) and a fourth for extra charge which uses If with Else. Note the assignment at the end: p is basically whatever variable was passed as the first parameter in the call. (In the case of the call above in btnCalculatePrice_Click(), this is subTotal. Since subTotal is passed by reference, this assignment actually changes the value stored in subTotal when this Sub is called.
|
Sub calcPrice(p As Single, sh As Integer, sz As String) Dim basePrice As Single Dim extraCharge As Single If sz = "short" Then basePrice = 1.1 End If If sz = "tall" Then basePrice = 1.5 End If If sz = "grande" Then basePrice = 1.9 End If If sh > 1 Then extraCharge = (sh - 1) * 0.65 Else extraCharge = 0 End If p = basePrice + extraCharge End Sub |
Finally, we have three similar Subs, all of which are event
handlers. These Subs are called when the three option buttons
for choosing latte size are clicked. Each contains just a single assignment to the global variable size.
|
Private Sub optGrande_Click() size = "grande" End Sub |