Sie sind auf Seite 1von 22

Understanding Variables, Conditions & Loops in Excel VBA - A Demo Application using VBA [Part 2 of 5] | Chandoo.

org - Learn Microsoft Excel Online

Back to blogNew? Start hereAboutArchivesChandoo.org Forums

Excel Basics
Advanced Excel
Formulas
Charts
VBA
Excel Dashboards
Project Mgmt.
Power Pivot
Downloads

TrainingProducts

Podcast

Subscribe

Understanding Variables, Conditions & Loops in


VBA [Part 2 of 5]
Posted on August 30th, 2011 in VBA Macros - 51 comments

This article is part of our VBA Crash Course. Please read the rest of the articles in this series by
clicking below links.

1.
2.
3.
4.
5.

What is VBA & Writing your First VBA Macro in Excel


Understanding Variables, Conditions & Loops in VBA
Using Cells, Ranges & Other Objects in your Macros
Putting it all together Your First VBA Application using Excel
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.

http://chandoo.org/wp/2011/08/30/variables-conditions-loops-in-vba/[8/12/2015 3:58:13 PM]

Understanding Variables, Conditions & Loops in Excel VBA - A Demo Application using VBA [Part 2 of 5] | Chandoo.org - Learn Microsoft Excel Online

Now, you are not the kind of boss who micro-manages & nitpicks. So you dont 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 computers memory used to store a value.
Although you dont 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.

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.

http://chandoo.org/wp/2011/08/30/variables-conditions-loops-in-vba/[8/12/2015 3:58:13 PM]

Understanding Variables, Conditions & Loops in Excel VBA - A Demo Application using VBA [Part 2 of 5] | Chandoo.org - Learn Microsoft Excel Online

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


For eg. below are some variables declared in VBA.
Dim
Dim
Dim
Dim
Dim
Dim
Dim
Dim

someNumber As Integer
otherNumber As Double
someText As String
aCondition As Boolean
myCells As Range
myChart As Chart
myList(1 To 10) As String
anotherList() As Variant

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.

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 dont
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.

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 Code

What it does?

someNumber = 2

Stores 2 in to the variable someNumber

someText = Hello

someText has the text value hello

someNumber = someNumber + 1

Increments the value of someNumber by 1

myList(2) = 812

Sets the value of 2nd item in myList array to 812

activeCell.Value = someNumber

Places the value of someNumber in currently selected cell

someNumber = activeCell.Value

Places 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


VBAs 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

http://chandoo.org/wp/2011/08/30/variables-conditions-loops-in-vba/[8/12/2015 3:58:13 PM]

Understanding Variables, Conditions & Loops in Excel VBA - A Demo Application using VBA [Part 2 of 5] | Chandoo.org - Learn Microsoft Excel Online

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")

http://chandoo.org/wp/2011/08/30/variables-conditions-loops-in-vba/[8/12/2015 3:58:13 PM]

Understanding Variables, Conditions & Loops in Excel VBA - A Demo Application using VBA [Part 2 of 5] | Chandoo.org - Learn Microsoft Excel Online

cell.value = cell.value + 1
Next cell

would run 10 times and increment each of the cells 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.

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?


http://chandoo.org/wp/2011/08/30/variables-conditions-loops-in-vba/[8/12/2015 3:58:13 PM]

Understanding Variables, Conditions & Loops in Excel VBA - A Demo Application using VBA [Part 2 of 5] | Chandoo.org - Learn Microsoft Excel Online

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 stores 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, 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 days sales.
Please share your views & ideas using comments. I like to learn from what you share.

Join Our VBA Classes


We run an online VBA (Macros) Class to make you awesome. This class offers 20+ hours of video content
on all aspects of VBA right from basics to advanced stuff. You can watch the lessons anytime and learn at
your own pace. Each lesson offers a download workbook with sample code. If you are interested to learn
VBA and become a master in it, please consider joining this course.
Click here to learn more and Join our VBA program.

Share this tip with your friends

Facebook

12

LinkedIn

Twitter

Google

Email

http://chandoo.org/wp/2011/08/30/variables-conditions-loops-in-vba/[8/12/2015 3:58:13 PM]

Print

Understanding Variables, Conditions & Loops in Excel VBA - A Demo Application using VBA [Part 2 of 5] | Chandoo.org - Learn Microsoft Excel Online

What is VBA & Writing your First


VBA Macro in Excel [VBA Crash
Course Part 1 of 5]

How to use Cells, Ranges & Other


Objects in Excel VBA

Written by Chandoo
Tags: downloads, for each, for loop, if then statement, inputbox,
Learn Excel, macros, no-nl, screencasts, using Ranges, vba classes
Home: Chandoo.org Main Page
? Doubt: Ask an Excel Question

51 Responses to Understanding Variables, Conditions & Loops in VBA [Part 2


of 5]
1.

Veronica says:
August 30, 2011 at 11:08 am
Nice
good explanation simple yet effective. The example was also not complicated..Looking
forward for next part !
Reply

maria says:
February 5, 2013 at 7:10 am
the download file is infected
virus
Reply

Chandoo says:
February 5, 2013 at 8:15 am
@Maria.. this file is perfectly alright. I think you have something else in your computer that
is causing the trouble.
Reply

Hui... says:
February 5, 2013 at 11:08 am
@Maria

http://chandoo.org/wp/2011/08/30/variables-conditions-loops-in-vba/[8/12/2015 3:58:13 PM]

Understanding Variables, Conditions & Loops in Excel VBA - A Demo Application using VBA [Part 2 of 5] | Chandoo.org - Learn Microsoft Excel Online

Why do you say it is infected?


What message are you getting and where is the message from ?

Reply
2.

NickDJ says:
August 30, 2011 at 11:28 pm
Nice example Chandoo! Im looking forward to joining VBA Class; these examples are such a great
teaser! I have a big project at the office Im looking to automate so I cant wait to save the time
Reply

3.

Dev Bhatia says:


August 31, 2011 at 5:03 am
Great.!!! I am a regular reader of your blog. I am new to VBA but you just made it as easy as eating
a cake. Looking forward to your next awesome articles. You guys at Chandoo.org are wonderful.
Reply

4.

Dave says:
August 31, 2011 at 7:27 am
Excellent tutorial with clear explanations of the variables etc.
I would only add some emphasis on the importance of using the
comment lines to track what the code is doing.
This helps a lot if you need to modify it later, or if someone else needs to follow it up after you have
lost the job!
I tend to be rather verbose myself due to short term memory problems
Reply

5.

David says:
August 31, 2011 at 8:27 am
Chandoo, I know its only a sample, but why didnt you indent your code? Makes it easier to read,
especially when youre using conditionals and loops.
I use Smart Indenter (http://www.oaltd.co.uk/indenter/default.htm) to auto-format my code for me.
So far no problems in Excel, and I also use it in MS Project modules and forms as well. Saves me the
headache of trying to format everything by hand.
And ditto to Daves comments: Early on in my career I didnt understand the importance of
commenting, and after having to go back and revise and add new features to old code Im kicking
myself for not commenting as much as I should have.
Reply

6.

Ravi Kiran says:


August 31, 2011 at 3:19 pm
Good post Chandoo. You are very best at teaching.

http://chandoo.org/wp/2011/08/30/variables-conditions-loops-in-vba/[8/12/2015 3:58:13 PM]

Understanding Variables, Conditions & Loops in Excel VBA - A Demo Application using VBA [Part 2 of 5] | Chandoo.org - Learn Microsoft Excel Online

One small error to your notice In the downloadable file Store Number 5 is repeated 7 times. I
hope you can change it an re-upload the file.
Regards,
Ravi.
Reply
7.

mike says:
August 31, 2011 at 6:32 pm
Great work, omg ive always struggled to understand dim, loops and all but this is a wicked example!
KEEP IT COMING
Reply

8.

Guy says:
August 31, 2011 at 10:59 pm
Excellent examples to illustrate what variables/conditions/loops are and what functions they serve.
Good mental model.

Reply
9. How to use Cells, Ranges & Other Objects in Excel VBA [VBA Crash Course - Part 3 of 5] |
Chandoo.org - Learn Microsoft Excel Online says:
September 2, 2011 at 8:49 am
[] Understanding Variables, Conditions & Loops in VBA []
Reply
10.

Arvid Martin says:


September 2, 2011 at 7:50 pm
Im a programmer by traiing, but Fortran and PL/1 were my languages in my day. Any
recommednations on a good VBA reference book or manual.
If I wanted to write applications in VBA outside of Office 2007 or 2010, where do I buy a VBA
compiler, linker or VBA interpretor for Windows 7?

Reply
11. Putting It All Together Our First VBA Application [Part 4 of 5 - Excel VBA Crash Course]
| Chandoo.org - Learn Microsoft Excel Online says:
September 6, 2011 at 9:47 am
[] Understanding Variables, Conditions & Loops in VBA []
Reply
12.

rizzy says:
December 7, 2011 at 12:32 pm
hi,
I have to create a Powerpoint whoes headline should be populated from the column of the XL sheet.
Is this do able? if so could you please guide me. I actually do testing and take test evidence and store
it in the PPT as slides,now i want to populate the step of test from the headline of every slide into the
XL sheet which stores the Test script or from the test script to the PPT headline. which one is

http://chandoo.org/wp/2011/08/30/variables-conditions-loops-in-vba/[8/12/2015 3:58:13 PM]

Understanding Variables, Conditions & Loops in Excel VBA - A Demo Application using VBA [Part 2 of 5] | Chandoo.org - Learn Microsoft Excel Online

executable? i am totally new to macro and have faction of knowledge of it..


Reply
13.

Amy says:
February 8, 2012 at 9:51 pm
Hello,
I read your site daily. It is awesome. I need a VBA macro that will cycle through the options in a
combo box (which you taught me to create), and print the dashboard for each sales manager in the
combo box. Then stop looping. Any chance you can help? Thanks!
Best,
Amy
Reply

14.

Shanmugam says:
May 17, 2012 at 2:47 pm
Good and thanks,
Reply

15.

Siva says:
June 17, 2012 at 10:43 am
Great Tutorial its very useful.
Thanks,
siva
Reply

16.

shivgan joshi says:


September 5, 2012 at 10:25 am
nice explanations
Reply

17.

Mark Saren says:


September 25, 2012 at 7:40 pm
I need help developing a variableloop for the following code please. The two variables are the
personsemail (eMailID)in whichto send the report and the place of service (POSc)to select in a
pivot table of the report. Both variables are in an Excel table range as listed:
For Each POSc In Windows(Constants.xlsx).Sheets(ProvPOS).Range(AR3:AR74)
For Each eMailID In Windows(Constants.xlsx).Sheets(ProvPOS).Range(AU3:AU74)

Workbooks.Open Filename:=I:\Denials Monthly FYTD Resp.xlsx, _


UpdateLinks:=3
Windows(Denials Monthly FYTD Resp.xlsx).Activate
Sheets(DirMgr Resp).Select
ActiveSheet.PivotTables(PivotTable156).PivotFields(POS).ClearAllFilters

http://chandoo.org/wp/2011/08/30/variables-conditions-loops-in-vba/[8/12/2015 3:58:13 PM]

Understanding Variables, Conditions & Loops in Excel VBA - A Demo Application using VBA [Part 2 of 5] | Chandoo.org - Learn Microsoft Excel Online

ActiveSheet.PivotTables(PivotTable156).PivotFields(POS).CurrentPage = _
(POSc.Value)
Sheets(Denials by Catg).Select
ActiveSheet.PivotTables(PivotTable1).PivotFields(POS).ClearAllFilters
ActiveSheet.PivotTables(PivotTable1).PivotFields(POS).CurrentPage = _
(POSc.Value)
Sheets(Top25 Reasons).Select
ActiveSheet.PivotTables(PivotTable2).PivotFields(POS).ClearAllFilters
ActiveSheet.PivotTables(PivotTable2).PivotFields(POS).CurrentPage = _
(POSc.Value)
ActiveWorkbook.SaveAs Filename:= _
H:\Service Payor Mix\Denials FYTD & (POSc.Value) & .xlsx, FileFormat:= _
xlOpenXMLWorkbook, CreateBackup:=False, ConflictResolution:=True
Sheets(Top25 Reasons).Select
Cells.Select
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Range(A1).Select
Sheets(Denials by Catg).Select
Cells.Select
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Range(A1).Select
Sheets(DirMgr Resp).Select
Cells.Select
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Range(A1).Select
Sheets(data).Select
Cells.Select
Selection.ClearContents
Sheets(data).Select
ActiveWindow.SelectedSheets.Visible = False
Sheets(DirMgr Resp).Select
ActiveWorkbook.SaveAs Filename:= _
I:\Denials\Denials FYTD & (POSc.Value) & .xls, FileFormat:= _
xlExcel8, Password:=, WriteResPassword:=, ReadOnlyRecommended:=False _
, CreateBackup:=False
ActiveWorkbook.SendForReview _
Recipients:=(eMailID.Value), _
Subject:=Please review your report: Denials FYTD., _
ShowMessage:=False, _
IncludeAttachment:=True
ActiveWindow.Close

Application.DisplayAlerts = True
Next
Next
End Sub
The above code runs, but does not do what I want it to do, i.e., useeach variable in the range,
POSc, as the pivot table fieldselection POS to create a unique report for each persons eMailID.
Thank you,
http://chandoo.org/wp/2011/08/30/variables-conditions-loops-in-vba/[8/12/2015 3:58:13 PM]

Understanding Variables, Conditions & Loops in Excel VBA - A Demo Application using VBA [Part 2 of 5] | Chandoo.org - Learn Microsoft Excel Online

Mark
Reply
18.

Abdul Aziz Sowe says:


October 11, 2012 at 12:19 pm
Hi,
Thanks for such a great website. It has been very useful to me. I have done an IF formula to
calculate Tax in excel but would like to write it as a UDF in VBA, can anyone help pls? Please see the
formula below. Pls note that if taxable income is 5,751,882 then tax = 1,605,565.
IF(TAXABLE INCOME<=150000,0,IF(TAXABLE INCOME<=450000,0.15*(450000150000),45000))+IF((TAXABLE INCOME-450000)<300000, (TAXABLE INCOME450000)*0.2,60000)+IF((TAXABLE INCOME-750000)>0,(TAXABLE INCOME-750000)*0.3,0)

Reply

Hui... says:
October 11, 2012 at 1:16 pm
Abdul
Try the following:
Function Tax(TI As Double) As Double
If TI <= 150000 Then
Tax = 0
ElseIf TI <= 450000 Then
Tax = 0.15 * (TI - 150000)
Else
Tax = 45000
End If
If TI > 450000 And TI <= 750000 Then
Tax = Tax + (TI - 450000) * 0.2
ElseIf TI > 750000 Then
Tax = Tax + 60000
End If
If TI > 750000 Then
Tax = Tax + (TI - 750000) * 0.3
End If
End Function

To use it copy the code and paste it in a Code Module in VBA


In excel simply use:
=Tax(Value)
or
=Tax(A1)
I hope the logic is correct but you can adjust to suit
Reply

Abdul Aziz Sowe says:


August 3, 2013 at 10:12 am
@Chandoo, I was trying to join VBA Classes but getting a response that my card cannot
be used to pay. I am using a Visa Debit Card from Sierra Leone. Will appreciate your help.
In the meantime, Hui, can you pls help me with a udf to calculate taxable income?
The logic is: taxable income = Gross Salary (Social Security Deduction + 220,000))

http://chandoo.org/wp/2011/08/30/variables-conditions-loops-in-vba/[8/12/2015 3:58:13 PM]

Understanding Variables, Conditions & Loops in Excel VBA - A Demo Application using VBA [Part 2 of 5] | Chandoo.org - Learn Microsoft Excel Online

Looking forward to your response.


Thanks.
Reply
19.

Abdul Aziz Sowe says:


October 11, 2012 at 2:50 pm
Thanks a ton, Hui.
It works perfectly.
Thanks once again. I was wondering, is it possible to do this in Access?
Reply

20.

Rakesh says:
November 6, 2012 at 3:55 am
how is the dollar symbol automatically coming up ???
Reply

RavanReturn says:
July 8, 2013 at 10:40 am
For doing this you need to select you all sheet by pressing ctrl+a.
After that you need to press ctrl+1 at your left side and in the last whenever you will put
numberic figure in that sheet $ symbol autometically shown at the end of figure.
Reply

RavanReturn says:
July 8, 2013 at 10:46 am
SORRY BEFORE YOUR LAST STEP I WAS FORGOTTEN TO TELL YOU THAT WHEN YOU PRESSED
CTRL+1 YOU NEED TO SELECT CURRENCY AND AFTER THAT OK
NOW TRY AGAIN
Reply
21.

Steve says:
February 26, 2013 at 9:11 pm
It would have been much more benefitical to have a step by step tutorial to have us create this actual
example from start to finish.
Reply

22.

Salahuddin Sultan says:


March 22, 2013 at 6:20 am
Perfect, your site is just about perfect
i have a huge data and wish to sort out some desired data out of it
what do you suggest me to use as sorting tool?
i know how to use pivot table but it is not resolving my problem as i have many fields

http://chandoo.org/wp/2011/08/30/variables-conditions-loops-in-vba/[8/12/2015 3:58:13 PM]

Understanding Variables, Conditions & Loops in Excel VBA - A Demo Application using VBA [Part 2 of 5] | Chandoo.org - Learn Microsoft Excel Online

Reply
23.

Ravi Dayal Kumar says:


April 24, 2013 at 1:49 pm
Please Check this, my condition value becoming zero when I run this macros
Dim Revision As Integer
Dim Purpose As String
Application.ScreenUpdating = False
- Removing Border
Selection.Borders(xlDiagonalDown).LineStyle = xlNone
Selection.Borders(xlDiagonalUp).LineStyle = xlNone
Selection.Borders(xlEdgeLeft).LineStyle = xlNone
Selection.Borders(xlEdgeTop).LineStyle = xlNone
Selection.Borders(xlEdgeBottom).LineStyle = xlNone
Selection.Borders(xlEdgeRight).LineStyle = xlNone
Selection.Borders(xlInsideVertical).LineStyle = xlNone
Selection.Borders(xlInsideHorizontal).LineStyle = xlNone
Range(A2).Select
Looping Do Until IsEmpty(ActiveCell)
If Revision = 0 Then
Purpose = C
Else: Purpose = R
End If
ActiveCell.Offset(0, 1).Range(A1).Value = Revision
ActiveCell.Offset(0, 3).Range(A1).Value = Purpose
ActiveCell.Offset(0, 5).Range(A1).Select
Selection.Cut
ActiveCell.Offset(0, -1).Range(A1).Select
ActiveSheet.Paste
ActiveCell.Offset(0, -4).Range(A1).Select
Selection.Copy
ActiveCell.Offset(0, 5).Range(A1).Select
ActiveSheet.Paste
ActiveCell.Offset(1, -5).Range(A1).Select
Loop
Application.CutCopyMode = False
Range(A2).Select
ActiveWorkbook.Save
End Sub
Reply

24.

Sagar says:
June 28, 2013 at 1:24 pm
Hi Chandoo,
Im new to VBA and this example was marvelous. Very simple and made lot of sense in ur
explaination. Would surely go through all the other examples. It was excellent.
Thanks a ton.
Reply

http://chandoo.org/wp/2011/08/30/variables-conditions-loops-in-vba/[8/12/2015 3:58:13 PM]

Understanding Variables, Conditions & Loops in Excel VBA - A Demo Application using VBA [Part 2 of 5] | Chandoo.org - Learn Microsoft Excel Online

25.

vicktor schausberger says:


August 3, 2013 at 1:11 am
How can I loop this little code in A1 I a number to add to A2 answer in Sub learnloop()
Dim aone As Integer
Dim atwo As Integer
Dim athe As Integer
aone = Range(a1).Value
atwo = Range(a2).Value
athe = aone + atwo
Range(A3).Value = athe
If athe < 100 Then
MsgBox ("learn about looping")
End If
End SubA3 in A4 and 5 other two number answer in a6 how loop apply here.
Reply

26.

Loise Galedo says:


August 8, 2013 at 7:34 pm
Good Day,
I need your help/assistance, because I need to do this report filtering only the Start Time and End
Time of each Practitioner.
Report Date Practitioner ID Practitioner Name Start Time End Time
Reply

27.

Steve says:
September 17, 2013 at 6:16 am
Hi Chandoo,
I use Excel spreadsheet a lot and find writing some basic logic statements that will generate a result
for me. For example, in the above example of yours (i.e. 25 stores reporting revenues) I can do that
in Excel spreadsheet using =IF(.).
My question is, how do I convert my knowledge of =IF() into VBA? Where do I start when I have
a different scenario and thus a different =IF() logic?
I am not technical, and am only learning VBA from your tutorials (just finished lesson 1
your site is very helpful. Great Job!
Reply

28.

John says:
September 18, 2013 at 7:06 pm
Chandoo,
Your example spreadsheet does not work in Win.8.
message when I try to save the spreadsheet: Compatability Check; loss of functionality

http://chandoo.org/wp/2011/08/30/variables-conditions-loops-in-vba/[8/12/2015 3:58:13 PM]

; and btw,

Understanding Variables, Conditions & Loops in Excel VBA - A Demo Application using VBA [Part 2 of 5] | Chandoo.org - Learn Microsoft Excel Online

Reply
29.

Saad says:
December 15, 2013 at 9:35 am
how to learn easily coding/programming in VBA in excel which sources is useful
Reply

30.

Saad says:
December 15, 2013 at 9:36 am
Also logic use in VBA and how are we better in vba
Reply

Hui... says:
December 16, 2013 at 5:10 am
@Saad
Programming or making a Model in Excel is effectively the same thing
It is purely the format of the environment and the syntax of the language that you are working
in that is different
You break a problem down into logical steps
where each step or group of steps represents generally a physical or data flow component from
real life
Variables are simply cells (in the Excel Model) or Variables (in VBA) that can hold a value or
string
eg:
In Excel
A1= 10 Sales of Apples
A2= 20 sales of Bananas
A3= A1+A2
=30 Total sales
In VBA
Dim Sales_of_Apples as Double
Dim Sales_of_Bananas as Double
Dim Total_Sales as Double
Sales_of_Apples = 10
Sales_of_Bananas = 20
Total_Sales = Sales_of_Apples + Sales_of_Bananas
=30 Total sales
VBA has a number of tools that allow more effective decision making and repetitive functions or
loops to be performed a lot simpler than can be done using Excel
To learn,
1. Start with small problems and slowly get bigger by introducing new functionality and steps to
your VBA
2. Look at other peoples solutions to problems and ask how/why they did what they did
3. Read a book on VBA, They typically walk you through from the basic steps to advanced steps
in a logical sequence

http://chandoo.org/wp/2011/08/30/variables-conditions-loops-in-vba/[8/12/2015 3:58:13 PM]

Understanding Variables, Conditions & Loops in Excel VBA - A Demo Application using VBA [Part 2 of 5] | Chandoo.org - Learn Microsoft Excel Online

Reply
31.

Kamlesh says:
January 18, 2014 at 7:15 am
Hi Chandoo,
Very good basic understing of VBA and Macro. However I am not clear how this programe will
simulate the Macro.. I am not clear, whether program will run the excel or excel data will create the
programme..? please clarify.
Reply

32.

Eric says:
February 11, 2014 at 3:10 am
Hi,
I was able to go run the macro on my own and it worked. I notice the macro does not store the
values to excel, is this expected? Is there a way I can do this?
Thanks,
Eric
Reply

33.

Naveed says:
March 1, 2014 at 7:19 am
Excellent tutorials Chandoo. I am new to VBA. I was wondering if you want to add another question,
like What is the store number? before putting in the associated sales value, how do you do it?
Reply

34.

Splinkey says:
September 10, 2014 at 3:57 pm
Noob Alert!
Am I the only one who is having an issue with this example.
When i copy this code into VBA for a blank sheet and ensure that the range C7:C30 is as shown in
the Gif
Store NumberSales for the dayReason for Deviation
1
2
3
4
5
6
7
8

when I enter a value for store 1 in the input box, excel overwrites the store number with the value
ive just entered, rather than writing it in the Sales for the Day column and if there is a reason for

http://chandoo.org/wp/2011/08/30/variables-conditions-loops-in-vba/[8/12/2015 3:58:13 PM]

Understanding Variables, Conditions & Loops in Excel VBA - A Demo Application using VBA [Part 2 of 5] | Chandoo.org - Learn Microsoft Excel Online

deviation it gets written to the Sales for the Day column?


I thought I could fix this by editing the line of code
store.Value = InputBox(Sales for Store & storenum)
to
store.Offset(, 1).Value = InputBox(Sales for Store & storenum)
and editing line
store.Offset(, 1).Value = reason
to
store.Offset(, 2).Value = reason
Which sort of worked, but now asks every time Reason for Deviation, regardless of Value?
#stumped
#helpaNoobweek
Reply

Splinkey says:
September 10, 2014 at 4:00 pm
When I say it sort of worked. I mean that it does now correctly write the value to the Sales
for the Day column, but now asks for reason for each store?
Thanks
Reply
35.

Elvis Thabiso says:


October 3, 2014 at 9:43 am
Hi Guys
My name is Elvis I would like to join the group as I do believe that this forum do have some to lean
from, Im using excel vs macros on a daily basis and the best part is that I never attend a formal
course for both of them.
I hope and trust that there is a lot that I still need to learn more with your assistant through this
forum.
Reply

36.

Anurag says:
October 12, 2014 at 1:39 pm
Great work dude!
VBA simplified!!!
Look forward to get more free stuff here
Reply

37.

Ravi says:
October 22, 2014 at 4:10 am
What change would I need to make in the code if I want the popup box to abort itself if I press the

http://chandoo.org/wp/2011/08/30/variables-conditions-loops-in-vba/[8/12/2015 3:58:13 PM]

Understanding Variables, Conditions & Loops in Excel VBA - A Demo Application using VBA [Part 2 of 5] | Chandoo.org - Learn Microsoft Excel Online

cancel button.
Reply
38.

mithun says:
November 27, 2014 at 4:49 am
Dear chandoo team the article is awesome but I need more clarification how I delete blank row within
data & special character.
Reply

39.

subramanya says:
February 19, 2015 at 9:00 am
Hi any body can tell me how to generate a mentor report of many students one by one with the help
of vba code.pls give me the code.
Reply

40.

Vivaan says:
July 25, 2015 at 6:53 am
Respected Sir,
Its really Helpful but as i coming from Telugu Medium Back Ground i am unable to understand
completely so if possible if you provide it Telugu Language also it is very help full to the persons like
me..
Thanks& Regards
Vivaan Kumar
Reply

41.

Pradeep Sahukari says:


July 25, 2015 at 6:55 am
Very Useful..Thank You..
Reply

42.

Justin says:
August 5, 2015 at 8:10 pm
Chandoo you are the man
Reply

Leave a Reply
Name (required)
Mail (will not be published) (required)
Website

http://chandoo.org/wp/2011/08/30/variables-conditions-loops-in-vba/[8/12/2015 3:58:13 PM]

Understanding Variables, Conditions & Loops in Excel VBA - A Demo Application using VBA [Part 2 of 5] | Chandoo.org - Learn Microsoft Excel Online

Submit Comment

Notify me of when new comments are posted via e-mail


Notify me of follow-up comments by email.
Notify me of new posts by email.

What is VBA & Writing your First


VBA Macro in Excel [VBA Crash
Course Part 1 of 5]

How to use Cells, Ranges & Other


Objects in Excel VBA

Name:

Email:

Submit

Meet Chandoo
At Chandoo.org, I have one goal, "to make you awesome in excel and charting". This blog is started
in 2007 and today has 450+ articles and tutorials on using excel, making better charts. Read more.
Connect:
7,521
.

Follow
,

http://chandoo.org/wp/2011/08/30/variables-conditions-loops-in-vba/[8/12/2015 3:58:13 PM]

Chandoo.org

Understanding Variables, Conditions & Loops in Excel VBA - A Demo Application using VBA [Part 2 of 5] | Chandoo.org - Learn Microsoft Excel Online

New to Excel?
1. 100 Excel Tips & Tricks
2. Excel Pivot Tables - Tutorial
3. 51 Excel Formulas in Plain English
4. VLOOKUP Formula for Dummies
5. Free Excel Chart Templates
Advanced Excel Tricks
1.
2.
3.
4.
5.

Excel Dynamic Charts


Learn Conditional Formatting
Making Dashboards using Excel
Project Management with Excel
Working with Excel Tables

Topics & Archives


1.
2.
3.
4.
5.
6.
7.

Learn Excel - Topic-wise


Charting Tips, Tricks and Tutorials
Ask an Excel Question
Best Excel & Charting Tips
Excel Tips, Tricks and Tutorials
Excel & Charting Quick Tips
Free Excel Templates

http://chandoo.org/wp/2011/08/30/variables-conditions-loops-in-vba/[8/12/2015 3:58:13 PM]

Understanding Variables, Conditions & Loops in Excel VBA - A Demo Application using VBA [Part 2 of 5] | Chandoo.org - Learn Microsoft Excel Online

Recently on Chandoo.org
VLOOKUP the last value
Make bar charts in original order of data for improved readability [charting tip]
Declutter your reports by showing icon only
Use shapes to enhance your Excel charts [tip]
Remove duplicate combinations in your data [quick tip]

Chandoo.org Podcast

Latest Episode:

CP041: 6 charts youll see in hell v2.0

About Online Excel


Home
Classes

Project
Management

Dashboards VBA &


Macros

Copyright 2015 Chandoo.org - Our policies & Contact Details

http://chandoo.org/wp/2011/08/30/variables-conditions-loops-in-vba/[8/12/2015 3:58:13 PM]

Excel
Podcast
Templates

Join our Free


News-letter

Das könnte Ihnen auch gefallen