Visual Basic Projects

The previous chapter introduced Visual Basic’s development editor, basic controls, and the principles of event-driven programming. In this chapter, we expand on that introduction to the language by building some real-life applications. Among other topics, we’ll look at how to write applications that have multiple windows, how to validate user input, and how to write error-trapping routines. We’ll also look at several techniques you’ll need as you work through the applications we develop in the rest of the book.

The bulk of the chapter demonstrates very basic programming techniques, such as building user interfaces, event programming, validating user input, and so on. The goal is to show you how to write simple applications using the most basic elements of the language. This chapter will explain the methodology for building applications. While the code of the applications will be rather simple, it will demonstrate user interface design and the basics of validating data and trapping errors.

If you’re a beginner, you may be thinking, “All I want now is to write a simple, application that works-I’ll worry about data validation later.” It’s never too early to start thinking about validating your code’s data and error trapping. As you’ll see, making sure that your application doesn’t crash requires more code than the actual operations it performs! If this isn’t quite what you expected, welcome to the club. A well-behaved application must catch and handle every error gracefully, including user errors. This chapter only discusses the basic concepts of error handling you’ll need to build a few simple applications.

Building a Loan Calculator

An easy-to-implement, practical application is one that calculates loan parameters. Visual Basic provides built-ill functions for performing many types of financial calculations, and you only need a single line of code to calculate the monthly payment given the loan amount, its duration, and the interest rate. Designing the user interface, however, takes much more effort.

Regardless of the language you use, you must go through the following process to develop an application:

1. Decide what the application will do and how it will interact with the user.
2. Design the application’s user interface.
3. Write the actual code.

Deciding How the Loan Application Works

Following the first step of-the process outlined above, you decide that the user should be able to specify the amount of the loan, the interest rate, and the duration of the loan in months. You must, therefore, provide three textboxes where the user can enter these values.

Another parameter affecting the monthly payment is whether payments are made at the beginning or at the end of each month, so you must also provide a way for the user to specify whether the payments will be early (first day of the month) or late (last day of the month). The most appropriate type of control for entering Yes/No or True/False type of information is the Check Box control. The CheckBox control is a toggle. If it’s checked, you can clear it by clicking on it. If it’s cleared, you can check it by clicking again. The user doesn’t enter any data in this control and it’s the-simplest method for specifying values with two possible states.

After the user enters all the information on the Form, they can click the Show Payment Command button to calculate the monthly payment and display it in a message box. All the action takes place in the Command button’s Click subroutine. The function for calculating monthly payments is called Pmt), and it must be called as follows:

MonthlyPayment = Pmt(InterestRate, Periods, Amount, FutureValue, Due)

The interest rate (variable InterestRate) is specified as a monthly rate. If the interest rate is 16.5%; this value should be 0.165/12. The duration of the loan (Periods) is specified in number of months, and Amount is the loan’s amount. The Future Value of a loan is zero (it would be a positive value for an investment), and the last parameter, Due, specifies when payments are due. If it’s 0, payments are due at the beginning of the month; if it’s 1, payments are due at the end of the month.

The present value of the loan is the amount of the loan with a negative sign’ It’s negative because you don’t have the money now. You’re borrowing it; it’s money you owe to the bank. The future value of the.loan is zero. The future value represents what the loan will be worth when it’s paid off. This is what the bank owes you or what you owe the bank at the end of the specified period.

Pmt is a built-in function that uses the five values in the parentheses to calculate the monthly payment. The values passed to the function are called arguments. Arguments are the values needed by a function (or subroutine) to carry out an action, such as a calculation. By’passing different values to the function, the user can calculate the parameters of a different loan. The Pmtt) function and other financial functions of Visual Basic are described in Appendix A, Built-In Functions, on the CD that accompanies this book.

You don’t need to know how the Pmtt) function calculates the monthly payment. The Prntt) function does the calculations and returns the result. To calculate the monthly payment on a loan of $25,000 with an interest rate of 14.5%, payable over 48 months/and due the last day of the payment period (which.in our case is’, a month), you’d call the PmtO function as follows:

Debug.Print Pmt(0.145 / 12, 48, -25000, 0, 0)

The value 689.448821287218 will be displayed in the Immediate window (you’ll see later how you can limit the digits after the decimal point to two, since this is all the accuracy you need for dollar amounts). Notice the negative sign in front of -the amount. If you specify a positive amount, the,result will be a ‘negative payment. The payment and the loan’s amount have different signs because they represent different cash flows. The last two arguments of the Pmto function are optional. If you omit them, Visual Basic assumes they are zero. You could also call the Pmtt) function like this:

Debug. Print Pmt(O .145 / 12, 48, -25000)-

Calculating the amount of the monthly payment given the loan parameters is quite simple. What you need to know or understand -are the parameters of a loan and how to pass them to the PmtO function. You must also know how the interest rate is specified, to avoid invalid values. What you don’t need to know is how the payment is calculated. Visual Bask does it for you. This is ~ essence of functions: they are “black boxes” that perform complicated calculations on their arguments and return the result. You don’t have to know how they work, just how to supply’ the values required for the calculations.

Designing the User Interface

Now that you know how to calculate the monthly payment, you can design the user interface. To do so, start a new project, rename its Form to Loan Calculator rename the project to Loan Project, and save the project as Loan. The Form and the project files can be found in the Loan folder under this chapter’s folder on the CD.

Your first task is to decide the font and size of the text you’ll use for most controis on the Form. Although we aren’t going to display anything on the Form directly, all the controls we place on it will have by default the same font as the Form (which is called the container of the controls). You can change the font later during the design, but it’s a good idea to start with the right font. At any rate, don’t try to align the controls if you’re planning to change their fonts. This will, most likely, throw off your alignment efforts.

The Loan application you’ll find on the CD uses lO-point MS Sans Serif. To change it, select the Form with the mouse, double-click the name of the Font property in the Properties window to open the Font dialog box, and select the desired font and attributes.

To design the Form shown previously, follow these steps:

1. Place three labels on the Form and assign the following captions to them:

Label1 Loan amount

Label2 Interest rate

Label3 Duration (in months).

The labels should be large enough to fit their captions. You don’t need to change the default names of the three Label controls on the Form because their captions are all we need. You aren’t going to program them.

2. Place a TextBox control nextto each label. Name the first textbox (the one nexrto the first label) Amount and set its Text property to 25,000, name the second textbox IRate and set its value to 14.5, and name the third textbox Duration and set its value to 48. These initial values correspond to a loan of $25,000 with an interest rate of 14.5% and a payoff period. of 48 months.

3. Next, place a CheckBox control on the Form. By default, the control’s caption is Checkl, and it appears to the right of the checkbox. Because we want the titles to be to the left of the corresponding controls, we’ll change this default appearance.

4. Select the checkbox with the mouse (if it’s not already selected), and in the Properties window, locate the Alignment property. Its value is O-Left Justify. If you expand the drop-down list by clicking the Arrow button, you’ll see that this property has another setting, I-Right Justify. Select the alternate value from the list.

5. With the checkbox selected, locate the Name property in the Froperties window, and set it to PayEarly.

6. Change the caption by entering the string “Check if early payments” in its Caption property field.

7. Place a Command button control on the lower left comer of the Form. Name it Showf’ayment, and set its caption to “Show Payment”.

8. Finally, place a TextBox control next to the Command button and name it. txtPml This is where the monthly payment will appear. Notice that the user isn’t supposed to enter any data in this box, so you must set its Locked property to True ..You’ll be able to change its value from within your code, but users won’t be able to type anything in it. (We could have used a Label control instead, but the uniform look of TextBoxes on a Form is usually preferred).

Aligning the Controls

Your next step is to align the controls on the Form. First, be sure that the captions on the labels are visible. Our labels contain lengthy captions, and if you don’t make the labels long enough, the captions may wrap to a second line and become invisible like the one shown.

To align the controls on the Form, Visual Basic provides a number of commands, all of which can be accessed through the Format menu. To align the controls that are already on the LoanCalc Form, follow these steps:

1. Select the three labels and the. checkbox, and left-align them by choosing Format» Align» Left.

2.. Select the four textboxes, and left-align them by choosing Format» Align » Left. Don’t include the checkbox in this selection.

3. With all four textboxes still selected, use the mouse to align them above and below the box of the CheckBox control.

Take a good look at it and check to see if any of your controls are misaligned. In the interface design process, you tend to overlook small problems such as a slightly misaligned control. The user of the application, however, instantly spots such mistakes. It doesn’t make any difference how nicely the rest of the controls are arranged on the Form; if one of them is misaligned, it will attract the user’s eye.

Programming the Loan Application

Now run the application and see how it behaves. Enter a few values in the textboxes, change the state of the checkbox, and test the functionality already built into the application. Clicking the Command button won’t have any effect because we have not yet added any code. If you’re happy with the user interface, stop the application, open the Form, and double-click the Command button. Visual Basic opens the Code window and displays the following three lines of the Show Payment_ Click event:

Option Explicit
.’
Private Sub ShowPayment_Click() , 
End Sub

Place the pointer between the lines Private … and End Sub, and enter the following lines:

The Code window should now look like the one shown. Notice the underscore character at the end of the first part of the long line. The underscore lets you break-long lines so that they will fit nicely in the Code window. I’m using this convention in this book a lot to fit long lines on the printed page. The same statement may appear in a single, long line in the project.

the first line of code declares a variable. It lets the application know that Payment is a placeholder for storing a floating-point number (a number . with a decimal part). The first really executable line in the subroutine calls the Pmtt) function, passing the values of the controls as arguments:

• The first argument is the interest rate. The value entered by the user in the’ , Irate textbox is multiplied by 0.01 so that the value 14.5 (which corresponds to 14.5%) is passed to the Pmtt) function as 0.145. Although we humans prefer to specify interest rates as integers (8%) or floating-point numbers larger’ than 1 (8.24%), the PmtO function expects to read a number less than 1. The value 1 corresponds to 100%. Therefore, the value 0.1 corresponds to 10%. This value is also divided by 12 to yield the monthly interest rate.

• The second argument is the duration of the loan in months (the value entered in the Duration textbox).

• . The ‘third argument is the loan’s amount (the value entered in the Amount textbox). The fourth argument (the loan’s future value) is 0 by definition.

• The last argument must be the value 0 or 1, which specifies when payments . are due. If they are fade early in the month, this value should be O. If they are made at the end of the month, it should be 1.As you know, the Check Box control’s Value property can be either o (if cleared) or 1 (if checked). Therefore, you can pass the quantity PayEarly.Value directly to the PmtO function.

The second line displays the result in the fourth TextBox control, The result is first formatted appropriately with the following statement:

Because the PmtO function returns a precise number, such as 372.2235687646345, you must round and format it nicely before displaying it. Since the bank can’t charge you anything less than a·penny, you don’t need extreme accuracy. Two fractional digits are sufficient. That’s what the Format$O function does. It accepts ”’1 number and a string and formats the number according to an argument you supply (it’s called the formatting string).

To format a number with two fractional digits, you set the formatting string to 1/#.001/. This tells Visual Basic to round the number to two fractional digits and allow away the rest. The integer part of the number isn’t affected. Moreover, if the result is something like 349.4, Visual Basic will format it as 349.40.

Run the application again; and when the Form opens, click the Show Payment button. The result for the loan described. by the initial values of the controls on ” the Form is 689.45. This is the amount you’ll be paying every month over the next four years to pay,.off a loan of $25,000 at 14.5%. Enter other values, and see how a loan’s duration and interest rate affect the monthly payment.

.The code of the Loan project on the CD is different than the one I have presented ‘. here and considerably longer. The statement-discussed in the last paragraph is the bare minimum for calculating a loan payment. The user may enter any values on the Form and cause the program to crash. In the next section, we’ll see how you often validate the data entered by the user, catch errors and handle them gracefully (that is, give the user a chance to correct the data and proceed) .

Validating the Data

If you were to enter a non-numeric value in one of the fields, the program would crash and display an error message. For example, if you entered “twenty” in the Duration textbox, the program would display the error message shown. A simple typing error can crash  the program. This isn’t the way Windows applications should work. Your applications must be able to handle most user errors; provide helpful messages, and in genera), guide the user in running the application efficiently. If a user error goes unnoticed, )four application will either end abruptly, er produce incorrect results without an indication.

-Click the End button, and Visual Basic will take you back to the application’s Code window. Obviously, we must do something a)x)1 it user errors. Applications must be foolproof and not crash with every mistake the user makes. One way to take care of typing errors is to examine each control’s contents, and if they don’t contain valid numeric values, display your.own descriptive message.and give the user another chance. Here’s the revised ShowPaymentClick) subroutine that examines the value of each textbox before attempting to use it in the calculations.

First, we declare three variables in which the loan’s parameters will be stored: LoanAmount, LoanlRate, and Loanlruraiion. These values will be passed to the PmtO function as arguments. Each textbox’s value is examined with an If structure. If the corresponding textbox holds a.valid number..its value is assigned to the numeric variable. If not, the program displays a warning and exits the subroutine without attempting to calculate the monthly payment. IsNumericO is another built-in function that accepts a variable and returns True if the variable is numeric, False otherwise.

If the Amount textbox holds a numeric value, such as 21,000 or 21.50, the function Is Numeric(Amount.Text) returns True, and the statement following it is executed, -: The statement following it assigns the value entered in the Amount textbox to the Loan/amount variable. If not, the Else clause of the statement is executed, which displays a warning in a message box and then exits the subroutine. The Exit Sub statement tells Visual Basic to  top executing the subroutine immediately, as if the End Sub line was encountered.

You can run the revised application and test it by entering invalid values in the fields. Notice that you can’t specify an invalid value for the last argument; the CheckBox control won’t let you enter a value. You can only check or clear it and both options are valid. The LoanCalc application you’ll find on the CD contains this last version with the. error-trapping code.

The actual calculation of the monthly payment takes a single line of Visual Basic code. Displaying it requires another line of code. Adding the code to validate the data entered by the user, however, is an entire program. And that’s the way things are:

Now run the application one last time and enter an enormous loan amount, Try to find out what it would take to payoff our national debt with a reasonable interest rate ID, say, 72 months. The program will crash again (as if you didn’t know). This time the program will go down with a different error message. Visual Basic will complain about an “overflow.”

Actually, the Loan application will crash with a small loan value. Any value greater than 32,.767 will cause an overflow condition. The largest value you can ‘assign to an integer variable is 32,767 (quite small for storing financial figures). As you’ll see in the next section, Visual Basic provides other types of variables, which can store enormous values (making the national debt look really small). In the meantime, if you want to use the loan calculator, change the declaration of the LoanAmount variable to:

Dim LoanAmount.As Single

The Single data type can hold much larger values.

An overflow error can’t be caught with data-validation code. There’s always a chance your calculations will produce overflows or other types of math errors. Data validation isn’t going to help here. We need something called error trapping. Error trapping tells Visual Basic to trap errors and, instead of stopping the program, inform your code that an error has occurred and give your code a chance to handle it. We’ll see how to prevent these types of errors in the next example.

Scroll to Top