Basic Math Operators – Addition

Basic Description


Basic Math Operators – Addition

When you store numbers inside of variables, one of the things you can do with them is mathematical calculations. We’ll start with simple addition. Set up another Sub and call it Add_Numbers. Inside of Sub and End Sub type the following code:

Dim Number_1 As Integer
Dim Number_2 As Integer
Number_1 = 10
Number_2 = 20
Worksheets(1).Range(“A1”).Value = “Addition Answer”
Worksheets(1).Range(“B1”).Value = Number_1 + Number_2

Your coding window will then look like this:


Return to Excel. Select any cells that have numbers in them, then press the Delete key on your keyboard to get rid of them. Now add a new button. From the Assign Macro dialogue box select your Add_Numbers Sub. Change the button text to Addition. Click away from the button to deselect it. Now click the button again. The result should be this (you’ll need to widen the A column):

addition result

We’ve done two things here: we’ve used VBA to add some text inside of cell A1, and we’ve put the result of our addition into cell B1. The line that puts the text into cell A1 is this:

Worksheets(1).Range(“A1”).Value = “Addition Answer”

This time after the equal sign we have some direct text. If you want direct text to the right of the equal sign you need to enclose it between double quotation marks. We have the text Addition Answer between double quotes. The Value of Range A1 on Worksheets(1) is then set to this new text.

The part that does the adding up is this line:

Worksheets(1).Range(“B1”).Value = Number_1 + Number_2

To the right of the equal sign we now have this:

Number_1 + Number_2

We have already stored a value of 10 inside of the variable called Number_1. Inside of the variable called Number_2 we have stored a value of 20. Just like in ordinary mathematics, the plus symbol is used to add up. VBA will add the two values for you and store the answer into the cell B1. You can add up more than two numbers, of course. If we had a third variable, we could have done this:

Worksheets(1).Range(“B1”).Value = Number_1 + Number_2 + Number_3

You can add up numbers that aren’t inside of variables. So this is perfectly fine:

Worksheets(1).Range(“B1”).Value = Number_1 + Number_2 + 30

Or this:

Worksheets(1).Range(“B1”).Value = 10 + 20 + 30

Or you can store your addition in just one variable:

Number_1 = 10 + 20 + 30
Worksheets(1).Range(“B1”).Value = Number_1

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>



clearPost Comment