星期五, 九月 02, 2011

Understanding Variables, Conditions & Loops in VBA [Part 2 of 5]

From Chandoo.org

Understanding Variables, Conditions & Loops in VBA [Part 2 of 5]:
This article is part of our VBA Crash Course. Please read the rest of the articles in this series by clicking below links.

What are Variables, Conditions & Loops are and how to use them in Excel VBA


  1. What is VBA & Writing your First VBA Macro in Excel

  2. Understanding Variables, Conditions & Loops in VBA

  3. Using Cells, Ranges & Other Objects in your Macros

  4. Putting it all together – Your First VBA Application using Excel

  5. My Top 10 Tips for Mastering VBA & Excel Macros

In part 2 of our VBA Crash Course, we are going to learn what Variables, Conditions & Loops are and how to use them in Excel VBA.

What are Variables, Conditions & Loops?


If you are new to computer programming, you might think I am speaking legalese. So, to make it easy to understand, lets assume you run a bunch of stores across the town. To make it colorful, lets call your stores “We are nuts” – a dry fruit and nuts store chain. At the end of every day, you call each of the 24 store managers and ask them how much sales they have made in that day.

Now, you are not the kind of boss who micro-manages & nitpicks. So you don’t really note down sale for every store. Instead, as you call the store manager, you just mentally update the total. So first store says “$2,300″ your total is 2300. Second manger says “$4,000″, the total now will be 6300. So on.

The value 6300 here is nothing but a variable.

A Variable is a small chunk of computer’s memory used to store a value.

Although you don’t micro-manage, you are certainly concerned, whenever a “we are nuts” store reports sales that are too low or too high. You then speak with the store manager for few extra minutes to understand what is going and how you can help. Lets just say, this threshold is $500 for low sales and $5000 for high sales. So anytime a manager reports values beyond this limit (500,5000), you spend some time discussing the business and learning what is going on.

This sort of thing is nothing but a condition.

A Condition is a logical check computer performs to test something. For eg. Sales < 500 or Sales > 5000 is a condition.

And now the whole process of each of the 24 store managers calling you and reporting the daily sales is nothing but a loop. They call you everyday and do the same thing.

A Loop is a set of instructions meant to be followed certain number of times.

Understanding Variables, Conditions & Loops in Excel VBA [Part 2 of 5]

Using Variables in VBA


Variables as we learned, are small chunks of computer memory used to store and retrieve a value. We can use them to store numbers, text, ranges of cells, charts or pretty much anything when it comes to VBA.

As with anything else, Variables too have a life span. Some variables die as soon as the SUB in which they are created ends. Some variables (declared at module level) have better life span as they go to gym and eat healthy food.

How to create variables in VBA?


Whenever you want to use a variable, you must create them first. This is your way of telling computer to set aside some memory units so that your variable can be used.

In Excel VBA, you can do this by the DIM statement.

For eg. below are some variables declared in VBA.

Dim someNumber As Integer

Dim otherNumber As Double

Dim someText As String

Dim aCondition As Boolean

Dim myCells As Range

Dim myChart As Chart

Dim myList(1 To 10) As String

Dim anotherList() As Variant

Aside: Should I define my variables?
By default, you can use variables without defining them in VBA. That means, if we write someNumber=12 without writing any DIM statement corresponding to it, your VBA code would still work. But this is not a good practice. Mainly because, if you are not declaring variables, then you don’t know what is available for you to use.

You can force Excel to throw up an error whenever you did not declare variables by adding the statement option explicit at the top of your code.

As you can see, this is almost like plain English. Let us understand 2 of these lines. The rest you can figure out easily.

Dim someNumber as Integer: This line tells Excel that you want to have a variable with the name someNumber which is of the type Integer. This means, you are going to use someNumber variable to store integer values only. Please note that Excel VBA integers are capable of storing values from -32,768 to 32,767 only. If you want to store bigger (or smaller) numbers, you can use the types Long or Double.

Dim myList(1 to 10) as String: This line tells Excel that you want to use a list of values (called as arrays in computer lingo) of String (text) type. The list size is defined to be 10. You can access individual items of the list by using the item number, like this: myList(2) points to second item in the list.

How to use variables in VBA?


Once you have created a few variables, you can use them in your VBA code. A few examples below.































VBA CodeWhat it does?
someNumber = 2Stores 2 in to the variable someNumber
someText = “Hello”someText has the text value hello
someNumber = someNumber + 1Increments the value of someNumber by 1
myList(2) = 812Sets the value of 2nd item in myList array to 812
activeCell.Value = someNumberPlaces the value of someNumber in currently selected cell
someNumber = activeCell.ValuePlaces the value of currently selected cell in someNumber variable

Using Conditions in VBA


Almost everything we do involves making decisions & testing conditions. In the “we are nuts” example, we are testing the condition of sales less than 500 or more than 5000 and then doing something based on that.

You can use various statements in VBA to test for conditions. We will learn the simplest of them. IF and THEN statement.

Using IF THEN Statement in VBA


VBA’s IF Then statement looks almost like plain English. Here is an example to test the Sales condition.

If ourSales < 500 or ourSales > 5000 then

'special instructions to handle too many or too little sales

end if

The above code should be obvious to you by now.

Using ELSE statement in VBA


Just like IF THEN statements are used to test a condition and do something, ELSE is used to do something when the IF condition is failed.

For eg,

If ourSales < 500 or ourSales > 5000 then

'special instructions to handle too many or too little sales

Else

'Note down the sales & move on

end if

Would just note down the sales figures if the sales are between 500 and 5000.

Using Loops in VBA


A Loop is a set of instructions meant to be followed specific number of times, as defined earlier. In “we are nuts” example, we are calling and asking for sales 24 times. That means we are doing the same set of operations (call, ask for sales, if the sales are too low or too high do something, hang-up) 24 times, in a loop.

In VBA, there are several different ways to write loops. We will see the easiest type of loop today. For more, please consider joining our Online VBA classes.

Using FOR Loop in VBA


A for loop repeats a set of VBA instructions any given number of times. For eg.

For storeNumber = 1 to 24

'call the store

'ask for sales figures

'do something if needed

'hang up

Next storeNumber

Would run for 24 times and each time repeats the same 4 steps (call, ask, do, hang-up).

Using FOR EACH Loop in VBA


FOR EACH is a special type of loop in Excel used to run same instructions for each of the various items in a list.

For example,

For Each cell in Range("A1:A10")

cell.value = cell.value + 1

Next cell

would run 10 times and increment each of the cell’s values by 1 in the range A1:A10.

Putting it all together – a Simple VBA Program to Note Down Sales of 24 stores


Now that you have learned 3 key ingredients of VBA – Variables, Conditions & Loops, its time we put them together to do a small VBA program.

A Demo of our Daily Sales Log VBA Application


Before we jump in to the code, lets just take a look at how it would work. I have shown it only for 5 stores. But it works for 24.

Using Variables, Conditions & Loops in Excel VBA - A demo

The Code behind our Daily Sales Log VBA Application


Here is the code that captures the sales of 24 stores whenever you click on the “Capture Sales” button.

Sub captureSales()

'when you run this macro, it will take the sales of all the 24 stores we own

'it will ask for a reason if the sales are too low or too high


Dim storeNum As Integer

Dim reason As String

Dim store As Range


storeNum = 1

For Each store In Range("C7:C30")

store.Value = InputBox("Sales for Store " & storeNum)

If store.Value < 500 Or store.Value > 5000 Then

reason = InputBox("Why are the sales deviated?", "Reason for Deviation", "Reason for Deviation")

store.Offset(, 1).Value = reason

End If

storeNum = storeNum + 1

Next store

End Sub

How this code works?


By now, you are already familiar with various parts of this code. So I will just explain the alien portions.


  • Dim statements: These lines declare the variables we are going to use. Notice the different data types (Integer, Range etc.) we have used for various types of data we want to hold.

  • For Each store In Range(“C7:C30″): This line is going to tell excel that for each store (ie cell) in the range C7:C30, we need to repeat the instructions all the way until Next Store. In our case, Excel is going to repeat for 24 times.

  • store.Value = InputBox(“Sales for Store ” & storeNum): This line shows a small box to you and asks for your input. You can enter a number and press OK (or enter). Whatever value you enter will be placed in current store’s cell.

  • reason = InputBox(“Why are the sales deviated?”, “Reason for Deviation”, “Reason for Deviation”): This line shows a box to user with a title and default value (Reason for deviation).

  • store.Offset(,1).value = reason: This statement places the reason for sales deviation in to the cell right to the store sales. Offset(,1) does the trick here.

Download Example Workbook & Learn about Variables, Conditions & Loops in VBA


Click here to download the example workbook and learn more about variables, conditions & loops in VBA.

What Next – Understanding Cells, Ranges & Other Objects in VBA


In the part 3 of this tutorial, we will learn how to use cells, ranges & other objects from VBA. Stay Tuned.

If you have not read, please read the first part of this series – Introduction to Excel VBA – What is it & How to write your first VBA Macro.

How do you like this Example?


How do you like the VBA examples shown in this article? How would you enhance the macro to do more? One idea is to add another button to clear previous day’s sales.

Please share your views & ideas using comments. I like to learn from what you share.

Join Chandoo.org’s VBA Classes


We run an online VBA (Macros) Class every 3 months. We just finished our first batch and it was an awesome experience for both students & teachers (Vijay, Hui and I teach this course). Now, we are opening the enrollments for 2nd batch of VBA classes from September 5th, Monday. If you are interested to learn VBA and become a master in it, please consider joining this course.

Click here to learn more about our VBA program.


没有评论: