Calculate
Let's develop a small macro which involves a simple calculation (adding a value to a variable) and a very important programming technique.
Place a command button on your worksheet and add the following code lines:
x = Range("A1").Value
x = x + 1
Range("A1").Value = x
1. The first code line declares a variable with name x of type Integer.
2. Next, we initialize this variable with the value of cell A1.
3. We want to add 1 to the variable x. You can do this by adding the line 'x = x +1'. In Excel Visual Basic (and in other programming languages), the symbol '=' means becomes. It does not mean equal! So x = x + 1 means x becomes x + 1. In other words: take the present value of x and add 1 to it. Example: If x = 6, x becomes 6 + 1 = 7.
4. Finally, place the variable with the new value into cell A1.
Exit the Visual Basic Editor and enter a value into cell A1. Click on CommandButton1 to see how the value of cell A1 is incremented each time you click on CommandButton1.
Result:



You've just created a counter in Excel VBA. Well done!
Did you find this information helpful? Show your appreciation, vote for us.
Go to Top: Calculate | Go to Next Topic: If Then Statement