Sams Teach Yourself Visual Basic 6 in 24 Hours

Sams Teach Yourself Visual Basic 6 in 24 Hours

By Greg Perry

Adding Code

Often, programmers run their applications as they build them despite the fact that no code exists yet to make the application do real work. You should be able to run your application now to make sure that the labels and text boxes all look correct. Check out the ToolTip text to ensure you've entered the text properly. Click the toolbar's End button to stop the program so that you can add the final code.

The code is going to borrow a bit from the interest calculation routine you learned about in Hour 8, "Visual Basic Looping." You'll have to modify the routine somewhat so the data comes from the Text Box controls you've set up. You want the calculation to take place when the user clicks the center command button, so add the following code to the command button's Click() event procedure. Double-click the Form window's Compute Interest command button to open the cmdCompute_Click () event procedure to complete the code that follows:

Private Sub cmdCompute_Click()
 ' Use a For loop to calculate a final total
 ' investment using compound interest.
 '
 ' intNum is a loop control variable
 ' sngIRate is the annual interest rate
 ' intTerm is the number of years in the investment
 ' curInitInv is the investor's initial investment
 ' sngInterest is the total interest paid
   Dim sngIRate As Single, sngInterest As Single
   Dim intTerm As Integer, intNum As Integer
   Dim curInitInv As Currency
   sngIRate = txtRate.Text / 100#
   intTerm = txtTerm.Text

   curInitInv = txtInvest.Text
   sngInterest = 1#   ' Begin at one for first compound

   ' Use loop to calculate total compound amount
   For intNum = 1 To intTerm
   sngInterest = sngInterest * (1 + sngIRate)
   Next intNum

   ' Now we have total interest,
   ' calculate the total investment
   ' at the end of [] years
   txtEnding.Text = curInitInv * sngInterest

End Sub

You must also add the terminating code for the Exit command button. Here's a simple way the Code window lets you add new procedures:

  1. Click the drop-down object list box (the left list box, directly beneath the toolbar) and select cmdExit.
  2. Select the event for which you want to add code in the right drop-down list box whose ToolTip reads Object. (The default procedure listed for command buttons is Click, so in this case you don't need to select a different procedure.)

Add the following code for the command button's event procedure:

Private Sub cmdExit_Click()
' Unload the form and terminate application
Unload frmInterest
End
End Sub

Share ThisShare This

Informit Network