Computer Learning Zone CLZ Access Excel Word Windows

The cure for boredom is curiosity. There is no cure for curiosity.

-Dorothy Parker
 
Home   Courses   TechHelp   Forums   Help   Contact   Merch   Join   Order   Logon  
 
Home > Courses > Visual Basic > VB 6 > 101 > Lesson 06 < Lesson 05 | Lesson 07 >
Calculator 2

Lesson 6: Add, Subtract, Multiply, Divide Buttons


 S  M  L  XL  FS  |  Slo  Reg  Fast  2x  |  Bookmark 

In this lesson, we will expand our simple calculator to support subtraction, multiplication, and division in addition to addition. We will walk through adding and configuring new buttons for each operation, updating their properties, and writing the corresponding code. I will show you how to address runtime errors like division by zero with proper error handling using IF statements and show how to display a user-friendly message. We will also discuss saving your program, working with the code window, and the importance of keyboard shortcuts when working with Visual Basic projects.

Navigation

Keywords

, Visual Basic calculator, VB calculator code, addition subtraction multiplication division VB, error handling VB, division by zero VB, IF THEN statement VB, MsgBox VB, control array VB, save project VB, runtime errors VB, keyboard shortcuts VB

 

Start a NEW Conversation
 
Only students may post on this page. Click here for more information on how you can set up an account. If you are a student, please Log On first. Non-students may only post in the Visitor Forum.
 
Subscribe
Subscribe to Calculator 2
Get notifications when this page is updated
 
Intro In this lesson, we will expand our simple calculator to support subtraction, multiplication, and division in addition to addition. We will walk through adding and configuring new buttons for each operation, updating their properties, and writing the corresponding code. I will show you how to address runtime errors like division by zero with proper error handling using IF statements and show how to display a user-friendly message. We will also discuss saving your program, working with the code window, and the importance of keyboard shortcuts when working with Visual Basic projects.
Transcript In the last lesson, we made a simple calculator, but all our simple calculator can do is add two numbers together. In this lesson, we are going to make it capable of subtraction, multiplication, and division.

Now, before we go too far, we forgot to save our program in the last lesson, did we not? That can be a problem, especially if the power goes out or someone comes along and spills coffee on your keyboard, as has happened to me on a couple of occasions. Well, I still spill coffee on my keyboard on a couple of occasions. One time, the computer actually went up in smoke. We will talk about that later.

Let's go ahead and save our program by clicking on the Save button. Here we are. Notice we are still in our VB files folder. Let's save the form. I am going to call this "Simple Calculator." I will hit Save. We can also save the project as Simple Calculator, simple cal, or, but do not save it as simply "Calculator." That is all right, and that is bad. Make sure you just click and save here, and it will save it as a VBP file, a Visual Basic project file.

It is okay to have the form and the project named the same thing, especially if you only have one form in a project, like these simple programs that we are writing today.

Now, so far, our calculator only does addition. We have a Calculate button here, but Calculate only does addition. So, let's change this button, first of all, so the caption says Add. Then we will make more buttons that do Subtract, Multiply, and Divide.

So, let's click on this button and get to its properties. We can leave the name alone. "CalculateButton" is fine. We do not have to worry about changing it to something else, although we should. But let's change Caption down here to Add. Now this button says Add. In fact, let's make it a little bit smaller. There we go.

Now, let's add another button over here to subtract. I will just copy and paste this button. Copy and paste. Do you want to create a control array? I will say No. Here is our other button. I am going to slide it down here. Let's change this one's name to "SubtractButton." Now I will put the caption "Subtract" on it.

Now, let's see its code. Double click on the Subtract button. Here we are inside our code window again. I am going to hit Enter. This time, it is going to be very simply:

answer = val(firstNumber) - val(secondNumber)

Could I have copied and pasted that and just changed the operation? I want to type it in again so you can see exactly how it looks.

Let's go ahead and try it. Let's run our program. 7.5 and 9. Add. I get 16.5. Subtract. I get -1.5. Perfect. Our Add and Subtract buttons are working perfectly.

Let's add two more real quick. Let's add Multiply and Divide. I will close the program. I am going to close the code window for now. That will put us back here.

Now, let's copy and paste two more buttons. Copy. Paste. Control or I, No. And paste again. Control or I, No. Let's move these over here. I will teach you how to better deal with control arrays in a future class.

Now, let's change the properties of these buttons. This one is going to be named "MultiplyButton." Its caption will be "Multiply." Click on the next button. This one will be "DivideButton" with a caption of "Divide."

Now double click on these buttons to adjust the code. I have double clicked on the Multiply button. Now notice I am between the other two buttons. That is because Visual Basic arranges the Private Sub names alphabetically. Notice I have CalculateButton, then MultiplyButton, then SubtractButton. But the code for these is going to be real easy.

What I will do is highlight this one. I will copy it. I am going to use my keyboard this time. Ctrl+C for copy. Now I will click down here and paste it. Paste is Ctrl+V as in Victor. Those are my keyboard shortcut tricks. I use these keyboard shortcuts all the time. Ctrl+C is copy. Ctrl+X for cut. Ctrl+V for paste. Ctrl+S for save. Get familiar with these keyboard shortcuts.

So, I pasted this line of text in here and now I will change this to multiplication, which is the asterisk. It is usually over the 8 key on the keyboard. Shift+8 is the asterisk for multiply.

Now, if you can see both windows, both your form and your code window on the screen, all you have to do to flip the screen is click on the form window.

Now double click on the Divide button and that will put you in a new Private Sub back in the code window for divide. Now watch this. All I have to do is paste, Ctrl+V, because that code that we copied earlier is still in the Windows clipboard. If you need to know more about the Windows clipboard, again, get your hands on our Windows Basics and our Microsoft Word Basics. I spend a lot of time covering cut, copy, and paste and the clipboard in those classes.

Division is a forward slash. The value of the first number divided by the value of the second number.

All right, let's go ahead and save our program and run it. I will type in some numbers like 50 and 10. Let's add them. It is 60. Subtract them. It is 40. Multiply. There is 500. And divide. There is 5.

Beautiful.

Let's try some other stuff. Let's change this from 10 to 0. Add. Subtract. Multiply. Divide. There is an error.

Now, this is not a compile error. This is not a syntax error in our code. Our code is fine. What we have here is a runtime error.

There are two kinds of errors you are going to get. Syntax errors are generally compile-time errors. In other words, when the program gets put together before it actually runs, the Visual Basic program looks at it and says, hey, this is not right. I cannot run your program. Something is wrong here. Those are the easy ones to find.

Then you have your runtime errors. Runtime errors are the nasty ones. These are errors in the logic of your code. They do not usually show up until you start running your program. Sometimes they are buried deep, so they do not even show up right away. We have released software commercially that has had runtime errors in it. Even Microsoft has released software that has had runtime errors in it.

This is an easy one to fix. It says division by zero. Basically, you violated a math rule. You cannot divide by zero.

What can we do? We can either end the program or debug the program. We are going to spend a lot of time in one of the future classes going over debugging. It is a whole class in and of itself.

Let's go ahead and click on the Debug button. I will show you what it looks like. Here we are. Essentially, it brings us into the code that generated the error. If you hold your mouse pointer over any of these, you can see what the value of these different variables are. Answer is zero. First number is 50. Second number is zero. That should be enough right there to tell you that we have a problem.

What we are going to do at this point is stop our program. Our program is technically still running. Here is the Start button. You will notice that over here is an End button. Click on the End button and it will stop the program.

Now, there are two ways we can fix this error. The first way is to simply have Visual Basic ignore any errors and continue moving. That is what I like to call the easy, cheesy way out of it.

Here is the easy, cheesy way. Come up in front of this line of code. I am going to click up here. Press Enter to give me a blank line and then Tab in. I am going to type in:

on error resume next

What does that do? Basically, it says if you encounter an error while running the subroutine, ignore it and move on to the next line. In this case, there is no next line, but it will basically not generate an error.

Let's see how that works. Let's run the program. I will type in 2 and 0 and hit Divide. Nothing happens.

Like I said, it was easy, but it is cheesy. There is nothing telling the user they cannot divide by zero. It would be nice if we could generate our own little error message.

Let's stop the program. There are a couple of ways to do this. I do not want to get too deeply into error checking and error handling in today's class. Let's get rid of this "on error resume next." Delete.

Let's put in a couple of extra blank lines.

What I would like to do is handle this error myself. The way we are going to do that is we are going to look at the denominator, the second number. We are going to see if it is equal to zero before we try dividing it. If it is zero, we will pop up a message box that says "You can't divide by zero." If it is not zero, we will let it do the math.

In order for this to work, we have to make Visual Basic smart. We have to make Visual Basic look at the value and make a decision as to what to do. If this is zero, pop up the error message and get out of the subroutine.

How do we do it? We are going to use a new function called IF. We are going to use an IF THEN statement. Here is how it works.

Let's tab over. I am going to type in:

If secondNumber = 0 Then
MsgBox "You can't divide by zero."
Exit Sub
End If

Now, what is all this? Let's take a look at it line by line.

IF - we are going to check a value. If the value of the second number is equal to zero, then do some stuff. We are going to do all the stuff between the IF statement and the END IF statement. You can put any number of lines you want in here.

What is the stuff? MsgBox, as we know. MsgBox "You can't divide by zero." Exit Sub means get out of dodge. Exit Sub, you are done. Do not continue on down here. Let's check the number. If it is equal to zero, let's pop the message and exit the subroutine; otherwise, it will continue running. It will come down here and do the math.

Let's save our program. I like to save my work often.

Let's run it and see what we get. Here we go. 5 and 0. Divide. Oh, "You can't divide by zero." Look at that. Is not that nice? We will hit OK. Let's try something with an actual value in here. Let's put a 2 in there. Divide. I get 2.5.

Let's close our program.

Now, you know how to make your basic program smart with an IF statement. If something, if the value of the second number is zero, then do this stuff.
Quiz Q1. What is the primary function of the calculator program described in the lesson?
A. To perform addition, subtraction, multiplication, and division on two numbers
B. To create a graphical report
C. To manage a database of users
D. To generate random numbers

Q2. When should you save your project in Visual Basic according to the lesson?
A. Only after you finish writing all the code
B. Before you make any changes to the form
C. Frequently, to prevent loss of work due to errors or accidents
D. Only after executing the program without errors

Q3. Why is it not recommended to name your project simply "Calculator"?
A. It is too short and may conflict with system file names
B. It will not save properly in Visual Basic
C. It automatically deletes the file after saving
D. It is a reserved keyword and will crash Visual Basic

Q4. What property is changed to alter the text displayed on a button in Visual Basic?
A. Name
B. TextBox
C. Caption
D. Value

Q5. What is the correct symbol for multiplication in Visual Basic code?
A. %
B. x
C. /
D. *

Q6. What happens if you try to divide by zero in the calculator program without error handling?
A. The program produces the correct answer
B. The program displays a syntax error message
C. The program crashes with a runtime error
D. The program automatically sets the answer to zero

Q7. What type of error occurs when you attempt to divide by zero in the program?
A. Compile-time error
B. Syntax error
C. Runtime error
D. Formatting error

Q8. Which statement is used in Visual Basic to allow the program to ignore errors and continue?
A. On error resume next
B. Ignore error
C. Continue on error
D. Error ignore

Q9. What is the disadvantage of using "On error resume next" for error handling in this context?
A. It makes the program stop whenever there is an error
B. It prevents the addition function from working
C. The user is not notified when an error like divide by zero occurs
D. It deletes all the input values

Q10. How can you display a custom message to the user when they try to divide by zero?
A. Use a MsgBox inside an If statement checking if the denominator is zero
B. Use a print statement at the end of the code
C. Save and close the project
D. Automatically restart the program

Q11. What does the Exit Sub statement do in Visual Basic?
A. Repeats the subroutine
B. Ends the current subroutine immediately
C. Closes the entire program
D. Clears all variables

Q12. What programming structure is used to check if the denominator is zero before dividing?
A. FOR loop
B. WHILE loop
C. IF THEN statement
D. SELECT CASE

Q13. When coding the button events, why might the code for each operation look similar?
A. Because each math operation requires a different data type
B. Because only the operator symbol usually changes for each function
C. Because each needs a unique and lengthy code block
D. Because buttons share the same code by default

Q14. What Visual Basic function converts a text box value into a numeric value for calculations?
A. Parse()
B. numerate()
C. val()
D. convertText()

Q15. According to the lesson, which keyboard shortcuts are useful for copying, pasting, and saving in Windows?
A. Ctrl+P for paste, Ctrl+C for cut, Ctrl+A for save
B. Ctrl+C for copy, Ctrl+X for cut, Ctrl+V for paste, Ctrl+S for save
C. Alt+C for cut, Shift+V for paste, Ctrl+S for screenshot
D. Ctrl+P for print, Ctrl+Z for delete, Ctrl+R for redo

Answers: 1-A; 2-C; 3-A; 4-C; 5-D; 6-C; 7-C; 8-A; 9-C; 10-A; 11-B; 12-C; 13-B; 14-C; 15-B

DISCLAIMER: Quiz questions are AI generated. If you find any that are wrong, don't make sense, or aren't related to the video topic at hand, then please post a comment and let me know. Thanks.
Summary Today's video from the Visual Basic Learning Zone picks up where we left off with our simple calculator project. Previously, we built a calculator that could only perform addition. In this lesson, we will expand its functionality so it can handle subtraction, multiplication, and division as well.

Before adding new features, I want to address an important habit for every programmer: saving your work. If you lose power or something happens to your computer, you could lose all your progress if the project isn't saved. I've had the unfortunate experience of losing work to a spilled cup of coffee, and, let me tell you, it's not fun. So, make a habit of saving your work often. I recommend saving both your form and the project file. It's perfectly fine to name them both the same if you're only working with a single form, like we are in these introductory projects.

Up to this point, our calculator's Calculate button performs only addition. Let's start by changing the caption on that button to "Add" to make its purpose clear. We will also create additional buttons for subtracting, multiplying, and dividing. To do this, it's easiest to simply copy and paste the existing Add button, then rename each new button according to its function and update the caption text as needed.

Once the Subtract button is ready, you'll need to add some code behind it. The operation is very straightforward: you just subtract the second input from the first and assign the result to your answer variable. You could copy and paste code from the Add button and modify it, but for demonstration it's useful to type it out so it's clear which line performs the subtraction.

Now, when you run your program, you can enter two numbers and click Add to get their sum, or Subtract to find the difference. Both functions should work as expected.

Next, let's add buttons for Multiply and Divide. Again, copy and paste one of your existing buttons, rename them accordingly, and set the captions to "Multiply" and "Divide" so the interface is user-friendly.

For the multiplication code, you only need to change the operator to an asterisk. When programming, keyboard shortcuts like Ctrl+C (copy), Ctrl+X (cut), Ctrl+V (paste), and Ctrl+S (save) can save a lot of time, so I suggest practicing those until they become second nature.

For division, simply update the operator to a forward slash. With these changes in place, your calculator can now add, subtract, multiply, and divide any two values.

After saving your progress, run the calculator and test all four operations with some sample numbers to ensure they're working properly. Try entering values like 50 and 10 to confirm the results.

However, if you try to divide by zero, you'll encounter a runtime error. This is different from a compile-time or syntax error, which occurs when your code is invalid and cannot be run. Runtime errors, on the other hand, occur during program execution and often stem from logic problems or invalid operations, like dividing by zero. These can be harder to find because they may not trigger until a very specific situation arises.

When this division by zero error occurs, you can use debugging tools to inspect the state of your variables and see exactly when the problem arises. In this case, you'll notice that the second number is zero and division is not valid.

There are a couple ways to avoid this crash. One quick way is to add an instruction to simply ignore any errors and continue executing. While this is easy, it's not the ideal solution since it leaves the user without any feedback.

Instead, a better approach is to check the denominator before performing the division. Using a conditional statement, you can detect if the second number is zero. If it is, display a message to the user informing them that division by zero is not possible, then exit the routine so no division attempt is made. The advantage to this method is that the user receives clear feedback on what's wrong and the program doesn't just silently fail.

Be sure to save your work regularly as you make these changes. Once completed, run your program and test the division function with a denominator of zero to verify that your error message appears as expected. Then test with a valid denominator to confirm that division works when it should.

With this approach, you've made your calculator smarter and more user-friendly. Now you have a basic understanding of using conditional statements like IF to control the flow of your program based on user input.

If you'd like to see a complete video tutorial with step-by-step instructions on everything discussed here, visit my website at the link below. Live long and prosper, my friends.
Topic List Saving your Visual Basic project and form
Renaming and organizing buttons in Visual Basic
Adding Add, Subtract, Multiply, and Divide buttons
Writing code for subtraction functionality
Writing code for multiplication functionality
Writing code for division functionality
Understanding runtime errors in Visual Basic
Handling division by zero errors
Using IF THEN statements for error checking
Showing message boxes for errors
Exiting a subroutine with Exit Sub
Keyboard shortcuts for copy, paste, cut, and save in Windows
Article In the last lesson, we built a simple calculator program in Visual Basic that could add two numbers together. Now, we will expand that calculator to handle subtraction, multiplication, and division as well. Before we dive in, it is important to remember to save your work regularly. Imagine losing your code because you forgot to save and something happened to your computer. To prevent this, always save your project as soon as possible. Click the Save button in Visual Basic, make sure you are in your VB files folder, and choose a clear name for your form and project. For example, you can call your project "Simple Calculator." Saving both the form and the project with the same name is fine, especially if you are working with just one form.

Currently, our calculator only adds numbers when we click the Calculate button. Instead of using a generic Calculate button, let us change that to say Add, and then create separate buttons for subtracting, multiplying, and dividing. Select your Calculate button and find its properties. The name "CalculateButton" can stay the same, but change the Caption property to "Add." Adjust the size if you need to.

Next, add more buttons for the other operations. The fastest way is to copy and paste your Add button. When asked if you want to create a control array, choose No. Place the new button where you want it, then change its name to "SubtractButton" and the caption to "Subtract." For the code, double click the Subtract button to open the code window.

Inside the Subtract button's click event, type the following line:

answer = val(firstNumber) - val(secondNumber)

This will subtract the second number from the first and store the result in the variable called answer. Now, if you run your program and enter values like 7.5 and 9, clicking Add will give you 16.5, and clicking Subtract will give you -1.5.

To add multiplication and division, repeat the process to make two more buttons by copying and pasting. Name one button "MultiplyButton" with a caption of "Multiply," and name the other "DivideButton" with a caption of "Divide". Double click each button to bring up its code. For multiply, use this line:

answer = val(firstNumber) * val(secondNumber)

The multiplication operator in Visual Basic is the asterisk symbol (*), which is usually Shift+8 on your keyboard. For divide, the code should be:

answer = val(firstNumber) / val(secondNumber)

The division operator is the forward slash (/).

After you have set this up, save your program, run it, and try different numbers. For example, using 50 and 10, Add will show 60, Subtract will show 40, Multiply will show 500, and Divide will show 5.

However, if you change the second number to 0 and try to divide, you will encounter a runtime error. This is not a syntax error, which usually happens before the program runs. Instead, it is an error that happens while the program is running, because dividing by zero is not allowed in math. Visual Basic will bring up an error message and give you the option to debug.

To prevent this error, you need to handle this situation in code. One quick fix is to use "on error resume next" before your division line. This tells Visual Basic to ignore any errors and continue running. If you try dividing by zero with this in place, nothing happens and you do not get any feedback. While this avoids the error, it does not warn the user, which is not ideal.

A better approach is to check if the second number is zero before trying to divide. You can use an If Then statement to do this. Remove "on error resume next" and instead, add the following code in your Divide button's click event before performing the division:

If secondNumber = 0 Then
MsgBox "You can't divide by zero."
Exit Sub
End If

This code checks if the value of secondNumber is zero. If it is, it shows a message box saying "You can't divide by zero" and then exits the subroutine using Exit Sub, so the division does not happen. If the second number is not zero, the program will continue and perform the division as normal.

After adding this check, save your program and run it again. Enter 5 and 0, then click Divide. This time, you see the message box warning you about dividing by zero, and the program continues smoothly. Change the second number to something else, like 2, and Divide will give you the correct answer.

Now you know how to expand your calculator to handle all four basic arithmetic operations and how to make your program smarter by using If Then statements for error handling. This makes your application more user-friendly and robust. Remember to save your work regularly and test different scenarios to ensure everything works as expected.
 
 
 

The following is a paid advertisement
Computer Learning Zone is not responsible for any content shown or offers made by these ads.
 

Learn
 
Access - index
Excel - index
Word - index
Windows - index
PowerPoint - index
Photoshop - index
Visual Basic - index
ASP - index
Seminars
More...
Customers
 
Login
My Account
My Courses
Lost Password
Memberships
Student Databases
Change Email
Info
 
Latest News
New Releases
User Forums
Topic Glossary
Tips & Tricks
Search The Site
Code Vault
Collapse Menus
Help
 
Customer Support
Web Site Tour
FAQs
TechHelp
Consulting Services
About
 
Background
Testimonials
Jobs
Affiliate Program
Richard Rost
Free Lessons
Mailing List
PCResale.NET
Order
 
Video Tutorials
Handbooks
Memberships
Learning Connection
Idiot's Guide to Excel
Volume Discounts
Payment Info
Shipping
Terms of Sale
Contact
 
Contact Info
Support Policy
Mailing Address
Phone Number
Fax Number
Course Survey
Email Richard
[email protected]
Blog RSS Feed    YouTube Channel

LinkedIn
Copyright 2026 by Computer Learning Zone, Amicron, and Richard Rost. All Rights Reserved. Current Time: 6/30/2026 6:01:19 AM. PLT: 1s
Keywords: , Visual Basic calculator, VB calculator code, addition subtraction multiplication division VB, error handling VB, division by zero VB, IF THEN statement VB, MsgBox VB, control array VB, save project VB, runtime errors VB, keyboard shortcuts VB  PermaLink  How To Add Subtract Multiply and Divide with Buttons and Error Handling in Visual Basic