SlideShare une entreprise Scribd logo
1  sur  106
 HOW TO’S
 EXCEL FORMULAS
 VBA IN EXCEL
 INTERESTING
 OTHERS
Excel IF Statement – How to Use
IF Statement is one of the most popular instructions among the Decision Making statements. IF
Statement gives the desired intelligence to a program, so that it can take decisions based on a
criteria and most importantly decide the program flow.
In Microsoft Excel, IF Statements can be quite useful for evaluating an expression (expressions
can be both Mathematical as well as Logical) and giving an output based on it.
Definition of IF Instruction:
According to Microsoft Excel, IF statement is defined as a function which “checks whether a
condition is met, returns one value if True and another value if False”.
In plain simple English IF function is an instruction that checks any condition, if the condition is
found to be TRUE then it returns a predefined value however if the condition is False, it returns a
different predefined value.
Syntax of Excel IF Statement:
The syntax of If Function in Excel is as follows:
=IF (Logic_Test, Value_if_True, Value_if_False)
Here, ‘Logic_Test’ refers to the expression that is to be evaluated.
‘Value_if_True’ is the output of IF Statement if the ‘Logic_Test’ is TRUE.
‘Value_if_False’ is the output of IF Statement if the ‘Logic_Test’ is FALSE.
Few Important points about IF Functions:
 If function only results one value out of ‘Value_if_True’ and ‘Value_if_False’. Both the
values cannot be returned at the same time.
 Nesting of IF statements is possible but Excel only allows this till 64 Levels.
 IF function throws a #Name? error if the expression that you are evaluating is invalid.
Examples of Excel IF Statement:
Now, let’s move to the practical examples and use of IF function.
In the below Example:
Example 1:
The scores of some students are given in a table along with their names. Now for finding the
Result of these students, we can use an IF statement. As you can see in the above image I have
also defined the Pass and Fail criteria for these students.
Sores above 50 are considered PASS, while scores that are below or equal to 50 are considered
FAIL. In this scenario we can use a formula:
=IF(B2<=50,"Fail","Pass")
Now, what this means. This formula means that first we are comparing the number at B2 i.e. 37
(Score of First Student) with our condition. This expression boils down to (37 <= 50) i.e. Is 37
less than or equal to 50, which is True. Hence the result will be ‘Value_if_True’ (second
parameter of if statement) i.e. “Fail”.
Similarly, for the second student the formula will be: =IF(B3<=50,"Fail","Pass")
Example 2:
In the second example an Employee Salary table of a company is shown. We have to calculate
the bonus for these employees. As you can see in the image the company has a strange criteria
for giving bonus to their employees.
The criteria is, if the employee salary is greater than or equal to $ 8000 then bonus will be 15%
of the salary otherwise the bonus will be 10% of the salary.
In this scenario we can use the Excel if Statement as: =IF(C2>=8000,C2*15%,C2*10%)
In this formula, first of all we check if the salary of first employee (in C2 cell) is greater than or
equal to 8000. If this is true then the formula evaluates an expression (C2 * 15%) otherwise the
result should be calculated by the expression (C2 * 10%).
As the salary of the first employee satisfies the condition i.e. (9,735 >= 8000). So, the result of
this formula is (9,735 x 15%) which comes out to be $ 1460.25.
Similarly for the third employee the formula can be: =IF(C4>=8000,C4*15%,C4*10%)
Recommended Reading: Nested If Conditions in Excel
Use of Logical Operators along with IF Statement:
Excel If Statement can also be used along with the logical operators (like AND, OR) for
analysing complex logics. Here I will help you to understand how can these operators be used
with IF function.
Operator Explanation
AND AND function only results into ‘True’ when all the conditions inside it are met.
OR OR Function results into ‘True’ when any one of the conditions is met.
The syntax of AND Function in Excel is: =AND(Logic1, Logic2, logic_n)
The syntax of OR Function in Excel is: =OR(Logic1, Logic2, logic_n)
Now let’s move to an example to understand how these functions can be used along with the IF
function.
Example 3:
In this example, another company wants to give bonus to its senior employees. The company
comes up with a criteria that any employee who has at-least 5 years of experience (5 years or
more) and whose salary is greater than 12000 will be considered a senior employee. And such an
employee will be eligible for a bonus equal to 20% of salary.
In such a scenario you cannot create an IF statement without using a logical operator. So, in this
scenario we can create the if statement as:
=IF(AND(C2>=5,D2>=12000),D2*20%,"No Bonus")
Here, in the AND function we have used two conditions, i.e. if C2 (Experience of 1st Employee)
is greater than or equal to 5 and if D2 (Salary of 1st Employee) is greater than or equal to 12000.
If both these condition are ‘True’ then only the output of AND will be ‘TRUE’ if any one of the
value is ‘FALSE’ then AND Function will result into ‘FALSE’
In this example for the first employee the experience is 6.4 years but the salary is less than
12000. So, the first employee won’t be eligible for any bonus.
Recommended Reading: VBA IF Statement With Examples
In the same way you can find out if all other employees are applicable for bonus or not.
Filed Under: Formulas Tagged With: Excel All Versions
About Ankit Kaul
Ankit is the founder of Excel Trick. He is tech Geek who loves to sit in front of his square headed girlfriend
(his PC) all day long. :D. Ankit has a strong passion for learning Microsoft Excel. His only aim is to turn you
guys into 'Excel Geeks'.
Learn Excel with Us!
 Excel VLOOKUP Tutorial
 Microsoft Excel IF Statement
 Excel Web App Viewers
 What is Excel VBA
 HLOOKUP - Excel Formula Training Session
 Spell Check In Excel
 Top 50 Excel Based Games
 Microsoft Excel Shortcuts And Functions Keys
 Excel SUMIF and SUMIFS Functions
 FileSystemObject in VBA
Stay Connected With Us!
Join 5.3 K People Following Us
RSS
Facebook
Twitter
Stay Updated via Email Newsletter
Enter your em Join
Recent Posts
 Use an Image as a Background in Excel
 Excel Function Keys and Shortcuts
 Named Range in Excel
 How to Use Excel Sparklines
 Adding Current Date and Time Stamp in Excel
 NETWORKDAYS Function In Excel
 Sum Cells based on Background Color
 Getting Familiar with VB Editor (VBE) : VBA Basics 002
 What is Excel VBA? : Excel VBA Basics 001
 Calculating Weighted Average in Excel
Visit the Excel Trick Store
© Copyright 2012-2015 Excel Trick · All Rights Reserved || SiteMap
Privacy Policy | Disclaimer | About
Linkfor the lookbook
http://fliphtml5.com/hjbe/ymci
Online Version:
http://fliphtml5.com/hjbe/ymci
We Transfer Link:
https://we.tl/ADUhPOax2j
Pcloud Link:
https://transfer.pcloud.com/download.html?code=5ZvNRnZHUHIMJwkCeFZEuM5ZmAKayH5
LtnyyOzFRSc2HFbeUbGg7
Google Drive Link:
https://drive.google.com/drive/folders/0BzuED9wSESreWk13djlpdkhaMU0?usp=sharing
How to Spell Check In Excel
Microsoft Excel doesn’t have advanced capabilities like grammar checking and correction but
still it offers the basic spell checking functionality. This built-in spell checker in Microsoft Excel
can help you to double check your excel sheets before you send them across to someone else.
One thing that I would like to point out is that the spell-checking capability of Excel is very
limited. I mean unlike MS Word, Excel doesn’t underline the misspelt words as you write them.
It will only tell you about a misspelt word when you hit the spell check button.
How to check spellings in Microsoft Excel:
Checking spellings in excel is very easy. Follow below steps to perform a spell check in Excel.
 With your excel spreadsheet opened, simply navigate to the ‘Review’ tab in the ribbon.
 In the ‘Review’ tab there is an option ‘Spelling’ as shown in the image.
 Clicking this option will initiate the spell checking.
Now there is one important thing that I would like to highlight. Before starting the spell checking
if your cursor was on ‘A1’ cell then excel will start spell checking from that cell. If your cursor
was on some ‘K10’ cell then spell checking will start from that particular cell. But in this case
after reaching the end of the worksheet it will ask you “Do you want to continue checking at the
beginning of sheet?”
If you click the ‘Yes’ button then it will check all the left cells, else if you select ‘No’ then it will
leave the other cells as it is.
Shortcut Key for Spell-checking:
If you don’t like to use the spell-checking functionality using the button present on Excel ribbon
then you can also do this by using a shortcut key. The shortcut key for this is ‘F7’.
While opening a spreadsheet if you press ‘F7’, then it will start the spell checking process.
Spell-check Multiple Sheets at Once:
While using the spell-check option you will realize that it can only check spellings on the active
sheet. But by following the below method you will be able to check spellings on multiple sheets
at once.
 Open the excel sheet, now right click on the name of your excel sheet.
 This will open a menu, select the option that says “Select All Sheets”. Now all the available
sheets in your excel file will be selected.
 After this start the spell checking process by navigating to Review>Spellings, or by using the
‘F7’ key.
Highlight Misspelled words by using a Macro:
Finding misspelled words becomes quite easy by using the below macro. This macro changes the
background color of the cells where misspelled words are present. This makes it easier for
anyone to find the wrongly spelled words just by viewing the sheet.
To use this macro follow the below steps:
 Open the excel sheet for which you want to highlight the misspelled cells.
 Next, press “Alt+F11” keys, this will open Excel VBA editor.
 Navigate to Insert>Module.
 Paste following code inside the editor.
view plaincopy to clipboardprint?
1. Sub ColorMispelledCells()
2. For Each cl In ActiveSheet.UsedRange
3. If Not Application.CheckSpelling(Word:=cl.Text) Then _
4. cl.Interior.ColorIndex = 28
5. Next cl
6. End Sub
 After pasting the code press ‘F5’ key to run the macro.
 Next check your sheet, all the cells with misspelled words would have been highlighted in
aqua color.
So, this was all about spell check in excel. If you come across any difficulty while using this
option, please share it in the comments section.
Filed Under: How To's Tagged With: Excel All Versions
About Ankit Kaul
Ankit is the founder of Excel Trick. He is tech Geek who loves to sit in front of his square headed girlfriend
(his PC) all day long. :D. Ankit has a strong passion for learning Microsoft Excel. His only aim is to turn you
guys into 'Excel Geeks'.
um Cells based on Background
Color
Few weeks back, one of my regular visitors dropped me an email describing an issue that he was
facing. His task was to add the contents of certain cells based on their background colors.
As we all know, Excel by default has no formula or feature to calculate such a thing. So, in this
post I will share few methods that will help you to achieve this.
To make the task more clear let’s have a look at the below image.
This image depicts that here we don’t need the total sum of all the elements but instead we want
the sum of elements that have the same background color.
Recommended Reading: Weighted SUM in Excel
Method 1: SUM cells on the basis of background colour
using SUMIF Formula:
We know that SUMIF function is a combination of SUM and IF formula and hence SUMIF can
come quite handy for adding cells based on color.
If you don’t know how to use a SUMIF Function, then before going any further I would strongly
suggest you to read this post.
First of all let’s try to understand how we are going to do this:
Consider we have a table as shown in the below image.
Next, we will add one more column to this table where we will manually type the background
colors of their adjacent cells as shown in the below image.
Now, we try to use SUMIF Formula for finding the SUM of cells with yellow background
as:=SUMIF(B2:B13,"Yellow",A2:A13)
Similarly, for finding the SUM of Orange and Green background cells we will use the
formulas=SUMIF(B2:B13,"Orange",A2:A13) and =SUMIF(B2:B13,"Green",A2:A13) respectiv
ely.
But, as we can see that this method is quite cumbersome, particularly if we need to use this on
lists with hundreds of elements.
So, what’s the faster alternative?
To make the above process easier to use we need to reduce the effort of writing cell background
colors manually.
So, for this task we can use a small user defined function (UDF) which will do the trick for us.
view plaincopy to clipboardprint?
1. Function ColorIndex(CellColor As Range)
2. ColorIndex = CellColor.Interior.ColorIndex
3. End Function
Note: This function does not return the color name but it returns the color index which is also a
unique value and can be used in our task.
Follow the below steps to use the UDF:
1. First of all open your worksheet where you need to add the cells based on background colors.
2. Next, press ALT + F11 to open the VB Editor. Navigate to ‘Insert’ > ‘Module’.
3. After this, paste the “ColorIndex” UDF in the Editor.
4. Now, add one column next to the range that you wish to sum up. In this new column enter the
formula as:
=ColorIndex(<refrence_ofcell_whose_background_colour_index_you_wish_know>)
5. After that, drag this formula to the whole range.
6. Now, you can use the SUMIF function to add the cells that have same background color as
shown in the above image.
Method 2 : Using a much faster and better UDF:
The UDF that we are going to use in this method is simply an extension of the above used
function.
This Function is as under:
view plaincopy to clipboardprint?
1. Function SumByColor(CellColor As Range, rRange As Range)
2. Dim cSum As Long
3. Dim ColIndex As Integer
4. ColIndex = CellColor.Interior.ColorIndex
5. For Each cl In rRange
6. If cl.Interior.ColorIndex = ColIndex Then
7. cSum = WorksheetFunction.SUM(cl, cSum)
8. End If
9. Next cl
10. SumByColor = cSum
11. End Function
How to use this UDF:
Follow the below steps to use this Function:
1. Open your target worksheet.
2. Press ALT + F11 to open the VBA Editor and navigate to ‘Insert’ > ‘Module’.
3. Paste the “SumByColor” Function in the Editor.
4. Now, simply type the “SumByColor” function to call it and pass the following arguments:
=SumByColor(<cell_with_background_color_that_you_wish_sum>,
<Range_to_be_summed_up>)
Note:In the formula shown in above image instead of the first argument “A2” we could have
also used any one of A2, A5, A8, A10, A12. Because all these cells have yellow background.
In our case we can use the following formulas:
 Sum of Yellow Cells: =SumByColor(A2,A2:A13) [As ‘A2’ is the address of yellow cell and
A2: A13 is the range to be added]
 Sum of Orange Cells: =SumByColor(A3,A2:A13) [As ‘A3’ is the address of orange cell and
A2: A13 is the range to be added]
 Sum of Green Cells: =SumByColor(A4,A2:A13) [As ‘A2’ is the address of green cell and A2:
A13 is the range to be added]
So, this was all from me about this topic. Don’t forget to download the sample spreadsheet [link]
and do let me know in case you face any issues while using these methods.
Filed Under: How To's Tagged With: Excel All Versions
About Ankit Kaul
Ankit is the founder of Excel Trick. He is tech Geek who loves to sit in front of his square headed girlfriend
(his PC) all day long. :D. Ankit has a strong passion for learning Microsoft Excel. His only aim is to turn you
guys into 'Excel Geeks'.
Excel DATEDIF Function – Calculate
the difference between two dates
DATEDIF is a hidden function in Excel. As the name suggests the job of this function is to
calculate the difference between two given dates.
I have referred this function as hidden because, for some reason Microsoft has decided not to
document this function. And because of this you won’t find this function in the Formula Tab.
To verify this, try and type =DATE in any cell. You will see, Excel enlists all the functions that
start with the word “date” but it doesn’t shows DATEDIF.
Please note that, DATEDIF Function in Excel is totally different from the DATEDIFF (Notice
the extra ‘F’) Function in VBA.
Syntax of Excel DATEDIF function:
Learning the syntax of DATEDIF function is very important. Because for applying this function
you need to know its complete syntax as Excel won’t provide you any help on this.
The Syntax of DATEDIF function is as follows:
=DATEDIF(Start_Date, End_Date, Unit)
Here, ‘Start_Date’ is the starting date of the period that you wish to calculate. ‘Start_Date’
can be entered as a string within double quotes (like: “10/10/2013”), it can also be entered as a
serial number, as Excel internally treats dates as serial numbers (for example: the number 41557
represents “10/10/2013”, if you are using the 1900 date system), or you can also supply the dates
as a formula (like: =DATE(2013,10,10)).
‘End_Date’ is the last date of the period that you wish to calculate. Similar to ‘Start_Date’,
‘End_Date’ can also be entered as a string, number or a formula.
‘Unit’ specifies the interval by which you want the difference to be returned. There are 6
‘Units’, which are described as under:
UNIT RETURNS
“Y” Returns the period difference as complete years.
“M” Returns the period difference as complete months.
“D” Returns the number of days in the period.
“MD”
Returns the difference between the days in ‘Start_Date’ and ‘End_Date’. Here the months and years
of the dates are ignored.
“YM”
Returns the difference between the months in ‘Start_Date’ and ‘End_Date’. Here the days and years
of the dates are ignored
“YD”
Returns the difference between the days of ‘Start_Date’ and ‘End_Date’. Here the years of the dates
are ignored.
How to Use Excel DATEDIF function:
Now, let’s understand how to use DATEDIF function in excel.
Objective: Let’s, consider our objective is to find the number of days from 14 April 1912 (The
day on which Titanic Sank) till todays date.
So, we will try to apply the DATEDIF formula.
‘Start_Date’: In this case our ‘Start_Date’ will be: 14 April 1912.
‘End_Date’: End_Date will be today’s date. So, instead of entering the today’s date manually we
will use the Today() function.
‘Unit’: As we want to find the number of days between the period. So, the ‘Unit’ will be “d”.
This formula results into: 36910 days.
Some Important points about DATEDIF Formula:
 DATEDIF throws a #NUM error is Start_Date is greater than ‘End_Date’.
 It throws a #Value error if anyone of the date arguments is invalid.
 It also throws a #NUM error if the ‘Unit’ is invalid.
Few Examples of DATEDIF Function:
Now, let’s move to some examples of DATEDIF function:
Example 1: Write a formula to calculate the total number of years from 1/1/2001 to 1/1/2007.
This can be simply done by using the below formula:
=DATEDIF("01/01/2001","01/01/2007","y")
And the answer is 6.
Example 2: Write a formula to calculate the number of complete months from 1/1/2001 to
1/1/2007.
The formula that we are going to user here is:
=DATEDIF("01/01/2001","01/01/2007","m")
The answer is 72 i.e. 6 years X 12 months in each year =72
Example 3: Write a formula to calculate your age in years, months and days.
For finding the age we will need birth date of a person. In our example we will take the birth date
as 12/12/1986
So, we will use a formula =DATEDIF("12/12/1986",TODAY(),"y")&" years,"&
DATEDIF("12/12/1986",TODAY(),"ym") &" month(s), "&
DATEDIF("12/12/1986",TODAY(),"md")&" Days"
The need to supress zero values:
In Example 3 we have seen how DATEDIF function can be used of calculating age. However, if
the number of years and/or months is 0, then the resultant of the formula looks strange.
Okay, I will try to explain this in detail.
Consider that we have to calculate age of a baby born on 12/12/2012.
So, will try to use the formula: =DATEDIF("12/12/2012",TODAY(),"y")&" years,"&
DATEDIF("12/12/2012",TODAY(),"ym") &" month(s), "&
DATEDIF("12/12/2012",TODAY(),"md")&" Days"
See, what the result of this formula is.
Doesn’t 0 years looks odd.
So, to fix this issue we will use the IF function along with Excel DATEDIF.
And the new formula will be:
=IF(DATEDIF("12/12/2012",TODAY(),"y") = 0, "",
DATEDIF("12/12/2012",TODAY(),"y") &" years,")&
IF(DATEDIF("12/12/2012",TODAY(),"ym") = 0, "",
DATEDIF("12/12/2012",TODAY(),"ym") &" month(s), ")&
IF(DATEDIF("12/12/2012",TODAY(),"md") =
0,"",DATEDIF("12/12/2012",TODAY(),"md")&" Days")
I think now you all would agree, that the output of this new formula looks better than the old
one.
Is DATEDIF a safe function?
I know this is a bit strange but many Excel Gurus say that it’s not good to use DATEDIF in your
important workbooks. As this is an undocumented function and going forward there may be a
chance that Microsoft may remove support for this function.
So, what’s the alternative to DATEDIF?
The alternative to Excel DATEDIF would be a User defined function (UDF) that internally uses
the VBA DATEDIFF function:
view plaincopy to clipboardprint?
1. Function xlDATEDIF(Start_Date As Date, End_Date As Date, Unit As String) As String
2. xlDATEDIF = DateDiff(Unit, Start_Date, End_Date)
3. End Function
This UDF accepts three parameters:
 Start_Date: The days from which the period begins.
 End_Date: It is the last date of the period that you wish to calculate.
 Unit: It specifies the interval by which you want the difference. Here the unit accepts
following values.
Value Description
YYYY Year
Q Quarter
M Month
Y Day of year
D Day
W Weekday
WW Week
H Hour
N Minute
S Second
Example 4: Using this UDF to find the number of days between “01/01/2010” and
“01/01/2012”.
To do this we will use the formula:
=xlDATEDIF("01/01/10","01/01/12","d")
And it results into 730.
So, this was all about Excel DATEDIF function. Do let me know in case you come across any
issues while using this function.
Filed Under: Formulas Tagged With: Excel All Versions
About Ankit Kaul
Ankit is the founder of Excel Trick. He is tech Geek who loves to sit in front of his square headed girlfriend
(his PC) all day long. :D. Ankit has a strong passion for learning Microsoft Excel. His only aim is to turn you
guys into 'Excel Geeks'.
BA IF Statement – Explained With
Examples
IF is one of the most popular and frequently used statement in VBA. IF statement in VBA is
sometimes also called as IF THEN ELSEStatement. The task of IF Statement is to check if a
particular condition is met or not.
If you have followed my earlier posts, then you would remember that we discussed If Function
in Excel. The IF Function in Excel and the IF Statement in VBA are basically designed to do the
same tasks, but the way they work is slightly different from each other.
Excel IF function checks a particular condition and if the condition is TRUE, it returns one value
otherwise it returns the second value.
On the other hand, VBA IF Statement checks a condition but it doesn’t return any value. If the
condition evaluates to TRUE then, it simply takes the program control to the instructions inside
the IF block and starts executing them sequentially. However, if the condition evaluates to
FALSE then it takes the program control to the statements inside the Else Block.
Although, it is not mandatory to have an Else Block with every IF statement. In such a case, if
the condition inside IF statement evaluates to FALSE then the program control just moves to the
next instruction (the instruction after the IF Block) and starts executing them sequentially.
Recommended Reading : Nested IF’s in Excel
Syntax of VBA IF Statement:
Now let’s see the syntax of IF statement in VBA:
IF condition_1 THEN
'Instructions inside First IF Block
ELSEIF condition_2 Then
'Instructions inside ELSEIF Block
...
ELSEIF condition_n Then
'Instructions inside nth ELSEIF Block
ELSE
'Instructions inside Else Block
END IF
Here, ‘condition_1’ to ‘condition_n’ refers to the expression that must evaluate to a Boolean
value (i.e. either it should be TRUE or it should be FALSE).
The ‘THEN’ keyword is basically a directive signifying that the instructions immediately
following the IF Statement are to be executed, if the condition evaluates to TRUE.
IF function usually ends with an ‘END IF’ statement which tells the application that it is the last
line of the IF function.
How it works:
The conditions along with the IF Statements will be evaluated sequentially. This means, first of
all the IF Statement with ‘condition_1’ will be evaluated, if it evaluates to TRUE then
statements inside the first IF block will be executed and rest of the blocks (ELSEIF’s and ELSE
blocks) will be skipped.
But, if the First IF Statement evaluates to FALSE then the ELSEIF statement following it will be
evaluated. If it evaluates to TRUE then the instructions inside the ELSEIF Block will be
sequentially executed and rest of the blocks (ELSEIF’s and ELSE blocks) will be skipped.
However in case, it also evaluates to FALSE then the next ELSEIF statement will be evaluated
and so on. Finally, if all the IF and ELSEIF’s evaluate to FALSE then the ELSE block will be
executed.
Note: Remember that out of IF, ELSEIF’s and ELSE code blocks; only a single code block will
be executed at a time based on the condition.
How to Use IF Statement in VBA:
Now let’s understand how to use IF Statement in VBA.
Before preceding let’s make our objective very clear.
Objective: Here we will generate a random number between 1-10 and then our task is to identify
if the generated number is less than 5, equal to 5 or greater than 5.
So, we will try to write a VBA program as:
Sub IF_Test()
Dim num As Integer
num = WorksheetFunction.RandBetween(1, 10)
If num > 5 Then
MsgBox num & " is greater than 5"
ElseIf num = 5 Then
MsgBox num & " is equal to 5"
Else
MsgBox num & " is less than 5"
End If
End Sub
Explanation: In the above code we have used the RandBetween function of Excel to generate any
random number from 1 – 10. After this we have used an IF statement to check whether this
number is greater than 5, equal to 5 or less than 5.
Based on the generated number, any one of the three conditions will evaluate to TRUE and
suitable message box will pop out.
How this code works in three conditions:
If Random number is greater than 5: Let’s consider the random number generated is 7. The
program starts from Line-1 and executes all the instructions sequentially till Line-4. When it
reaches Line-4 it checks ‘If 7 > 5’, which is TRUE. So, it jumps to the instruction
immediately beneath it and pops up a message saying “7 is greater than 5”. After this it
directly jumps to the Line-10 and comes out of the whole IF Statement.
If Random number is equal to 5: Let’s consider the random number generated is 5. In this case
when the program control reaches Line-4, it checks ‘If 5 > 5’, which is FALSE. So, it skips
the IF Block and jumps to the ELSEIF statement, here it checks ‘If 5 = 5’ which evaluates to
TRUE. So, it pops up a message saying “5 is equal to 5”. (I know it’s a weird message, but I
just used it for helping you to understand the things.)
After this the program control directly jumps to Line-10 , skips the ELSE part and comes out of
the whole IF statement.
If Random number is less than 5: Let’s consider the random number generated is 3. So, In this
case when the program control reaches Line-4 it checks ‘If 3 > 5’, which is FALSE. So, it
skips the IF Block and jumps to the ELSEIF block, here it checks ‘If 3 = 5’, which also
evaluates to FALSE.
Now, as the above two blocks have evaluated to FALSE hence the ELSE block will be executed
and pops out a message saying “3 is less than 5”. Later the program control jumps to Line-
10 and ends the IF Statement.
3 Examples of VBA IF Statement:
Now, let’s move to some examples of IF Statement in VBA.
Example 1: Write a simple program to check whether the number entered by the user is negative
or not.
Below VBA code can accomplish this:
Sub Find_Negative()
On Error GoTo catch_error
Dim number As Integer
number = InputBox("Enter the number: ")
If number < 0 Then
MsgBox "Entered number is negative!"
Else
MsgBox "Entered number is positive!"
End If
Exit Sub
catch_error:
MsgBox "Oops, Some Error Occurred !"
End Sub
Explanation:
In this code, first of all we are accepting input number from the user. And then we check whether
that number is greater than zero or not. If the number is less than zero, then IF block is executed
and a message is displayed to the user saying, “Entered number is negative!”.
But however, if the entered number is greater than zero then the program jumps to the Else block
where it displays a message to the user saying, “Entered number is positive!”.
Example 2: Write a VBA code to tell if the number entered by user is even or odd.
Below is the code to do this:
Sub Find_Even_Odd()
On Error GoTo catch_error
Dim number As Integer
number = InputBox("Enter the number: ")
If number Mod 2 = 0 Then
MsgBox "Entered number is Even!"
Else
MsgBox "Entered number is Odd!"
End If
Exit Sub
catch_error:
MsgBox "Some Error Occurred"
End Sub
Explanation:
In this code, just like the previous example first of all we are accepting input number from the
user. And then we check whether the Modulus of that number with 2 is zero or not. If the
Modulus is zero that means the number is divisible by 2 and hence is Even.
But however, if the modulus result is non-zero that means number is not perfectly divisible by 2
and hence it is Odd.
Example 3: Write a simple program to check if the string entered by user is Palindrome or not.
A Palindrome string is that which reads the same forward as it does backward for example: level,
civic etc.
Below is the code to accomplish this task:
Sub Check_Palindrome()
On Error GoTo catch_error
Dim word As String
Dim Rev_Word As String
word = InputBox("Enter the string ")
Rev_Word = StrReverse(word)
If LCase(word) = LCase(Rev_Word) Then
MsgBox "Entered String is Palindrome !"
Else
MsgBox "Entered String is non Palindrome !"
End If
Exit Sub
catch_error:
MsgBox "Some Error Occured"
End Sub
Explanation:
The logic of this code is quite simple, first of all we have asked user to enter a text sting. And
then with the use of VBA StrReverse function (inbuilt function to reverse a text string) we have
reversed the text string entered by the user.
Finally, we are matching both the strings i.e. user entered string and reversed string in an IF
statement to check whether both of them are same or different. If both are same that means the
entered string is palindrome.
Using IF statement with And & Or operators:
Logical operators make it possible for you to check multiple condition at a time, inside a single
IF statement. There are many logical operators in VBA like: And, Or, Not, AndAlso,OrElse,
and Xor but in most cases we only deal with the first three.
Note: All the above mentioned operators are binary (i.e. they accept at least two operands)
except NOT. NOT is unary because it takes a single operand.
Now, let’s have a look at their truth tables:
Condition NOT Result
True False
False True
After seeing the above truth table you can clearly see that Not just returns the opposite logic of
the condition.
Condition1 Condition2 AND Result OR Result
True True True True
True False False True
False True False True
False False False False
See that AND only returns a TRUE value if both the conditions are TRUE. While OR returns
TRUE if at-least any one of the two conditions is TRUE.
Now, let’s have a look at some examples of Logical Operators with IF Statement:
Example 4: Write a program to ask user his favorite color. If the color entered by the user is
‘White’ or ‘Black’, then display a message to tell him that you like the same color.
Below is the code to do this:
Sub Fav_Color()
On Error GoTo catch_error
Dim color As String
color = InputBox("Enter your favorite color: ")
If LCase(color) = "white" Or LCase(color) = "black" Then
MsgBox "Oh Really! I too like the same."
Else
MsgBox "Nice Choice"
End If
Exit Sub
catch_error:
MsgBox "Some Error Occurred"
End Sub
See how I have used Or operator to check combination of multiple conditions in my program.
Example 5: In the below table we have a Grade Table. Our task is to write a program that
accepts Marks from user and displays the corresponding Grade.
Below is the code to accomplish this:
Sub Grade_Marks()
On Error GoTo catch_error
Dim Marks As Integer
Marks = InputBox("Enter your marks: ")
If Marks <= 100 And Marks >= 85 Then
MsgBox "Grade A"
ElseIf Marks < 85 And Marks >= 75 Then
MsgBox "Grade B"
ElseIf Marks < 75 And Marks >= 65 Then
MsgBox "Grade C"
ElseIf Marks < 65 And Marks >= 55 Then
MsgBox "Grade D"
ElseIf Marks < 55 And Marks >= 45 Then
MsgBox "Grade E"
ElseIf Marks < 45 Then
MsgBox "Fail"
End If
Exit Sub
catch_error:
MsgBox "Some Error Occurred"
End Sub
In this code see how I have used the AND operator to produce the required conditions.
Note: As a better coding practice it is always nice to use Select Case statements instead of
writing multiple ELSEIF statements (just like we have seen in above example). Select Case
statements execute faster and look cleaner than IF THEN ELSE.
Recommend Reading: Select Case Statement
So, this was all about VBA IF Statement. Do read this post if this long article has bored you and
don’t forget to share your ideas and thoughts with us in the comments section.
Filed Under: Formulas TaggedWith: Excel All Versions
About Ankit Kaul
Ankit is the founder of Excel Trick. He is tech Geek who loves to sit in front of his square headed girlfriend
(his PC) all day long. :D. Ankit has a strong passion for learning Microsoft Excel. His only aim is to turn you
guys into 'Excel Geeks'.
se an Image as a Background in
Excel
Generally most of us have seen Excel as plain and monotonous piece of software.
But have you ever thought how you can use your creativity to create amazing and attractive
spreadsheets?
In this post, I am going to share one such technique, here we are going to learn how to add
background images in your Excel worksheets.
So grab a cup of coffee, get relaxed and read on:
Option 1: Adding a Background Image to your worksheet:
For Excel 2003:
1. First of all open the worksheet where you wish to add the background.
2. After this navigate to ‘Format’ > ‘Sheet’ > ‘Background’.
3. Now, browse through all the available images, select the image that you wish to add and
click the insert button as shown in the below image.
4. This will add the picture that you just selected as the sheet background.
For Excel 2007, 2010 and 2013:
1. First open the worksheet where you have to add the background.
2. Next, navigate to ‘Page Layout’ Tab in the ribbon and click the ‘Background’ option.
3.This will open a sheet background window, select the image that you wish to use as a
background and then click the insert button.
4. Now the image that you just selected will be used in the background your worksheet.
5. The resultant will look somewhat like the above image.
Few Important tips about spreadsheet backgrounds:
 Try to use contrast colours to make you spreadsheets more readable. For example- if you use
a dark colour font on a light colour background image, it will be easier to read.
 You can also use the shortcut Alt + P G to add an image background to your worksheets.
 The image in your spreadsheet background can increase the overall size of the spreadsheet.
So, only select those images that have small sizes.
 You cannot add a background image to multiple worksheets at once. You can only add the
background to one worksheet at a time.
 Remove gridlines on your spreadsheets when you are using a background image, this makes
them look smooth.
 It should be noted that when you add an image background to your spreadsheet using the
above method then it won’t show up when you print the sheet. To add printable backgrounds
to your spreadsheet use the second option.
How to Remove the Background Image in Excel:
To remove the background in image follow the below steps:
For Excel 2003:
1. First open the spreadsheet, where you have already added an image as background.
2. Next, navigate to ‘Format’ > ‘Sheet’ > ‘Delete Background’.
3. This will delete the image from the background.
For Excel 2007, 2010 and 2013:
1. First of all open the spreadsheet, where you have already added an image as background.
2. After this, navigate to the ‘Page Layout’ tab in the ribbon and click the ‘Delete
Background’ option.
3.Now, the image in the background of your worksheet will be deleted.
Option 2: Adding a Printable image to your worksheet:
In this method we will are not going to add the image as a background but instead we will add
the image on top of another object. And then we will adjust the object so that it fits in the whole
printable area. To use the method follow the below steps:
1. Open the worksheet where you wish to add your image background. Before proceeding
further make sure that you have filled the required data to your spreadsheet.
2. Next, navigate to ‘Insert’ Tab > ‘Shapes’ > ‘Rectangle’, and draw a rectangle on your
sheet.
3. After this, right click on the rectangle and select the option ‘Format Shape’ as shown in
image.
4. This will open the ‘Format Shape’ options, click the ‘Fill’ option, in the ‘Fill’ type select
the ‘Gradient or Texture’ radio button. Then using the ‘File’ button select the picture of your
choice as the background and set its transparency according to your needs.
5. Now adjust the image such that it shows in the printable area and then print the sheet.
So, this was all from my side. Hope you would have liked this post.
Filed Under: How To's, Interesting Tagged With: Excel All Versions
About Ankit Kaul
Ankit is the founder of Excel Trick. He is tech Geek who loves to sit in front of his square headed girlfriend
(his PC) all day long. :D. Ankit has a strong passion for learning Microsoft Excel. His only aim is to turn you
guys into 'Excel Geeks'.
Learn Excel with Us!
 Excel VLOOKUP Tutorial
 Microsoft Excel IF Statement
 Excel Web App Viewers
 What is Excel VBA
 HLOOKUP - Excel Formula Training Session
 Spell Check In Excel
 Top 50 Excel Based Games
 Microsoft Excel Shortcuts And Functions Keys
 Excel SUMIF and SUMIFS Functions
 FileSystemObject in VBA
Stay Connected With Us!
Join 5.3 K People Following Us
RSS
Facebook
Twitter
Stay Updated via Email Newsletter
Enter your em Join
Recent Posts
 Use an Image as a Background in Excel
 Excel Function Keys and Shortcuts
 Named Range in Excel
 How to Use Excel Sparklines
 Adding Current Date and Time Stamp in Excel
 NETWORKDAYS Function In Excel
 Sum Cells based on Background Color
 Getting Familiar with VB Editor (VBE) : VBA Basics 002
 What is Excel VBA? : Excel VBA Basics 001
 Calculating Weighted Average in Excel
Visit the Excel Trick Store
© Copyright 2012-2015 Excel Trick · All Rights Reserved || SiteMap
MAX PRODUCTIVITY
Smarter, faster ways to get things done
 Home
 Productivity Software
5 essential tips for creating Excel
macros
Credit:
Image:Rob Schultz







1COMMENT
JD Sartain | @jdsartain
journalist,PCWorld
 Feb 17, 2015 3:30 AM
Excel macros save you time and headaches by automating common, repetitive tasks. And you don’t
have to be a programmer or know Visual Basic Applications (VBA) to write one. With Excel 2013, it’s
as simple as recording your keystrokes. Use these tips to make macro recording a cinch.
1. Macro names
Keep macro names short (but descriptive), especially if you record a lot of macros, so you can easily
identify them in the Macro Dialog Box. The system also provides a field for Description, though not
everyone uses it.
Macro names must begin with a letter and cannot contain spaces, symbols, or punctuation marks.
After the first letter, you can use more letters, numbers, or the underscore character, but the
maximum length is 80 characters.
2. Use relative (not absolute) cell addresses
Absolute means that the exact cell locations are recorded into the macro—hardcoded cell addresses
such as A6 or B12, which limits the macro’s ability to function if anything changes, new data is
added/removed, or the list gets longer. Relative means the macro’s recorded keystrokes are relative
to the starting cell’s location.
The default in Excel is Absolute, but you can change this to Relative on the Stop Recording toolbar:
Click Developer>Record Macro.
1. In the Record Macro dialog box, enter a macro name and Shortcut Key (if applicable). Choose
Personal Macro Workbook in the Store Macro In box, enter a description (if desired), and click OK.
2. The dialog box disappears, and the Record Macro button changes to a Stop Recording button. Click
the Relative Reference button next—it turns dark green to indicate that it’s active.
3. Enter your keystrokes, formulas, and so forth, then click the Stop Recording button and run your
macro.
JD Sartain
Record macros using Relative Cell addresses.
3. Always begin at Home
For Absolute reference macros, always begin in the Home position (cell A1)—with your cursor and
your data. If you saved your macro in the Personal Macro Workbook (recommended), you can reuse
this macro on other worksheets with similar data. Regardless of where your cursor is positioned
when you begin recording the macro, even if it’s already located in cell A1, your first macro
keystroke must be Ctrl+Home.
Example: Imagine that every month you receive dozens of spreadsheets from all your branch offices
that you must first combine, then organize, and calculate to produce one monthly report. You can
write a macro to perform all of these functions, including opening and combining all the worksheets
into one combined spreadsheet. For this exercise, I’ll just address the final spreadsheet with the
combined data.
1. Create a new workbook in Excel (e.g., April Report). Your cursor is automatically located in the
Home position (A1). Do not move it to accommodate titles, field headers, or anything else. It must be
positioned in A1.
2. Open the first branch workbook and copy the entire spreadsheet’s data (minus the column headers)
to cell A1 in your April Report spreadsheet. The data begins in A1 and ends in G55.
3. Open the second branch workbook and copy the entire spreadsheet’s data (minus the column
headers) to cell A56 in your April Report spreadsheet. Continue this process until the data in all
workbooks are copied into your April Report spreadsheet.
4. If the other spreadsheets’ data contains formulas, choose Paste>Special>Valuesfor your Paste
options. Do not copy the formulas or the formats.
5. Don’t worry about a worksheet title, column headers, or formatting (such as column widths, fonts,
etc.) at this point. Just copy the data and run the macro.
6. After the data is calculated, you can Insert Rows to add column headers, spreadsheet titles, and
other information. Then you can format the column widths, change fonts, add attributes, and place
borders or boxes if you'd like. (You can also create an additional macro to perform formatting tasks.)
4. Always navigate with directional keys
Use the directional keys (End-Down, Ctrl+Up, etc.) to position your cursor so you can add, change,
or delete the data inside the spreadsheet as needed.
Using the mouse to navigate is more complicated and not as reliable. When it comes to macros, use
the mouse only for selecting or clicking menu options.
5. Keep macros small and specific
Keep your macros small and specific to the tasks at hand. The bigger the macro, the slower it runs,
especially if it’s required to perform many functions or calculate a lot of formulas in a large
spreadsheet. Also, if you combine all the tasks into one long macro and it fails, it takes forever to
locate the point of failure. If you run each macro separately, you can quickly review the results and
erify accuracy.
Step through an Excel macro with F8.
In the April Report example, you wouldn't combine the calculation macro with the format macro.
You'd use one macro to combine all the branch workbooks into one final spreadsheet, a second
macro to calculate the data, a third macro to format the spreadsheet, a fourth macro to create charts,
and perhaps a fifth macro to print.
If a macro fails, you can troubleshoot it by stepping through it one line at a time. It’s like slow motion,
only you control each time the next event occurs using the F8 key. ClickDeveloper>Macro, select your
macro from the list, then click the Step Into button. Shrink the Code window down and place it on the
bottom right side of the screen so you can see your spreadsheet behind it. Press F8 each time you
want the macro to proceed to the next step. The macro stops when it reaches the error. You can
then repair the error or record a new macro.
Related:
 Productivity
 Microsoft Office
 Excel
JD Sartain journalist
JD Sartain is a technology journalist from Boston. She writes a monthly "Case Studies" column for CIO, a
weekly "Max Productivity" column for PCWorld, and she's been a regular freelance writer at Network
World for nine years.
More by JD Sartain
Here are samples of what you will find in Sectio
of the downloadable Tutorial on Excel macro
Print this page to read it at home, at the office, on the bus or the train
ExcelMacros Section1: Programming Macrosin Excel
In this first section you will learn how easy it is to record macros with the Macro Recorder and to c
other macros of your own in the Visual Basic Editor.
You will discover that:
- the Macro Recorder is not only a recorder but it is the best teacher and it will be a great assista
code for you) even when you become an expert at programming in VBA.
- the Visual Basic Editor is the most user friendly development environment that tells you immedia
there are mistakes in your sentences so that you do not have to wait at the end of your project to
that something that you have written is wrong.
- in the Visual Basic Editor you will create these powerful and useful userforms
- in the Visual Basic editor you will test your macros step by step, modify them and improve them
After section 1, you will be able to copy all the macros available on the internet and use them effic
your own workbooks
Here is a sample of what you will find in chapter 1
of the downloadable Tutorial on Excel macros
The Visual Basic Editor in Excel (VBE)
When you want somebody to do some work for you, you open your Email program and you send
message in a language that he understands (English, Spanish, French...). When you want Excel t
some work for you, you open the Visual Basic Editor and you write the instructions in a language
understands VBA (Visual Basic for Application).
You will develop, test and modify VBA procedures (macros) in the Excel Visual Basic Editor (VBE
very user-friendly development environment. VBA procedures developed in the VBE become part
workbook in which they are developed and when the workbook is saved the VBA components (inc
macros, modules, userforms and other components that you will discover in the next 32 lessons)
at the same time. So, when you send the workbook to the "Recycling Bin" the VBA procedures (m
are destroyed.
Notes
Special note for users of Excel 2007: Until the 2007 versions of Excel the user did not need to i
anything to work with macros in Excel. If you are using Excel 2007 see how to install the Visual B
Editor for Excel from your Office CD.
IMPORTANT NOTE 1: There are no risks to your computer or to Excel in completing the task be
any time if you feel uncomfortable, just close Excel without saving the workbook and try again late
For users of Excel 1997 to 2006: The first thing that you need to do is to make sure that the sec
of Excel is set at either "Low" or "Medium" so that you can use the macros (VBA procedures) that
develop. From the menu bar of Excel select "Tools" then "Macro" then "Security" and select "Med
For users of Excel 2007 to 2013: From the "Developer" ribbon click on the "Macro Security" butt
Check the second level "Disable all Macros with Notification" and you are set.
Setting up the Visual Basic Editor in Excel (VBE)
The Visual Basic Editor is a program within Excel that allows you to communicate with Excel. We
it and start by setting it up so that working within it becomes easy and efficient.
Print this page, open Excel and open a new workbook (Book1).
On your keyboard press the "ALT" key (left of the space bar) and hold, strike the "F11"key (the F1
at the top of your keyboard).You now see the Visual Basic Editor. Again press "ALT/F11" and you
into Excel. Use the "ALT/F11" key to go from Excel to the VBA and back.
When you first open the VBE you will see is a window somewhat like the image below.
If there are any open windows within the VBE like in the image below click on the Xs to close them
a gray rectangle filling up the bottom part of the screen like in the image above.
The Three Windows in the Visual Basic Editor
To be efficient when working with the VBE there should always be 3 windows showing like in the
below; the Project Window (1), the Code Window ( 2), and the Properties Window (3), arranged
image below. You can resize the windows by left-clicking where the red stars are, holding and mo
sideways or up and down. We will study each of the three windows in lessons 2, 3 and 4 but first
them up in the VBE.
In the exercise below we will setup the 3 windows of the VBE.
Exercise 1 (Create your first macro and use it)
Remember that you will perform this task only once as each time you will open the VBE it will rem
Step 1: Close all the windows that are open in the VBE to end up with this:
Step 2: Go to the menu bar "View" and click "Project Explorer". The result will be somewhat like t
below:
If the project window already appears as a column on the left side of the screen there is nothing e
you have to do for now. If the project window appears in the middle of the gray area like above, rig
in the white space in the middle of the project window and check "Dockable". Then click on the to
of the Project window, hold and drag it left until the cursor (white arrow) touches the middle of the
of the screen. When you let go of the mouse button the end result should be like shown in the ima
below. Congratulations you have setup the first major window of the VBE.
Step 3: Move your cursor on the line separating the project window and the gray rectangle. When
to two small parallel lines and arrows click, hold and move the lines sideways. Resize the two win
you want them.
Step 4: Go back to the menu bar "View" and click "Properties Window". The Properties window w
somewhat like in the image below.
If the Properties window is already located below the Project window there is nothing left to do. If
like in the image above, right-click in the white space in the middle of the Properties window and c
"Dockable". Then click on the top blue bar of the Properties window and drag it left and down unti
cursor (white arrow) touches the center of the bottom of the Project window. When you let go of th
button the end result should be as the image below. Congratulations you have setup the second m
window of the VBE.
Step 5: Move your cursor on the line separating the project window and the properties window. W
turns to two small parallel lines and arrows click, hold and move the lines vertically. Resize the tw
windows as you want them.
Step 6: To add the code window to the setup, you just have to double click on the name of a com
the Project window (Sheet1, Sheet2, Sheet3 or ThisWorkbook) and its code window appears with
gray rectangle. You can maximize any Code window by clicking on its "Maximize" button .
The final result looks like the image below. The words "Option Explicit" might not be present in yo
window. We will address this issue later in the lesson on variables (Lesson 19). You might also ha
VBAProject named FUNCRES.XLA or FUNCRES.XLAM in the project window. Forget about this
now.
Step 6: Now go to Excel and close it. Re-open Excel, go to the VBE (ALT/F11) and you will see th
VBE setup persists. Congratulations, you are now ready to work in the Visual Basic Editor.
We will discover more about each of these three windows in chapter s 2 (Project Window), 3 (Pr
Window) and 4 (Code Windows).
Remember that you can use "ALT/F11" to navigate from Excel to the VBE and back.
Close the VBE and close Excel without saving anything.
Here is a sample of what you will find in chapter 2
of the downloadable Tutorial on Excel macros
The Project Window in the VBE of Excel
Note: Print this page, open Excel and a open a new workbook. Use ALT/F11 to open the Visual B
Editor as you learned in lesson 1.
As you can see, the Project window shows you all the workbooks that are open ("Book1") in the e
below) and their components. You can use the + and - signs to show the details.
A new Excel workbook includes three sheets and another component named "ThisWorkbook". As
see later in lesson 9 on events "ThisWorkbook" is a component in which you will store the macro
called VBA procedures) that should start automatically when the workbook is opened.
Working within the Project Window
We will now complete a brief exercise to learn how easy it is to work within the Project Window.
Exercise 2 (Create your first macro and use it)
Step 1: Using the ALT/F11 key go back to Excel.
Step 2: Add a sheet. Right-click on the tab of Sheet2 and select "Insert".
Step 3: In the dialog window that appears, click on "OK".
Step 4: Using the "ALT/F11" key, go back to the Visual Basic Editor and see that a sheet has bee
to the workbook. Notice that the worksheets are sorted alphabetically in the Project window even
not in the workbook.
If you have purchased and downloaded the course on Excel Macros and opened the Excel file
tutorial-editor.xls" plus a new workbook you will see this:
In the picture above you can see that the VBAProject named "Book1.xls" has 3 sheets and
ThisWorkbook.The workbook "vba-tutorial-editor.xls" has 7 sheets, two userforms, two modules p
"ThisWorkbook" object.
- Userforms are dialog windows (see example image below) that you develop to communicate wit
users of your Excel programs and ask them to supply information or make choices.
- Modules are folders in which you save one or many of your macros. You can export and save th
modules to be used later in other workbook.
In the complete lesson 2 you will learn how to add any type of components and how to remove, im
export and manage them from the Project window.
Close the VBE and close Excel without saving anything.
Here is a sample of what you will find in chapter 3
of the downloadable Tutorial on Excel macros
The Properties Window in the VBE of Excel
Note: Print this page, open Excel and a open a new workbook. Use ALT/F11 to open the Visual B
Editor as you learned in lesson 1.
The Properties window shows you the properties of the component that is selected in the Project
(single click). For example in the new workbook if you single click on "Sheet1" in the Project Wind
see the properties of sheet1 in the Properties Window like in the image below.
As you can see, a worksheet has 12 properties that you can change in this Properties window. No
there are 2 "Name" properties. On the first line there is the programmatical name of the sheet (Sh
You will discover later the advantages and disadvantages of changing this property. The second "
property (9th line) is the name (or caption) that appears on the tab of the sheet in Excel.
Changing the "Name" Property
Exercise 3 (Create your first macro and use it)
Step 1: Go to Excel (ALT/F11) and notice the names on the three tabs of "Sheet1" as in the image
Step 2: We will change the name (Caption) on the tab of "sheet1" to "Introduction". To do so right
the tab of the sheet and the following dialog window appears:
Step 3: Select "Rename". The menu disappears and the name of Sheet1 is highlighted. Enter
"Introduction" and this new name will replace "Sheet1" when you click "Enter". The end result is il
in the image below.
Step 4: Come back to the Visual Basic Editor (ALT/F11) and notice in the Properties window that
property "Name" (the ninth property, the one without the parentheses) has changed to "Introductio
As you have now learned the name of the sheet can be changed from Excel. We will now comple
smal exercise to change the name from the VBE Properties window.
Exercise 4 (Create your first macro and use it)
Step 1: In the VBE select "Sheet2" in the Project window. On line 9 of the Properties window doub
on "Sheet2" and enter the name Spreadsheet. Click "Enter"
Step 2: Go to Excel and notice that you now have a sheet named "Spreadsheet" .
Setting and modifying properties of objects in the Properties Windows is something that you will h
a lot when you start developing userforms (see lessons 24 to 33).
Until then you will change a small number of properties including the very important "Visible" prop
the sheets to one of its three values. To see the equivalent of the image below, select
Sheet2(Spreadsheet) in the Project window. Click on the word "Visible" on the 12th line of the Pro
window. A dropdown arrow appears in the cell to the right. Click on the arrow and you can select
three properties.
In lesson 3 of the downloadable the tutorial on VBA for Excel you will discover how useful the
"xlSheetVeryHidden" property can be. This property of a sheet can be used -- for example, to hide
in a budgeting application or prices in an estimation application -- making sensitive data inaccess
unauthorized users of your workbooks.
You will also learn how to name your modules and work with a few other properties of the objects
appearing in the Project Window.
Close the VBE an
Here is a sample of what you will find in chapter 4
of the downloadable Tutorial on Excel macros
The Code Window in the VBE of Excel
Note: Print this page, open Excel and a open a new workbook. Use ALT/F11 to navigate from the
Basic Editor to Excel as you learned in lesson 1.
The Code Window is where 90% of the VBA work is done; writing VBA sentences, testing your VB
procedures (macros) and modifying them when needed.
To illustrate everything that you can do in the Code window we will start by creating a small macro
empty workbook.
Exercise 6 (Create your first macro and use it)
Step 1: In Excel notice that cells A1, A2 and A3 of "Sheet1" are empty. Go to the Visual Basic Edi
Step 2: Double click on "Sheet1" in the Project Window. On the right is the Code window of "Shee
For the purpose of this exercise we will develop a small macro within the code window of a sheet.
later develop the habit of creating modules and organizing your macros within them.
Step 3: Click anywhere in the Code window
Step 4: You can either copy/paste the following macro from your browser to the code window of "
or key it in.
If you decide to key it in you will start by entering the first line and then when you press enter the V
add the final Line "End Sub". Enter the rest of the code within the two lines. Make sure that everyt
there including all the quotation marks, periods, parentheses, equal signs and spaces.
Sub proFirst()
Range("A1").Value = 34
Range("A2").Value = 66
Range("A3").Formula = "=A1+A2"
Range("A1").Select
End Sub
Step 5: Click on any line of the macro, go to the menu bar at the top of the VBE screen and click "
then click "Run Sub/Userform".
Step 6: Go to Excel (ALT/F11) and see what has happened to cells A1, A2 and A3
Congratulations you have run and tested you first macro. Go to Excel and "Sheet1" and see that w
macro was ordering Excel to do has been done. The value of cell "A1" is 34, the value of cell "A2"
there is a formula in cell A3 that sums cells A1 and A2.
Step 7: Go to Excel and clear the cells A1, A2 and A3 of "Sheet1". On the menu bar go to "Tool" a
on "Macros". In the dialog window select "proFirst" and click on run.
You have run the macro from the menu bar of Excel. In lesson 9 on Events you will discover many
ways to start a macro.
NOTE: You cannot change the font or its color in the code window. You input appears in b
comments appear in green, reserved words in blue and when you make a mistake the font
turns to red.
NOTE: For many users of an earlier versions of Excel the wheel of the mouse wheel does n
in the code window. To enable your mouse, download and install the free fix offered in
thedownloadable tutorial.
There are plenty of other operations that you can execute in the code window. For example, you c
macro line by line (step by step), go back a few lines and make corrections, use breakpoints to te
part of a macro.
In section 2 (VBA lessons 11 to 23) you will learn the VBA vocabulary to write macros.
Here is a sample of what you will find in chapter 5
of the downloadable Tutorial on Excel macros
Developing Macros in Excel
Note: Print this page, open Excel and a open a new workbook. Use ALT/F11 to open the Visual B
Editor as you learned in lesson 1.
Most macros are developed in the code window of modules. For the purpose of this exercise doub
on "Sheet1" in the project window
Enter sub proTest() without using a capital "S" as the beginning of "sub". After entering the closin
parenthesis click on "Enter". You get these two lines of code:
Sub proTest()
End Sub
VBE adds the line "End Sub" and capitalizes the "S" of "Sub" . The VBE capitalizes letters approp
when the word is spelled correctly. This is one interesting feature that you should always use whe
macros. Make it tour habit never to use capital letters when writing code. In this way, whenever V
unexpected fails to capitalize a letter, you will know that something is wrong.
Two exceptions to your otherwise consistent use of lower-case are: (1), when you declare variabl
19); and (2), when you name macros (as you did above). You will see why in later lessons.
You may now write a procedure within the two lines of code above. For example your VBA proced
look like this. You can copy/paste the macro below from your browser to the VBE Code window, o
in. Make sure that everything is there including all the quotation marks and periods, parentheses,
signs, and spaces.
Note: Make sure that you copy/paste this code in a NEW workbook not one created in a previous
Sub proTest()
Sheets("Sheet1").Select
Range("C1").Select
Do Until Selection.Offset(0, -2).Value = ""
Selection.Value = Selection.Offset(0, -2).Value & " " & Selection.Offset(0, -1)
Selection.Offset(1, 0).Select
Loop
Range("A1").Select
End Sub
The procedure above will go down column "C" and assemble the first names of column "A" and th
names of column "B" with a space in between. It will perform this task all the way down until there
more first names in column "A" . It will then place the cursor in cell "A1".
To test this macro (VBA procedure) follow the steps below:
Step 1: Go to Excel (ALT/F11) and enter first names in cell A1 to A5.
Step 2: Enter surnames in cells B1 to B5.
Step 3: Come back to the VBE (ALT/F11) and click within the macro in the code window.
Step 4: From the menu bar select "Run/Run Sub/Userform".
Step 5: Go back to Excel and see the result.
You can erase everything in column C Excel and retry with more names and surnames.
Try it again removing the first name in cell A3. Notice that the macro stops on line 2.
Here is a sample of what you will find in chapter 6
of the downloadable Tutorial on Excel macros
Testing Macros in the VBE for Excel
Testing the VBA procedure step by step
NOTE: While you are running the macro step by step you can stop the execution at any tim
clicking on the stop button in the toolbar.
Testing is the most time-consuming part of any VBA project. During the development of a project
use 20% of your time analysing and designing, 15% programming and 65% testing.
During the testing phase, you will correct bugs, typos and the logical errors. More importantly you
improve your original project, fine tune it, discover better ways to do things and add code.
In lesson 4 you have created your first macro and tested it using the "Run" button. You can also te
macro step by step.
Print this page, open Excel and a open a new workbook. Use ALT/F11 to open the Visual Basic E
you learned in lesson 1.
Step 1: Go to Excel and make sure that cells A1, A2 and A3 of Sheet1 are empty.
Step 2: In VBE go to the Code window of Sheet1 and copy/paste the following macro:
Sub proFirst()
Range("A1").Value = 34
Range("A2").Value = 66
Range("A3").Formula = "=A1+A2"
Range("A1").Select
End Sub
Step 3: Click anywhere within the macro and then press the F8 key at the top of your keyboard. V
highlights the first line of code in yellow.
Step 4: Right-click on the small yellow arrow and see a menu appear
In lesson 4 of the downloadable Tutorial on VBA for Excel you will learn about these precious
items and everything else that you can do in the Code window. For now let's finish testing this ma
by step.
Step 5: Press on "F8" a second time. No line has been executed yet and if you go to Excel you wi
cells A1 to A3 are still empty. The next time you press "F8" , VBE will execute the yellow-highlighte
Step 6: Press "F8" a third time. The yellow-highlighted line is now "Range("A2").Value = 66". VBE
executed the previous line "Range("A1").Value = 34" has been executed so if you go to Excel (AL
you will see 32 in cell A1.
Step 7: Come back to VBE (ALT/F11) and press "F8" again. Go to Excel and see what happened
A2.
Step 8: Come back to VBE (ALT/F11) and press "F8" again. Go to Excel and see that there is a fo
cell A3.
Step 9: Come back to the VBE (ALT/F11) and press "F8" again, cell A1 is now selected in Excel.
Step 10: Press "F8" again. Nothing happens in Excel but "End Sub" is highlighted in yellow
Step 11: Press "F8" again. Nothing happens in Excel no more lines in VBE are highlighted in yello
The macro hac been tested, the test is over.
In the code change the addresses A1, A2 and A3 respectively to B1, B2 and B3. Test the macro
it as many times as you want.
You have tested a macro step by step. In the downloadable tutorial you will learn how to test pa
macro, how to come back a few lines, make changes and re-execute these lines. You will also dis
most important functionality, how to share the screen between Excel and VBE.
In no other programming environment can you test a procedure step by step while seeing
in the spreadsheet on a single screen.
In the picture below you can see the Visual Basic Editor on the left side of a screen and Excel on
side. While you press the F8 key to execute the macro step by step in the Visual Basic Editor, you
what is happening in the Excel spreadsheet. You will discover the split screen function in lesson 6
thedownloadable the course on VBA for Excel (Macros).
Here is a sample of what you will find in chapter chapter 7
of the downloadable Tutorial on Excel macros
The Macro Recorder
IMPORTANT NOTE 1: There are no risks to your computer or to Excel in completing the exercise
At any time if you feel uncomfortable just close Excel without saving the workbook and retry later.
IMPORTANT NOTE 2 (for Excel 2007 ONLY) : You can only complete the exercises below if you
installed VBA for Excel on your computer. If you do not have, click here.
One of the tools that makes the programming environment in Excel unique is the Excel Macro Re
When you start the macro recorder anything you do in Excel is recorded as a new macro. That ma
macro recorder the best VBA teacher and also a great assistant who will write a lot of the words a
sentences that you need without a single typo. It will also be there when you do not remember so
that you do not use often. Even after many years of programming you will still use the macro reco
not to learn anymore but to write code (VBA words and sentences).
With the Excel macro recorder you can not develop a macro that will damage Excel or you
computer so try anything and learn.
In this lesson on line you will record a macro and run it.
Recording Your First New Macro:
Step 1: Print this page.
Step 2: Open Excel and a new workbook.
Step 3: Go to the "Developer" ribbon to click on
Step 4: A small window appears titled "Record Macro". We will review its components in thedown
tutorial. For now just click on "OK".
When you do so the small window disappears and in the "Developer" ribbon i
by telling you that you are going in the right direction. The macro recorder is ON
Step 5: In the sheet below (Sheet1) select cells B1 to B5, go to "Sheet2", select cell B6, come ba
"Sheet1" and select cells D2 to D5.
Step 6: In the "Developer" ribbon click on
Running your first recorded macro
Step 1: Select cell "A1" of "Sheet1".
Step 2: In the "Developer" ribbon click on
Step 3: In the window that appears Macro1 is selected.
Again we will forget about the components of this window because we will study them in thedown
tutorial. For now, just click "Run".
Step 4: See how fast the macro runs. You do not even see Excel go to Sheet2 (but it does). At th
the execution cells D2 to D5 are selected.
What took you around 5 seconds to do manually (step 5 of the first exercise) took Excel a fraction
second. Excel can work much faster than you can. Welcome to the marvelous world of VBA for E
(Macros).
You can repeat steps 1 to 4 of this second exercise as often as you like.
Looking at your first recorded macro
To complete this third exercise you must have studied chapters 1 to 4.
Go to the Visual Basic editor and you will see the following macro in the code window when you d
click on Module 1 in the Project Window:
Sub Macro1()
' Macro1 Macro
Range("B1:B5").Select
Sheets("Sheet2").Select
Range("B6").Select
Sheets("Sheet1").Select
Range("D2:D5").Select
End Sub
As you can see the macro recorder recorded your instructions in a language that Excel understan
You can now use VBA's written code to have Excel perform this task.
Never forget that the Excel macro recorder is your best teacher and will remain a great assistant f
rest of your VBA developer's life.
Here is a sample of what you will find in chapter 8
of the downloadable Tutorial on Excel macros
Macros Help and Assistance
There is plenty of help and assistance available within Excel when you develop macros. As you h
discovered in the previous lesson the Macro Recorder is a great teacher and assistant. In this les
investigate the two other sources of assistance within the Visual Basic Editor of Excel: the Help F
the Object Browser.
Here is how the Object Browser appers when you call it. ALL the VBA words are presented in this
including useful examples. The search function is powerful.
Here is a sample of what you will find in chapter 9
of the downloadable Tutorial on Excel macros
Starting, triggering a Macro in Excel
Note 2: Print this page, open Excel and a open a new workbook. Use ALT/F11 to open the Visua
Editor as you learned in lesson 1.
When does the VBA procedure (macro) start? When an EVENT happens. The event is what trigg
VBA Excel procedure. In earlier lessons you have used an event to start your macros. In the Visu
Editor you have gone to the menu bar and clicked on "Run/Run Sub/Userform" and the macro wa
executed. You have also clicked on the F8 key at the top of your keyboard and the macro got exe
by line.
You do not want your user to go to the Visual Basic Editor to trigger a macro. A lot of other events
happen to start a macro. The event that is mostly (85%) of macros used is clicking on a button. Th
can be on the worksheet or on a userform that you would develop. The event can also be: openin
workbook, selecting a sheet, the value of a cell changing due to a manual input or due to the reca
of a formula, clicking on a selected keystroke or going to the right menu item in Excel.
Preparing the Exercise on Events
To complete the following exercises, copy paste the code below from your browser to the code wi
"Sheet1" of the new Excel workbook as you have learned in previous lessons.
Sub proFirst()
Range("A1" ).Value = 34
Range("A2" ).Value = 66
Range("A3" ).Formula = "=A1+A2"
Range("A1" ).Select
End Sub
Macros Triggered from the Developer Ribbon
Step 1: Select "Macros" from the "Developer" ribbon. You will see the "Macro" dialog window belo
Step 2: "Sheet1.proFirst" being selected in the list box and its name appearing in the text box abo
box just click "Run". The macro is automatically executed
Step 3: Erase the contents of cells A1, A2 and A3
You now see that colleagues must have installed VBA on their own computer to be able to use yo
macros from the "Developer" ribbon.
Macros Triggered by a Keystroke
In this second first exercise on events we will get the macro to be keyboard activated by capital "s
(Shift/S). First you need to program a key. To do so:
Step 1: Select "Macros" from the "Developer" ribbon. You will see the "Macro" dialog window belo
Step 2: "Sheet1.proFirst" being selected in the list box and its name appearing in the text box abo
box just click on "Options". A new dialog window "Macro Options" appears:
Step 3: In the shortcut key text box enter a capital "s" "SHIFT/s" and then click "OK". Click "Cance
dialog window
Step 4: If you now click "CTRL/SHIFT/S" the macro will be executed instantly.
Macros Triggered by Clicking on a Text Box on the Worksheet
More than 90% of the macros are triggered by a click on a button located on a worksheet.
We prefer using text boxes rather than VBA command buttons because they are much easier to m
and allow much more creativity in the design. You can use the font that you like and the backgrou
that fits your needs. If you are a little creative you can add 3D effects, special borders and others.
Step 1: From the "Insert ribbon" click on the "Text Box" icon once. Lower the curser toward the sh
and hold the left button of the mouse and stretch the text box to the desired dimension.
Step 2: Right click on the text box, select "Assign Macro" from the menu and the "Assign Macro" d
window appears:
Step 3: Select "Sheet1.proFirst" from the list box and its name appears in the text box above the l
just click on "OK".
Step 3: Click away from the text box on the Excel sheet.
Step 4: Left click on the text box and the macro is executed.
You can assign macros to text boxes, images or WordArt using the same approach.
Here is a sample of what you will find in lchapter10
of the downloadable Tutorial on Excel macros
VBA Macros Security and Protection in Excel
Note 1: You will change the security setting one single time. You will not have to do it again. Tell
colleagues about it specially if you want to send them Excel workbooks with macros. The setting s
here is totally safe and you will not make your computer vulnerable to any virus.
Special note for users of Excel 2007: See how to install the Visual Basic Editor from your Of
CDand set the security level of your Excel.
If you send a workbook with macros to a colleague and he can not get them to work it is probably
his security setting is at "High" . Tell him how to change his level of security by going to the "Deve
ribbon, clicking on "Macro Security", selecting "Macro Settings and checking the second level "Di
Macros with Notification" and you are set.
From then on each time you open a workbook that contains macros a temporary status bar appea
the grid in Excel:
Click on "Options" and the following dialog window will appear.
Adopt the same attitude as you have with documents attached to Emails. If you know the origin of
you may enable the macros if not click on "Disable Macros" and you are fully protected. You can
workbook but the VBA procedures (macros) are not operational. You can go to the Visual Basic E
take a look at the macros. If nothing looks suspicious close the workbook and re-open it enabling
macros.
Password Protecting the code
As an Excel-VBA Developer you might want to protect your code so that nobody else may modify
VBE editor go to "Tools/VBAProject Properties/Protection" . Check the box and submit a passwor
sure that you save the password somewhere that you will remember. If ever you loose the passw
important workbook you can always buy a program on the Internet that will allow you to view the c
if it is password protected.
Remember that passwords are like any locks, they only keep the honest people out.
To organize your discovery of Excel macros, the downloadable Tutorial on Excel Macros is
in three sections (all 3 sections part of the single download):
Section 1: Excel Macros Programming (Chapters 1 to 10)
This section is about recording, writing, modifying and testing macros in the Visual Basic Editor. You will a
learn about security and discover "events" (an event is what starts the macro).
Section 2: Excel VBA Vocabulary (Chapters 11 to 23)
Developing a macro is communicating with Excel and to do so you need to use a language called Visual B
Applications (VBA). In section 2 you will learn all the VBA vocabulary that is essential to work with busines
(accounting, sales, production and others).
Section 3: Forms and Controls in VBA for Exce (Chapters 24 to 33)
The userform is a small or large dialog window that you create and allows the user to submit values that w
by your macros. To these userforms you will add controls (command buttons, text boxes, list boxes and ot
program them.
Home » Excel-VBA-Tutorial » VBA-Code-Presentation
Excel VBA Tutorial Part 1 - VBA Code Presentation
When learning to produce VBA code, it is important, from the very start, that you adopt good
habits in terms of code presentation, so that it is easy to read the code and understand how it
works.
While you may, at the time you are writing the code, have a clear idea of what it does and how
it works, you need to consider what the code will look like when you return to it in 6 months'
time. Worse still, what if someone else needs to work on your code and has to figure out how it
works?
This page discusses comments, code indentation and line breaks all of which will assist in
making your code clearer and easier to interpret.
Comments
The single most important practice for writing clear, decipherable code is to add frequent
comments.
Comments are lines in your code which act as notes to yourself or others, to explain what the
code means or what it is doing.
Comments are not executed during the running of the program, so have no impact on the result
your macro. VBA considers any line that starts with an apostraphe (') to be a comment and the
Excel VBA editor highlights these lines by colouring them in green, so you can see, at a glance,
that they are comments and will not be executed.
See the example below, which shows comments used to clarify the details of a simple Sub
procedure:
' Sub procedure to search cells A1-A100 of the current active
' sheet, and find the cell containing the supplied string
Sub Find_String(sFindText As String)
Dim i As Integer ' Integer used in 'For' loop
Dim iRowNumber As Integer ' Integer to store result in
iRowNumber = 0
' Loop through cells A1-A100 until 'sFindText' is found
For i = 1 To 100
If Cells(i, 1).Value = sFindText Then
' A match has been found to the supplied string
' Store the current row number and exit the 'For' Loop
iRowNumber = i
Exit For
End If
Next i
' Pop up a message box to let the user know if the text
' string has been found, and if so, which row it appears on
If iRowNumber = 0 Then
MsgBox "String " & sFindText & " not found"
Else
MsgBox "String " & sFindText & " found in cell A" & iRowNumber
End If
End Sub
Don't worry if you don't understand some of the code in the example above - this will be
explained later in this tutorial. The example has been included simply to show how comments
are used to explain each section of the code.
It is easy to get lazy about adding comments to your code, but it really is worth making the
effort. The minutes invested in ensuring your code is well documented could save you hours of
frustration in the long term.
Code Indentation
Another way of assisting in making your code readable is by adding indentations to it. You can
see how, in the example above, the code has been indented within the main Sub procedure and
then indented further inside individual blocks of code. These indented sections enable you to
easily see where each block of code starts and ends.
Line Breaks
Your code can also be made more readable by inserting line breaks in the middle of long lines of
code. In VBA, if you want to split a line up, you need to add a space followed by an underscore (
_) just before the line break. This tells the VBA compiler that the current line of code continues
on the following line.
The following example shows how simple line breaks can be used to make long lines of code
much easier to read and understand.
Consider the following 'If' statement:
If (index = 1 And sColor1 = "red") Or (index = 2 And sColor1 = "blue") Or (index = 3 And sColor1
= "green") Or (index = 4And sColor1 = "brown") Then
By adding line breaks the same 'If' statement can be presented as follows:
If (index =1 AndsColor1 = "red") Or _
(index =2 AndsColor1= "blue") Or_
(index =3 AndsColor1= "green") Or_
(index =4 AndsColor1= "brown") Then
When the 'If' statement is broken up over four lines, you can see the different conditions within
the 'If' statement much more clearly. This example illustrates how presenting your code in a
clear way can help you to produce readable code, which will help you to avoid introducing bugs
or errors.
xcel VBA Tutorial Part 3 - Excel Visual Basic Arrays
Excel Visual Basic arrays are structures which are used to store a set of related variables of the
same type. Each of the entries in the array can be accessed by an index number.
For example, if you had 20 members of a team and you wanted to store all the names for use in
your VBA code. You could declare 20 variables to hold the team member names, as follows:
Dim Team_Member1 As String
Dim Team_Member2 As String
.
.
.
Dim Team_Member20 As String
Alternatively, you could use the much simpler and more organised method of storing the Team
members in an array of 20 String variables:
Dim Team_Members(1 To 20) As String
Once you have declared the array as above, each entry of the array is populated as follows:
Team_Members(1) = "John Smith"
.
.
.
A further advantage of storing your data in an array, rather than in individual variables, arises if
you want to perform the same action on every member of the list. If your team member names
were stored in 20 individual variables, you would need 20 lines of code to carry out a specific
action on each name. However, if you have stored your names in an array, you can use a simple
loop to carry out the action for each entry in the array.
This is shown in the example code below, which prints out each name in the Team_Members
array to a cell in Column A of the current Excel Worksheet:
For i = 1 To 20
Cells(i,1).Value = Team_Members(i)
Next i
It is clear from the above that handling an array of 20 names is much less cumbersome and
more organised than handling 20 individual variables, but imagine if you had 1,000 names to
store! And imagine you wanted to store Surnames separately from Forenames! It is clear that it
would soon become almost impossible to handle this amount of data without the use of Arrays
in your VBA code.
Multi-Dimensional Excel Visual Basic Arrays
The Visual Basic Arrays discussed above are one-dimensional, in that they refer to one list of
Names. However, arrays can have multiple dimensions. An array having two dimensions acts as
a grid of values.
For example, imagine that you want to store daily sales figures for the month of January, for 5
different teams. You would need a 2-dimensional array, consisting of 5 sets of figures over 31
days. You would then declare the array as follows:
Dim Jan_Sales_Figures(1 To 31, 1 To 5) As Currency
In order to access the entries in the array 'Jan_Sales_Figures', you need to use two indices,
refering to the day of the month and the team number. For example, the sales figures for
Team2 on January 15th would be referenced as:
Jan_Sales_Figures(15, 2)
You can declare arrays with 3 or more dimensions in the same way - i.e. by adding further
dimensions into the declaration and using a further index to reference the array entries.
Declaring Excel Visual Basic Arrays
The above sections have already given some examples of Visual Basic Array declarations, but it
is worth discussing this further. As seen above, a one-dimensional array can be declared as
follows:
Dim Team_Members(1 To 20) As String
This declaration tells the VBA compiler that the array 'Team_Members' has 20 variables, which
are referenced by indices 1 to 20. However, we could also decide to number our array variables
from 0 to 19, in which case the declaration would be:
Dim Team_Members(0 To 19) As String
In fact, the default form of array indexing is to start at 0, so if you omit the start index from the
declaration, and simply declare the array as:
Dim Team_Members(19) As String
Then the VBA compiler will understand this to be an array of 20 variables, which are indexed
from 0 to 19.
The same rules are applied to declarations of multi-dimensional Visual Basic arrays. As shown in
the previous example, a two-dimensional array is declared by separating the dimension indices
by a comma:
Dim Jan_Sales_Figures(1 To 31, 1 To 5) As Currency
However, if we omit the start indices from both dimensions, as follows:
Dim Jan_Sales_Figures(31, 5) As Currency
this is understood to be a two-dimensional array in which the first dimension has 32 entries,
indexed from 0 to 31 and the second dimension has 6 entries, indexed from 0 to 5.
Dynamic Arrays
In the above examples, the arrays all have fixed dimensions. However, in many cases, we don't
know how big an array is going to be before run time. We could solve this be declaring a huge
array, in an attempt to cover the maximum possible size needed, but this would use up an
unnecessarily large amount of memory and could slow down your program. A better option
would be to use a Dynamic array, which is an array that can be sized and re-sized as many times
as you like, during the execution of a macro.
A dynamic array is declared with empty parentheses, as follows:
Dim Team_Members() As String
You then need to declare the dimension of the array during the execution of the code, using
the ReDim statement:
ReDim Team_Members(1 To 20)
If, during the execution of the code, you need to extend the size of your array, you can
use ReDim again:
If Team_Size > 20 Then
ReDim Team_Members(1 To Team_Size)
End If
It should be noted that resizing a dynamic array in this way will result in the loss of all the
values that had previously been stored in the array. If you want to avoid this loss, and keep the
values that have previously been assigned to the array, you need to use the "Preserve"
keyword, as shown below:
If Team_Size > 20 Then
ReDim Preserve Team_Members(1 To Team_Size)
End If
The disadvantage of using the "Preserve" keyword when resizing Visual Basic Arrays is that you
can only change the upper bound of an array, not the lower bound. Also, if you have a multi-
dimensional array, the use of the "Preserve" keyword limits you to changing only the last
dimension of the array.
Excel VBA Tutorial Part 4 - VBA Function & Sub Procedures
Built-In VBA Functions
Before creating your own VBA Functions, it is useful to know that Excel VBA already has a large
number of built-in functions that you can use in your code.
You can view a list of these from the VBA Editor:
 From an Excel Workbook, open up the VBA Editor (by pressing ALT-F11);
 Press F2 to open up the Object Browser;
 Select VBA in the drop-down listin the top left corner of the Object Browser;
 The listthat appears shows the VBA built in classes, members and functions. If you click on a
function name a brief description appears at the bottom of the window; Pressing F1 brings up the
online help for that function.
Alternatively, a list of built-in VBA functions, with examples, is provided on the VBA Functions
page or the Tech on the Net website.
User-Defined VBA Function & Sub Procedures
In Excel Visual Basic, a set of commands to perform a specific task is placed into a procedure,
which can be aFunction procedure or a Sub procedure (also known as functions and
subroutines).
The main difference between a VBA Function procedure and a Sub procedure is that a Function
procedure returns a result, whereas a Sub procedure does not.
Therefore, if you wish to perform a task that returns a result (e.g. summing of a group of
numbers), you will generally use a Function procedure, but if you just need a set of actions to
be carried out (e.g. formatting a set of cells), you might choose to use a Sub procedure.
Arguments
VBA procedures can be passed data via arguments, which are declared in the procedure
definition. For example, you might have a VBA Sub procedure that adds an Integer to every cell
in the current range. You could supply the value of the integer to the Sub via an argument, as
follows:
Sub AddToCells(i As Integer)
.
.
.
End Sub
Note that it is not essential for VBA Functions or Subs to have arguments. Some procedures
may not require them.
Optional Arguments
You can also define VBA procedures to have Optional arguments. These are arguments that the
user can supply if they want, but if they are omitted, the procedure will assign a default value to
them.
To return to the example above, if we wanted to make the supplied integer argument optional,
this would be declared as follows:
Sub AddToCells(Optional i As Integer = 0)
In this case, the supplied integer, i, has a default value of 0.
You can use multiple Optional arguments in a VBA procedure, as long the Optional arguments
are all positioned at the end of the argument list.
Passing Arguments By Value and By Reference
When arguments are passed to VBA procedures, they can be passed in two ways:
 ByVal - The argumentispassedby Value.Thismeansthatjustthe value (i.e.acopy of the argument)
ispassedto the procedure andtherefore,anychanges thatare made to the argumentinside the
procedure will be lostwhenthe procedure isexited.
 ByRef - The argumentispassedbyReference.Thismeansthatthe addressof the argumentispassed
to the procedure.Anychangesthatare made to the argumentinside the procedure will
be remembered whenthe procedure isexited.
You can specify whether an argument is passed to a VBA procedure by value or by reference by
using the ByVal or theByRef keyword when defining the procedure. This is shown below:
Sub AddToCells(ByVal i As
Integer)
.
.
.
End Sub
In this case, the integer i is passed by Value. Any changes that are made
to i will be lost when you exit the Sub procedure.
Sub AddToCells(ByRef i As
Integer)
.
.
.
End Sub
In this case, the integer i is passed by Reference. When you exit the Sub,
any changes that have been made to i will be remembered by the
variable that was passed into the Sub procedure.
It should be noted that by default, in VBA, arguments are passed by Reference. Therefore, if
you do not use the ByValor the ByRef keyword, the arguments will be passed by Reference.
Before discussing further properties of VBA Function and Sub procedures, it is useful to look at
the two types of procedure individually. The following two sections provide a brief discussion of
VBA Function and VBA Sub procedures, along with simple examples.
VBA Function Procedures
The VBA editor recognises a Function procedure, because the commands are positioned
between the following start and end commands:
Function
.
.
.
End Function
As previously mentioned, VBA function procedures (unlike sub procedures) return a value. The
return values have the following rules:
 The data type of the returnedvalue mustbe declared inthe Functionheader.
 The value to be returnedmustbe assignedtoa variable havingthe same name asthe Function.This
variable doesnotneedtobe declared,asitalreadyexistsasa part of the function.
This is illustrated in the following example.
VBA Function Procedure Example: Perform a Mathematical Operation on 3 Numbers
The following code shows an example of a simple VBA Function procedure that receives three
arguments, each of which are 'Doubles' (double precision floating point numbers). The Function
returns a further 'Double', which is the sum of the first two arguments, minus the third
argument:
Function SumMinus(dNum1 As Double, dNum2 As Double, dNum3 As Double) As Double
SumMinus = dNum1 + dNum2 - dNum3
End Function
The above very simple VBA Function procedure illustrates the way in which data arguments are
supplied to a procedure. It is also seen that the Function procedure return type is defined as
being a 'Double' (i.e. by the term "As Double" which is included after the Function arguments).
The above example also shows how the Function procedure result is stored in a variable that
has the same name as the Function.
Calling VBA Function Procedures
If the above simple Function procedure is typed into a Module in the Visual Basic Editor, it will
then be available to be called from other VBA procedures or to be used in the worksheets of
your Excel workbook.
Calling a VBA Function Procedure From Another Procedure
You can call a Function procedure from within another VBA procedure by simply assigning the
Function to a variable. The following example shows a call to the simple SumMinus function
that was defined above:
Sub main()
Dim total as Double
total = SumMinus(5, 4, 3)
End Sub
Calling a VBA Function Procedure From A Worksheet
You can call VBA Function procedures from an Excel Worksheet, in the same way as you can call
any of the built-in Excel functions.
Therefore, you could call the SumMinus Function procedure by typing the following into any
cell of your worksheet:
=SumMinus(10, 5, 2)
VBA Sub Procedures
The VBA editor recognises a Sub procedure, because the commands are positioned between
the following start and end commands:
Sub
.
.
.
End Sub
VBA Sub Procedure Example 1: Center and Apply Font Size to a Selected Range of Cells
The following code shows an example of a simple VBA Sub procedure that applies formatting to
the current selected cell range. The cells are formatted to be aligned centrally (both
horizontally and vertically) and to have a user-supplied font size:
Excel trick
Excel trick
Excel trick
Excel trick
Excel trick
Excel trick
Excel trick

Contenu connexe

Tendances

Excel Excellence (Microsoft Excel training that "sticks"): Macros
Excel Excellence (Microsoft Excel training that "sticks"): MacrosExcel Excellence (Microsoft Excel training that "sticks"): Macros
Excel Excellence (Microsoft Excel training that "sticks"): MacrosLaura Winger
 
Excel Excellence (Microsoft Excel training that "sticks"): Formulas
Excel Excellence (Microsoft Excel training that "sticks"): FormulasExcel Excellence (Microsoft Excel training that "sticks"): Formulas
Excel Excellence (Microsoft Excel training that "sticks"): FormulasLaura Winger
 
Entering Data - Excel 2013 Tutorial
Entering Data - Excel 2013 TutorialEntering Data - Excel 2013 Tutorial
Entering Data - Excel 2013 TutorialSpreadsheetTrainer
 
Advanced Excel formulas, v look up, count, count if, pivot tables, filters
Advanced Excel formulas, v look up, count, count if, pivot tables, filters Advanced Excel formulas, v look up, count, count if, pivot tables, filters
Advanced Excel formulas, v look up, count, count if, pivot tables, filters DevadattaSai Cheedella
 
Excel Formulas Functions
Excel Formulas FunctionsExcel Formulas Functions
Excel Formulas Functionssimply_coool
 
Row, Column, Index, Match, Offset Functions. Excel Tutorial
Row, Column, Index, Match, Offset Functions. Excel TutorialRow, Column, Index, Match, Offset Functions. Excel Tutorial
Row, Column, Index, Match, Offset Functions. Excel TutorialIlgar Zarbaliyev
 
Excel functions formulas
Excel functions formulasExcel functions formulas
Excel functions formulasLearnIT@UD
 
Excel Formulas Functions 2007
Excel Formulas Functions 2007Excel Formulas Functions 2007
Excel Formulas Functions 2007simply_coool
 
10 Excel Formulas that will help you in any Job
10 Excel Formulas that will help you in any Job10 Excel Formulas that will help you in any Job
10 Excel Formulas that will help you in any JobHitesh Biyani
 
Simple formulas excel
Simple formulas excelSimple formulas excel
Simple formulas excelMalika khalil
 
Module 5 entering data in worksheet
Module 5 entering data in worksheetModule 5 entering data in worksheet
Module 5 entering data in worksheetDr. Shalini Pandey
 
Cash flow using excel
Cash flow using excelCash flow using excel
Cash flow using excelMalika khalil
 
Sample Excel 2013 Advanced Essentials
Sample Excel 2013 Advanced EssentialsSample Excel 2013 Advanced Essentials
Sample Excel 2013 Advanced Essentialslearnbydoing
 
Excel Data Management
Excel Data ManagementExcel Data Management
Excel Data ManagementRachel Espino
 
New Dynamic Array Functions. Excel Tutorial
New Dynamic Array Functions. Excel TutorialNew Dynamic Array Functions. Excel Tutorial
New Dynamic Array Functions. Excel TutorialIlgar Zarbaliyev
 
Worksheet Basics & Navigation - Excel 2013 Tutorial
Worksheet Basics & Navigation - Excel 2013 TutorialWorksheet Basics & Navigation - Excel 2013 Tutorial
Worksheet Basics & Navigation - Excel 2013 TutorialSpreadsheetTrainer
 

Tendances (19)

Excel Excellence (Microsoft Excel training that "sticks"): Macros
Excel Excellence (Microsoft Excel training that "sticks"): MacrosExcel Excellence (Microsoft Excel training that "sticks"): Macros
Excel Excellence (Microsoft Excel training that "sticks"): Macros
 
Excel Excellence (Microsoft Excel training that "sticks"): Formulas
Excel Excellence (Microsoft Excel training that "sticks"): FormulasExcel Excellence (Microsoft Excel training that "sticks"): Formulas
Excel Excellence (Microsoft Excel training that "sticks"): Formulas
 
Entering Data - Excel 2013 Tutorial
Entering Data - Excel 2013 TutorialEntering Data - Excel 2013 Tutorial
Entering Data - Excel 2013 Tutorial
 
Advanced Excel formulas, v look up, count, count if, pivot tables, filters
Advanced Excel formulas, v look up, count, count if, pivot tables, filters Advanced Excel formulas, v look up, count, count if, pivot tables, filters
Advanced Excel formulas, v look up, count, count if, pivot tables, filters
 
Excel Formulas Functions
Excel Formulas FunctionsExcel Formulas Functions
Excel Formulas Functions
 
Row, Column, Index, Match, Offset Functions. Excel Tutorial
Row, Column, Index, Match, Offset Functions. Excel TutorialRow, Column, Index, Match, Offset Functions. Excel Tutorial
Row, Column, Index, Match, Offset Functions. Excel Tutorial
 
Formula in MS Excel
Formula in MS ExcelFormula in MS Excel
Formula in MS Excel
 
Excel11
Excel11Excel11
Excel11
 
Excel functions formulas
Excel functions formulasExcel functions formulas
Excel functions formulas
 
Excel Formulas Functions 2007
Excel Formulas Functions 2007Excel Formulas Functions 2007
Excel Formulas Functions 2007
 
10 Excel Formulas that will help you in any Job
10 Excel Formulas that will help you in any Job10 Excel Formulas that will help you in any Job
10 Excel Formulas that will help you in any Job
 
Simple formulas excel
Simple formulas excelSimple formulas excel
Simple formulas excel
 
Module 5 entering data in worksheet
Module 5 entering data in worksheetModule 5 entering data in worksheet
Module 5 entering data in worksheet
 
Cash flow using excel
Cash flow using excelCash flow using excel
Cash flow using excel
 
Sample Excel 2013 Advanced Essentials
Sample Excel 2013 Advanced EssentialsSample Excel 2013 Advanced Essentials
Sample Excel 2013 Advanced Essentials
 
Excel Data Management
Excel Data ManagementExcel Data Management
Excel Data Management
 
New Dynamic Array Functions. Excel Tutorial
New Dynamic Array Functions. Excel TutorialNew Dynamic Array Functions. Excel Tutorial
New Dynamic Array Functions. Excel Tutorial
 
Worksheet Basics & Navigation - Excel 2013 Tutorial
Worksheet Basics & Navigation - Excel 2013 TutorialWorksheet Basics & Navigation - Excel 2013 Tutorial
Worksheet Basics & Navigation - Excel 2013 Tutorial
 
Excel help 01
Excel help 01Excel help 01
Excel help 01
 

En vedette

Converted by pdf suite
Converted by pdf suiteConverted by pdf suite
Converted by pdf suiteduangduand
 
Prolog (present)
Prolog (present) Prolog (present)
Prolog (present) Melody Joey
 
Презентация слайды2
Презентация слайды2Презентация слайды2
Презентация слайды2goryakiny
 
Research 2
Research 2Research 2
Research 2rkatungi
 
พีระมิด
พีระมิดพีระมิด
พีระมิดduangduand
 
ใบงานที่4เซลล์
ใบงานที่4เซลล์ใบงานที่4เซลล์
ใบงานที่4เซลล์TANIKAN KUNTAWONG
 
Lets see the reality around us
Lets see the reality around usLets see the reality around us
Lets see the reality around usTishi Bali
 
Demo: How to make air refreshener ? (Powder form & Spray form)
Demo: How to make air refreshener ?(Powder form & Spray form)Demo: How to make air refreshener ?(Powder form & Spray form)
Demo: How to make air refreshener ? (Powder form & Spray form)Melody Joey
 
ทรงกระบอก
ทรงกระบอกทรงกระบอก
ทรงกระบอกduangduand
 
ทรงกลม
ทรงกลมทรงกลม
ทรงกลมduangduand
 
ใบงาน
ใบงานใบงาน
ใบงานduangduand
 
Directed decision phase locked loop
Directed decision phase locked loopDirected decision phase locked loop
Directed decision phase locked loopHitham Jleed
 

En vedette (20)

Converted by pdf suite
Converted by pdf suiteConverted by pdf suite
Converted by pdf suite
 
Prolog (present)
Prolog (present) Prolog (present)
Prolog (present)
 
Презентация слайды2
Презентация слайды2Презентация слайды2
Презентация слайды2
 
Diapositivas
DiapositivasDiapositivas
Diapositivas
 
Research 2
Research 2Research 2
Research 2
 
กรวย
กรวยกรวย
กรวย
 
พีระมิด
พีระมิดพีระมิด
พีระมิด
 
ใบงานที่4เซลล์
ใบงานที่4เซลล์ใบงานที่4เซลล์
ใบงานที่4เซลล์
 
Physics
PhysicsPhysics
Physics
 
Gross u11a3
Gross u11a3Gross u11a3
Gross u11a3
 
Lets see the reality around us
Lets see the reality around usLets see the reality around us
Lets see the reality around us
 
Mot 3033
Mot 3033Mot 3033
Mot 3033
 
Demo: How to make air refreshener ? (Powder form & Spray form)
Demo: How to make air refreshener ?(Powder form & Spray form)Demo: How to make air refreshener ?(Powder form & Spray form)
Demo: How to make air refreshener ? (Powder form & Spray form)
 
Black Box Testing
Black Box TestingBlack Box Testing
Black Box Testing
 
ทรงกระบอก
ทรงกระบอกทรงกระบอก
ทรงกระบอก
 
ทรงกลม
ทรงกลมทรงกลม
ทรงกลม
 
ใบงาน
ใบงานใบงาน
ใบงาน
 
SaaS con Symfony2
SaaS con Symfony2SaaS con Symfony2
SaaS con Symfony2
 
Directed decision phase locked loop
Directed decision phase locked loopDirected decision phase locked loop
Directed decision phase locked loop
 
الخروج
الخروجالخروج
الخروج
 

Similaire à Excel trick

03 Logical functions.pdf
03 Logical functions.pdf03 Logical functions.pdf
03 Logical functions.pdfRizwanAli988729
 
ICDL Advanced Excel 2010 - Tutorial
ICDL Advanced Excel 2010 - TutorialICDL Advanced Excel 2010 - Tutorial
ICDL Advanced Excel 2010 - TutorialMichael Lew
 
IMPORTRANGE-1.pptx
IMPORTRANGE-1.pptxIMPORTRANGE-1.pptx
IMPORTRANGE-1.pptxKetanSehdev3
 
Lisa Donaldson Notes
Lisa Donaldson NotesLisa Donaldson Notes
Lisa Donaldson NotesIBAT College
 
Excel for SEO -from Distilled UK
Excel for SEO -from Distilled UKExcel for SEO -from Distilled UK
Excel for SEO -from Distilled UKEldad Sotnick-Yogev
 
CBN Advanced Excel Training Slide.pptx
CBN Advanced Excel Training Slide.pptxCBN Advanced Excel Training Slide.pptx
CBN Advanced Excel Training Slide.pptxEdwinAdeolaOluwasina1
 
Top tips from the experts on how to learn Excel
Top tips from the experts on how to learn ExcelTop tips from the experts on how to learn Excel
Top tips from the experts on how to learn ExcelStat Analytica
 
Top 20 microsoft excel formulas you must know
Top 20 microsoft excel formulas you must knowTop 20 microsoft excel formulas you must know
Top 20 microsoft excel formulas you must knowAlexHenderson59
 
Empowerment Technologies - Module 5
Empowerment Technologies - Module 5Empowerment Technologies - Module 5
Empowerment Technologies - Module 5Jesus Rances
 
Excel functionssimplymeasured
Excel functionssimplymeasuredExcel functionssimplymeasured
Excel functionssimplymeasuredcentral.zone
 
Most important excel functions &amp; shortcuts
Most important excel functions &amp; shortcutsMost important excel functions &amp; shortcuts
Most important excel functions &amp; shortcutsMike Willy
 
Excel-eBook.pdf
Excel-eBook.pdfExcel-eBook.pdf
Excel-eBook.pdfbill291588
 
Excel-Ebook.pdf
Excel-Ebook.pdfExcel-Ebook.pdf
Excel-Ebook.pdfMihir Soni
 
Introduction to excel - application to statistics
Introduction to excel - application to statisticsIntroduction to excel - application to statistics
Introduction to excel - application to statisticszavenger
 
Ms excel 2007 tutorial
Ms excel 2007 tutorialMs excel 2007 tutorial
Ms excel 2007 tutorialjks2010
 
How to if function
How to if functionHow to if function
How to if functionhansenk1002
 

Similaire à Excel trick (20)

03 Logical functions.pdf
03 Logical functions.pdf03 Logical functions.pdf
03 Logical functions.pdf
 
ICDL Advanced Excel 2010 - Tutorial
ICDL Advanced Excel 2010 - TutorialICDL Advanced Excel 2010 - Tutorial
ICDL Advanced Excel 2010 - Tutorial
 
IMPORTRANGE-1.pptx
IMPORTRANGE-1.pptxIMPORTRANGE-1.pptx
IMPORTRANGE-1.pptx
 
Lisa Donaldson Notes
Lisa Donaldson NotesLisa Donaldson Notes
Lisa Donaldson Notes
 
Excel tips and tricks you should try
Excel tips and tricks you should tryExcel tips and tricks you should try
Excel tips and tricks you should try
 
Grade 6 computer
Grade 6 computer Grade 6 computer
Grade 6 computer
 
Excel for SEO -from Distilled UK
Excel for SEO -from Distilled UKExcel for SEO -from Distilled UK
Excel for SEO -from Distilled UK
 
CBN Advanced Excel Training Slide.pptx
CBN Advanced Excel Training Slide.pptxCBN Advanced Excel Training Slide.pptx
CBN Advanced Excel Training Slide.pptx
 
Top tips from the experts on how to learn Excel
Top tips from the experts on how to learn ExcelTop tips from the experts on how to learn Excel
Top tips from the experts on how to learn Excel
 
Top 20 microsoft excel formulas you must know
Top 20 microsoft excel formulas you must knowTop 20 microsoft excel formulas you must know
Top 20 microsoft excel formulas you must know
 
Empowerment Technologies - Module 5
Empowerment Technologies - Module 5Empowerment Technologies - Module 5
Empowerment Technologies - Module 5
 
Excel functionssimplymeasured
Excel functionssimplymeasuredExcel functionssimplymeasured
Excel functionssimplymeasured
 
Most important excel functions &amp; shortcuts
Most important excel functions &amp; shortcutsMost important excel functions &amp; shortcuts
Most important excel functions &amp; shortcuts
 
Excel-eBook.pdf
Excel-eBook.pdfExcel-eBook.pdf
Excel-eBook.pdf
 
Excel-Ebook.pdf
Excel-Ebook.pdfExcel-Ebook.pdf
Excel-Ebook.pdf
 
Introduction to excel - application to statistics
Introduction to excel - application to statisticsIntroduction to excel - application to statistics
Introduction to excel - application to statistics
 
Excel Function Training
Excel Function TrainingExcel Function Training
Excel Function Training
 
Ms excel 2007 tutorial
Ms excel 2007 tutorialMs excel 2007 tutorial
Ms excel 2007 tutorial
 
Excel IF, IFs.ppt
Excel IF, IFs.pptExcel IF, IFs.ppt
Excel IF, IFs.ppt
 
How to if function
How to if functionHow to if function
How to if function
 

Dernier

Call Girls In Panjim North Goa 9971646499 Genuine Service
Call Girls In Panjim North Goa 9971646499 Genuine ServiceCall Girls In Panjim North Goa 9971646499 Genuine Service
Call Girls In Panjim North Goa 9971646499 Genuine Serviceritikaroy0888
 
Call Girls in Gomti Nagar - 7388211116 - With room Service
Call Girls in Gomti Nagar - 7388211116  - With room ServiceCall Girls in Gomti Nagar - 7388211116  - With room Service
Call Girls in Gomti Nagar - 7388211116 - With room Servicediscovermytutordmt
 
Call Girls Navi Mumbai Just Call 9907093804 Top Class Call Girl Service Avail...
Call Girls Navi Mumbai Just Call 9907093804 Top Class Call Girl Service Avail...Call Girls Navi Mumbai Just Call 9907093804 Top Class Call Girl Service Avail...
Call Girls Navi Mumbai Just Call 9907093804 Top Class Call Girl Service Avail...Dipal Arora
 
Best VIP Call Girls Noida Sector 40 Call Me: 8448380779
Best VIP Call Girls Noida Sector 40 Call Me: 8448380779Best VIP Call Girls Noida Sector 40 Call Me: 8448380779
Best VIP Call Girls Noida Sector 40 Call Me: 8448380779Delhi Call girls
 
Insurers' journeys to build a mastery in the IoT usage
Insurers' journeys to build a mastery in the IoT usageInsurers' journeys to build a mastery in the IoT usage
Insurers' journeys to build a mastery in the IoT usageMatteo Carbone
 
Organizational Transformation Lead with Culture
Organizational Transformation Lead with CultureOrganizational Transformation Lead with Culture
Organizational Transformation Lead with CultureSeta Wicaksana
 
Famous Olympic Siblings from the 21st Century
Famous Olympic Siblings from the 21st CenturyFamous Olympic Siblings from the 21st Century
Famous Olympic Siblings from the 21st Centuryrwgiffor
 
Call Girls Hebbal Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
Call Girls Hebbal Just Call 👗 7737669865 👗 Top Class Call Girl Service BangaloreCall Girls Hebbal Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
Call Girls Hebbal Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangaloreamitlee9823
 
KYC-Verified Accounts: Helping Companies Handle Challenging Regulatory Enviro...
KYC-Verified Accounts: Helping Companies Handle Challenging Regulatory Enviro...KYC-Verified Accounts: Helping Companies Handle Challenging Regulatory Enviro...
KYC-Verified Accounts: Helping Companies Handle Challenging Regulatory Enviro...Any kyc Account
 
John Halpern sued for sexual assault.pdf
John Halpern sued for sexual assault.pdfJohn Halpern sued for sexual assault.pdf
John Halpern sued for sexual assault.pdfAmzadHosen3
 
It will be International Nurses' Day on 12 May
It will be International Nurses' Day on 12 MayIt will be International Nurses' Day on 12 May
It will be International Nurses' Day on 12 MayNZSG
 
Monte Carlo simulation : Simulation using MCSM
Monte Carlo simulation : Simulation using MCSMMonte Carlo simulation : Simulation using MCSM
Monte Carlo simulation : Simulation using MCSMRavindra Nath Shukla
 
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756dollysharma2066
 
Mondelez State of Snacking and Future Trends 2023
Mondelez State of Snacking and Future Trends 2023Mondelez State of Snacking and Future Trends 2023
Mondelez State of Snacking and Future Trends 2023Neil Kimberley
 
Mysore Call Girls 8617370543 WhatsApp Number 24x7 Best Services
Mysore Call Girls 8617370543 WhatsApp Number 24x7 Best ServicesMysore Call Girls 8617370543 WhatsApp Number 24x7 Best Services
Mysore Call Girls 8617370543 WhatsApp Number 24x7 Best ServicesDipal Arora
 
MONA 98765-12871 CALL GIRLS IN LUDHIANA LUDHIANA CALL GIRL
MONA 98765-12871 CALL GIRLS IN LUDHIANA LUDHIANA CALL GIRLMONA 98765-12871 CALL GIRLS IN LUDHIANA LUDHIANA CALL GIRL
MONA 98765-12871 CALL GIRLS IN LUDHIANA LUDHIANA CALL GIRLSeo
 
Call Girls Jp Nagar Just Call 👗 7737669865 👗 Top Class Call Girl Service Bang...
Call Girls Jp Nagar Just Call 👗 7737669865 👗 Top Class Call Girl Service Bang...Call Girls Jp Nagar Just Call 👗 7737669865 👗 Top Class Call Girl Service Bang...
Call Girls Jp Nagar Just Call 👗 7737669865 👗 Top Class Call Girl Service Bang...amitlee9823
 
Regression analysis: Simple Linear Regression Multiple Linear Regression
Regression analysis:  Simple Linear Regression Multiple Linear RegressionRegression analysis:  Simple Linear Regression Multiple Linear Regression
Regression analysis: Simple Linear Regression Multiple Linear RegressionRavindra Nath Shukla
 

Dernier (20)

Call Girls In Panjim North Goa 9971646499 Genuine Service
Call Girls In Panjim North Goa 9971646499 Genuine ServiceCall Girls In Panjim North Goa 9971646499 Genuine Service
Call Girls In Panjim North Goa 9971646499 Genuine Service
 
VVVIP Call Girls In Greater Kailash ➡️ Delhi ➡️ 9999965857 🚀 No Advance 24HRS...
VVVIP Call Girls In Greater Kailash ➡️ Delhi ➡️ 9999965857 🚀 No Advance 24HRS...VVVIP Call Girls In Greater Kailash ➡️ Delhi ➡️ 9999965857 🚀 No Advance 24HRS...
VVVIP Call Girls In Greater Kailash ➡️ Delhi ➡️ 9999965857 🚀 No Advance 24HRS...
 
Call Girls in Gomti Nagar - 7388211116 - With room Service
Call Girls in Gomti Nagar - 7388211116  - With room ServiceCall Girls in Gomti Nagar - 7388211116  - With room Service
Call Girls in Gomti Nagar - 7388211116 - With room Service
 
Call Girls Navi Mumbai Just Call 9907093804 Top Class Call Girl Service Avail...
Call Girls Navi Mumbai Just Call 9907093804 Top Class Call Girl Service Avail...Call Girls Navi Mumbai Just Call 9907093804 Top Class Call Girl Service Avail...
Call Girls Navi Mumbai Just Call 9907093804 Top Class Call Girl Service Avail...
 
Best VIP Call Girls Noida Sector 40 Call Me: 8448380779
Best VIP Call Girls Noida Sector 40 Call Me: 8448380779Best VIP Call Girls Noida Sector 40 Call Me: 8448380779
Best VIP Call Girls Noida Sector 40 Call Me: 8448380779
 
Insurers' journeys to build a mastery in the IoT usage
Insurers' journeys to build a mastery in the IoT usageInsurers' journeys to build a mastery in the IoT usage
Insurers' journeys to build a mastery in the IoT usage
 
Organizational Transformation Lead with Culture
Organizational Transformation Lead with CultureOrganizational Transformation Lead with Culture
Organizational Transformation Lead with Culture
 
Famous Olympic Siblings from the 21st Century
Famous Olympic Siblings from the 21st CenturyFamous Olympic Siblings from the 21st Century
Famous Olympic Siblings from the 21st Century
 
Call Girls Hebbal Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
Call Girls Hebbal Just Call 👗 7737669865 👗 Top Class Call Girl Service BangaloreCall Girls Hebbal Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
Call Girls Hebbal Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
 
Forklift Operations: Safety through Cartoons
Forklift Operations: Safety through CartoonsForklift Operations: Safety through Cartoons
Forklift Operations: Safety through Cartoons
 
KYC-Verified Accounts: Helping Companies Handle Challenging Regulatory Enviro...
KYC-Verified Accounts: Helping Companies Handle Challenging Regulatory Enviro...KYC-Verified Accounts: Helping Companies Handle Challenging Regulatory Enviro...
KYC-Verified Accounts: Helping Companies Handle Challenging Regulatory Enviro...
 
John Halpern sued for sexual assault.pdf
John Halpern sued for sexual assault.pdfJohn Halpern sued for sexual assault.pdf
John Halpern sued for sexual assault.pdf
 
It will be International Nurses' Day on 12 May
It will be International Nurses' Day on 12 MayIt will be International Nurses' Day on 12 May
It will be International Nurses' Day on 12 May
 
Monte Carlo simulation : Simulation using MCSM
Monte Carlo simulation : Simulation using MCSMMonte Carlo simulation : Simulation using MCSM
Monte Carlo simulation : Simulation using MCSM
 
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
 
Mondelez State of Snacking and Future Trends 2023
Mondelez State of Snacking and Future Trends 2023Mondelez State of Snacking and Future Trends 2023
Mondelez State of Snacking and Future Trends 2023
 
Mysore Call Girls 8617370543 WhatsApp Number 24x7 Best Services
Mysore Call Girls 8617370543 WhatsApp Number 24x7 Best ServicesMysore Call Girls 8617370543 WhatsApp Number 24x7 Best Services
Mysore Call Girls 8617370543 WhatsApp Number 24x7 Best Services
 
MONA 98765-12871 CALL GIRLS IN LUDHIANA LUDHIANA CALL GIRL
MONA 98765-12871 CALL GIRLS IN LUDHIANA LUDHIANA CALL GIRLMONA 98765-12871 CALL GIRLS IN LUDHIANA LUDHIANA CALL GIRL
MONA 98765-12871 CALL GIRLS IN LUDHIANA LUDHIANA CALL GIRL
 
Call Girls Jp Nagar Just Call 👗 7737669865 👗 Top Class Call Girl Service Bang...
Call Girls Jp Nagar Just Call 👗 7737669865 👗 Top Class Call Girl Service Bang...Call Girls Jp Nagar Just Call 👗 7737669865 👗 Top Class Call Girl Service Bang...
Call Girls Jp Nagar Just Call 👗 7737669865 👗 Top Class Call Girl Service Bang...
 
Regression analysis: Simple Linear Regression Multiple Linear Regression
Regression analysis:  Simple Linear Regression Multiple Linear RegressionRegression analysis:  Simple Linear Regression Multiple Linear Regression
Regression analysis: Simple Linear Regression Multiple Linear Regression
 

Excel trick

  • 1.  HOW TO’S  EXCEL FORMULAS  VBA IN EXCEL  INTERESTING  OTHERS Excel IF Statement – How to Use IF Statement is one of the most popular instructions among the Decision Making statements. IF Statement gives the desired intelligence to a program, so that it can take decisions based on a criteria and most importantly decide the program flow. In Microsoft Excel, IF Statements can be quite useful for evaluating an expression (expressions can be both Mathematical as well as Logical) and giving an output based on it. Definition of IF Instruction: According to Microsoft Excel, IF statement is defined as a function which “checks whether a condition is met, returns one value if True and another value if False”. In plain simple English IF function is an instruction that checks any condition, if the condition is found to be TRUE then it returns a predefined value however if the condition is False, it returns a different predefined value. Syntax of Excel IF Statement: The syntax of If Function in Excel is as follows: =IF (Logic_Test, Value_if_True, Value_if_False) Here, ‘Logic_Test’ refers to the expression that is to be evaluated. ‘Value_if_True’ is the output of IF Statement if the ‘Logic_Test’ is TRUE. ‘Value_if_False’ is the output of IF Statement if the ‘Logic_Test’ is FALSE. Few Important points about IF Functions:  If function only results one value out of ‘Value_if_True’ and ‘Value_if_False’. Both the values cannot be returned at the same time.  Nesting of IF statements is possible but Excel only allows this till 64 Levels.
  • 2.  IF function throws a #Name? error if the expression that you are evaluating is invalid. Examples of Excel IF Statement: Now, let’s move to the practical examples and use of IF function. In the below Example: Example 1: The scores of some students are given in a table along with their names. Now for finding the Result of these students, we can use an IF statement. As you can see in the above image I have also defined the Pass and Fail criteria for these students. Sores above 50 are considered PASS, while scores that are below or equal to 50 are considered FAIL. In this scenario we can use a formula: =IF(B2<=50,"Fail","Pass") Now, what this means. This formula means that first we are comparing the number at B2 i.e. 37 (Score of First Student) with our condition. This expression boils down to (37 <= 50) i.e. Is 37 less than or equal to 50, which is True. Hence the result will be ‘Value_if_True’ (second parameter of if statement) i.e. “Fail”. Similarly, for the second student the formula will be: =IF(B3<=50,"Fail","Pass") Example 2:
  • 3. In the second example an Employee Salary table of a company is shown. We have to calculate the bonus for these employees. As you can see in the image the company has a strange criteria for giving bonus to their employees. The criteria is, if the employee salary is greater than or equal to $ 8000 then bonus will be 15% of the salary otherwise the bonus will be 10% of the salary. In this scenario we can use the Excel if Statement as: =IF(C2>=8000,C2*15%,C2*10%) In this formula, first of all we check if the salary of first employee (in C2 cell) is greater than or equal to 8000. If this is true then the formula evaluates an expression (C2 * 15%) otherwise the result should be calculated by the expression (C2 * 10%). As the salary of the first employee satisfies the condition i.e. (9,735 >= 8000). So, the result of this formula is (9,735 x 15%) which comes out to be $ 1460.25. Similarly for the third employee the formula can be: =IF(C4>=8000,C4*15%,C4*10%) Recommended Reading: Nested If Conditions in Excel Use of Logical Operators along with IF Statement: Excel If Statement can also be used along with the logical operators (like AND, OR) for analysing complex logics. Here I will help you to understand how can these operators be used with IF function.
  • 4. Operator Explanation AND AND function only results into ‘True’ when all the conditions inside it are met. OR OR Function results into ‘True’ when any one of the conditions is met. The syntax of AND Function in Excel is: =AND(Logic1, Logic2, logic_n) The syntax of OR Function in Excel is: =OR(Logic1, Logic2, logic_n) Now let’s move to an example to understand how these functions can be used along with the IF function. Example 3: In this example, another company wants to give bonus to its senior employees. The company comes up with a criteria that any employee who has at-least 5 years of experience (5 years or more) and whose salary is greater than 12000 will be considered a senior employee. And such an employee will be eligible for a bonus equal to 20% of salary. In such a scenario you cannot create an IF statement without using a logical operator. So, in this scenario we can create the if statement as: =IF(AND(C2>=5,D2>=12000),D2*20%,"No Bonus")
  • 5. Here, in the AND function we have used two conditions, i.e. if C2 (Experience of 1st Employee) is greater than or equal to 5 and if D2 (Salary of 1st Employee) is greater than or equal to 12000. If both these condition are ‘True’ then only the output of AND will be ‘TRUE’ if any one of the value is ‘FALSE’ then AND Function will result into ‘FALSE’ In this example for the first employee the experience is 6.4 years but the salary is less than 12000. So, the first employee won’t be eligible for any bonus. Recommended Reading: VBA IF Statement With Examples In the same way you can find out if all other employees are applicable for bonus or not. Filed Under: Formulas Tagged With: Excel All Versions About Ankit Kaul Ankit is the founder of Excel Trick. He is tech Geek who loves to sit in front of his square headed girlfriend (his PC) all day long. :D. Ankit has a strong passion for learning Microsoft Excel. His only aim is to turn you guys into 'Excel Geeks'. Learn Excel with Us!  Excel VLOOKUP Tutorial  Microsoft Excel IF Statement  Excel Web App Viewers  What is Excel VBA  HLOOKUP - Excel Formula Training Session  Spell Check In Excel  Top 50 Excel Based Games  Microsoft Excel Shortcuts And Functions Keys  Excel SUMIF and SUMIFS Functions  FileSystemObject in VBA Stay Connected With Us! Join 5.3 K People Following Us RSS
  • 6. Facebook Twitter Stay Updated via Email Newsletter Enter your em Join Recent Posts  Use an Image as a Background in Excel  Excel Function Keys and Shortcuts  Named Range in Excel  How to Use Excel Sparklines  Adding Current Date and Time Stamp in Excel  NETWORKDAYS Function In Excel  Sum Cells based on Background Color  Getting Familiar with VB Editor (VBE) : VBA Basics 002  What is Excel VBA? : Excel VBA Basics 001  Calculating Weighted Average in Excel Visit the Excel Trick Store © Copyright 2012-2015 Excel Trick · All Rights Reserved || SiteMap Privacy Policy | Disclaimer | About
  • 8. Online Version: http://fliphtml5.com/hjbe/ymci We Transfer Link: https://we.tl/ADUhPOax2j Pcloud Link: https://transfer.pcloud.com/download.html?code=5ZvNRnZHUHIMJwkCeFZEuM5ZmAKayH5 LtnyyOzFRSc2HFbeUbGg7 Google Drive Link: https://drive.google.com/drive/folders/0BzuED9wSESreWk13djlpdkhaMU0?usp=sharing How to Spell Check In Excel Microsoft Excel doesn’t have advanced capabilities like grammar checking and correction but still it offers the basic spell checking functionality. This built-in spell checker in Microsoft Excel can help you to double check your excel sheets before you send them across to someone else. One thing that I would like to point out is that the spell-checking capability of Excel is very limited. I mean unlike MS Word, Excel doesn’t underline the misspelt words as you write them. It will only tell you about a misspelt word when you hit the spell check button. How to check spellings in Microsoft Excel: Checking spellings in excel is very easy. Follow below steps to perform a spell check in Excel.  With your excel spreadsheet opened, simply navigate to the ‘Review’ tab in the ribbon.  In the ‘Review’ tab there is an option ‘Spelling’ as shown in the image.
  • 9.  Clicking this option will initiate the spell checking. Now there is one important thing that I would like to highlight. Before starting the spell checking if your cursor was on ‘A1’ cell then excel will start spell checking from that cell. If your cursor was on some ‘K10’ cell then spell checking will start from that particular cell. But in this case after reaching the end of the worksheet it will ask you “Do you want to continue checking at the beginning of sheet?” If you click the ‘Yes’ button then it will check all the left cells, else if you select ‘No’ then it will leave the other cells as it is. Shortcut Key for Spell-checking: If you don’t like to use the spell-checking functionality using the button present on Excel ribbon then you can also do this by using a shortcut key. The shortcut key for this is ‘F7’. While opening a spreadsheet if you press ‘F7’, then it will start the spell checking process. Spell-check Multiple Sheets at Once: While using the spell-check option you will realize that it can only check spellings on the active sheet. But by following the below method you will be able to check spellings on multiple sheets at once.  Open the excel sheet, now right click on the name of your excel sheet.
  • 10.  This will open a menu, select the option that says “Select All Sheets”. Now all the available sheets in your excel file will be selected.  After this start the spell checking process by navigating to Review>Spellings, or by using the ‘F7’ key. Highlight Misspelled words by using a Macro: Finding misspelled words becomes quite easy by using the below macro. This macro changes the background color of the cells where misspelled words are present. This makes it easier for anyone to find the wrongly spelled words just by viewing the sheet. To use this macro follow the below steps:  Open the excel sheet for which you want to highlight the misspelled cells.  Next, press “Alt+F11” keys, this will open Excel VBA editor.  Navigate to Insert>Module.  Paste following code inside the editor. view plaincopy to clipboardprint? 1. Sub ColorMispelledCells() 2. For Each cl In ActiveSheet.UsedRange 3. If Not Application.CheckSpelling(Word:=cl.Text) Then _ 4. cl.Interior.ColorIndex = 28 5. Next cl 6. End Sub  After pasting the code press ‘F5’ key to run the macro.  Next check your sheet, all the cells with misspelled words would have been highlighted in aqua color.
  • 11. So, this was all about spell check in excel. If you come across any difficulty while using this option, please share it in the comments section. Filed Under: How To's Tagged With: Excel All Versions About Ankit Kaul Ankit is the founder of Excel Trick. He is tech Geek who loves to sit in front of his square headed girlfriend (his PC) all day long. :D. Ankit has a strong passion for learning Microsoft Excel. His only aim is to turn you guys into 'Excel Geeks'. um Cells based on Background Color Few weeks back, one of my regular visitors dropped me an email describing an issue that he was facing. His task was to add the contents of certain cells based on their background colors. As we all know, Excel by default has no formula or feature to calculate such a thing. So, in this post I will share few methods that will help you to achieve this. To make the task more clear let’s have a look at the below image.
  • 12. This image depicts that here we don’t need the total sum of all the elements but instead we want the sum of elements that have the same background color. Recommended Reading: Weighted SUM in Excel Method 1: SUM cells on the basis of background colour using SUMIF Formula: We know that SUMIF function is a combination of SUM and IF formula and hence SUMIF can come quite handy for adding cells based on color. If you don’t know how to use a SUMIF Function, then before going any further I would strongly suggest you to read this post. First of all let’s try to understand how we are going to do this: Consider we have a table as shown in the below image.
  • 13. Next, we will add one more column to this table where we will manually type the background colors of their adjacent cells as shown in the below image. Now, we try to use SUMIF Formula for finding the SUM of cells with yellow background as:=SUMIF(B2:B13,"Yellow",A2:A13)
  • 14. Similarly, for finding the SUM of Orange and Green background cells we will use the formulas=SUMIF(B2:B13,"Orange",A2:A13) and =SUMIF(B2:B13,"Green",A2:A13) respectiv ely. But, as we can see that this method is quite cumbersome, particularly if we need to use this on lists with hundreds of elements. So, what’s the faster alternative?
  • 15. To make the above process easier to use we need to reduce the effort of writing cell background colors manually. So, for this task we can use a small user defined function (UDF) which will do the trick for us. view plaincopy to clipboardprint? 1. Function ColorIndex(CellColor As Range) 2. ColorIndex = CellColor.Interior.ColorIndex 3. End Function Note: This function does not return the color name but it returns the color index which is also a unique value and can be used in our task. Follow the below steps to use the UDF: 1. First of all open your worksheet where you need to add the cells based on background colors. 2. Next, press ALT + F11 to open the VB Editor. Navigate to ‘Insert’ > ‘Module’. 3. After this, paste the “ColorIndex” UDF in the Editor. 4. Now, add one column next to the range that you wish to sum up. In this new column enter the formula as: =ColorIndex(<refrence_ofcell_whose_background_colour_index_you_wish_know>)
  • 16. 5. After that, drag this formula to the whole range. 6. Now, you can use the SUMIF function to add the cells that have same background color as shown in the above image. Method 2 : Using a much faster and better UDF: The UDF that we are going to use in this method is simply an extension of the above used function. This Function is as under: view plaincopy to clipboardprint?
  • 17. 1. Function SumByColor(CellColor As Range, rRange As Range) 2. Dim cSum As Long 3. Dim ColIndex As Integer 4. ColIndex = CellColor.Interior.ColorIndex 5. For Each cl In rRange 6. If cl.Interior.ColorIndex = ColIndex Then 7. cSum = WorksheetFunction.SUM(cl, cSum) 8. End If 9. Next cl 10. SumByColor = cSum 11. End Function How to use this UDF: Follow the below steps to use this Function: 1. Open your target worksheet. 2. Press ALT + F11 to open the VBA Editor and navigate to ‘Insert’ > ‘Module’. 3. Paste the “SumByColor” Function in the Editor. 4. Now, simply type the “SumByColor” function to call it and pass the following arguments: =SumByColor(<cell_with_background_color_that_you_wish_sum>, <Range_to_be_summed_up>)
  • 18. Note:In the formula shown in above image instead of the first argument “A2” we could have also used any one of A2, A5, A8, A10, A12. Because all these cells have yellow background. In our case we can use the following formulas:  Sum of Yellow Cells: =SumByColor(A2,A2:A13) [As ‘A2’ is the address of yellow cell and A2: A13 is the range to be added]  Sum of Orange Cells: =SumByColor(A3,A2:A13) [As ‘A3’ is the address of orange cell and A2: A13 is the range to be added]  Sum of Green Cells: =SumByColor(A4,A2:A13) [As ‘A2’ is the address of green cell and A2: A13 is the range to be added] So, this was all from me about this topic. Don’t forget to download the sample spreadsheet [link] and do let me know in case you face any issues while using these methods. Filed Under: How To's Tagged With: Excel All Versions About Ankit Kaul Ankit is the founder of Excel Trick. He is tech Geek who loves to sit in front of his square headed girlfriend (his PC) all day long. :D. Ankit has a strong passion for learning Microsoft Excel. His only aim is to turn you guys into 'Excel Geeks'.
  • 19. Excel DATEDIF Function – Calculate the difference between two dates DATEDIF is a hidden function in Excel. As the name suggests the job of this function is to calculate the difference between two given dates. I have referred this function as hidden because, for some reason Microsoft has decided not to document this function. And because of this you won’t find this function in the Formula Tab. To verify this, try and type =DATE in any cell. You will see, Excel enlists all the functions that start with the word “date” but it doesn’t shows DATEDIF. Please note that, DATEDIF Function in Excel is totally different from the DATEDIFF (Notice the extra ‘F’) Function in VBA. Syntax of Excel DATEDIF function: Learning the syntax of DATEDIF function is very important. Because for applying this function you need to know its complete syntax as Excel won’t provide you any help on this. The Syntax of DATEDIF function is as follows: =DATEDIF(Start_Date, End_Date, Unit) Here, ‘Start_Date’ is the starting date of the period that you wish to calculate. ‘Start_Date’ can be entered as a string within double quotes (like: “10/10/2013”), it can also be entered as a serial number, as Excel internally treats dates as serial numbers (for example: the number 41557 represents “10/10/2013”, if you are using the 1900 date system), or you can also supply the dates as a formula (like: =DATE(2013,10,10)).
  • 20. ‘End_Date’ is the last date of the period that you wish to calculate. Similar to ‘Start_Date’, ‘End_Date’ can also be entered as a string, number or a formula. ‘Unit’ specifies the interval by which you want the difference to be returned. There are 6 ‘Units’, which are described as under: UNIT RETURNS “Y” Returns the period difference as complete years. “M” Returns the period difference as complete months. “D” Returns the number of days in the period. “MD” Returns the difference between the days in ‘Start_Date’ and ‘End_Date’. Here the months and years of the dates are ignored. “YM” Returns the difference between the months in ‘Start_Date’ and ‘End_Date’. Here the days and years of the dates are ignored “YD” Returns the difference between the days of ‘Start_Date’ and ‘End_Date’. Here the years of the dates are ignored. How to Use Excel DATEDIF function: Now, let’s understand how to use DATEDIF function in excel. Objective: Let’s, consider our objective is to find the number of days from 14 April 1912 (The day on which Titanic Sank) till todays date. So, we will try to apply the DATEDIF formula. ‘Start_Date’: In this case our ‘Start_Date’ will be: 14 April 1912.
  • 21. ‘End_Date’: End_Date will be today’s date. So, instead of entering the today’s date manually we will use the Today() function. ‘Unit’: As we want to find the number of days between the period. So, the ‘Unit’ will be “d”. This formula results into: 36910 days. Some Important points about DATEDIF Formula:  DATEDIF throws a #NUM error is Start_Date is greater than ‘End_Date’.  It throws a #Value error if anyone of the date arguments is invalid.  It also throws a #NUM error if the ‘Unit’ is invalid.
  • 22. Few Examples of DATEDIF Function: Now, let’s move to some examples of DATEDIF function: Example 1: Write a formula to calculate the total number of years from 1/1/2001 to 1/1/2007. This can be simply done by using the below formula: =DATEDIF("01/01/2001","01/01/2007","y") And the answer is 6. Example 2: Write a formula to calculate the number of complete months from 1/1/2001 to 1/1/2007. The formula that we are going to user here is: =DATEDIF("01/01/2001","01/01/2007","m") The answer is 72 i.e. 6 years X 12 months in each year =72 Example 3: Write a formula to calculate your age in years, months and days. For finding the age we will need birth date of a person. In our example we will take the birth date as 12/12/1986
  • 23. So, we will use a formula =DATEDIF("12/12/1986",TODAY(),"y")&" years,"& DATEDIF("12/12/1986",TODAY(),"ym") &" month(s), "& DATEDIF("12/12/1986",TODAY(),"md")&" Days" The need to supress zero values: In Example 3 we have seen how DATEDIF function can be used of calculating age. However, if the number of years and/or months is 0, then the resultant of the formula looks strange. Okay, I will try to explain this in detail. Consider that we have to calculate age of a baby born on 12/12/2012. So, will try to use the formula: =DATEDIF("12/12/2012",TODAY(),"y")&" years,"& DATEDIF("12/12/2012",TODAY(),"ym") &" month(s), "& DATEDIF("12/12/2012",TODAY(),"md")&" Days" See, what the result of this formula is. Doesn’t 0 years looks odd.
  • 24. So, to fix this issue we will use the IF function along with Excel DATEDIF. And the new formula will be: =IF(DATEDIF("12/12/2012",TODAY(),"y") = 0, "", DATEDIF("12/12/2012",TODAY(),"y") &" years,")& IF(DATEDIF("12/12/2012",TODAY(),"ym") = 0, "", DATEDIF("12/12/2012",TODAY(),"ym") &" month(s), ")& IF(DATEDIF("12/12/2012",TODAY(),"md") = 0,"",DATEDIF("12/12/2012",TODAY(),"md")&" Days") I think now you all would agree, that the output of this new formula looks better than the old one. Is DATEDIF a safe function? I know this is a bit strange but many Excel Gurus say that it’s not good to use DATEDIF in your important workbooks. As this is an undocumented function and going forward there may be a chance that Microsoft may remove support for this function. So, what’s the alternative to DATEDIF? The alternative to Excel DATEDIF would be a User defined function (UDF) that internally uses the VBA DATEDIFF function: view plaincopy to clipboardprint? 1. Function xlDATEDIF(Start_Date As Date, End_Date As Date, Unit As String) As String 2. xlDATEDIF = DateDiff(Unit, Start_Date, End_Date) 3. End Function This UDF accepts three parameters:  Start_Date: The days from which the period begins.  End_Date: It is the last date of the period that you wish to calculate.
  • 25.  Unit: It specifies the interval by which you want the difference. Here the unit accepts following values. Value Description YYYY Year Q Quarter M Month Y Day of year D Day W Weekday WW Week H Hour N Minute S Second Example 4: Using this UDF to find the number of days between “01/01/2010” and “01/01/2012”. To do this we will use the formula: =xlDATEDIF("01/01/10","01/01/12","d") And it results into 730.
  • 26. So, this was all about Excel DATEDIF function. Do let me know in case you come across any issues while using this function. Filed Under: Formulas Tagged With: Excel All Versions About Ankit Kaul Ankit is the founder of Excel Trick. He is tech Geek who loves to sit in front of his square headed girlfriend (his PC) all day long. :D. Ankit has a strong passion for learning Microsoft Excel. His only aim is to turn you guys into 'Excel Geeks'. BA IF Statement – Explained With Examples IF is one of the most popular and frequently used statement in VBA. IF statement in VBA is sometimes also called as IF THEN ELSEStatement. The task of IF Statement is to check if a particular condition is met or not. If you have followed my earlier posts, then you would remember that we discussed If Function in Excel. The IF Function in Excel and the IF Statement in VBA are basically designed to do the same tasks, but the way they work is slightly different from each other. Excel IF function checks a particular condition and if the condition is TRUE, it returns one value otherwise it returns the second value. On the other hand, VBA IF Statement checks a condition but it doesn’t return any value. If the condition evaluates to TRUE then, it simply takes the program control to the instructions inside the IF block and starts executing them sequentially. However, if the condition evaluates to FALSE then it takes the program control to the statements inside the Else Block.
  • 27. Although, it is not mandatory to have an Else Block with every IF statement. In such a case, if the condition inside IF statement evaluates to FALSE then the program control just moves to the next instruction (the instruction after the IF Block) and starts executing them sequentially. Recommended Reading : Nested IF’s in Excel Syntax of VBA IF Statement: Now let’s see the syntax of IF statement in VBA: IF condition_1 THEN 'Instructions inside First IF Block ELSEIF condition_2 Then 'Instructions inside ELSEIF Block ... ELSEIF condition_n Then 'Instructions inside nth ELSEIF Block ELSE 'Instructions inside Else Block END IF Here, ‘condition_1’ to ‘condition_n’ refers to the expression that must evaluate to a Boolean value (i.e. either it should be TRUE or it should be FALSE). The ‘THEN’ keyword is basically a directive signifying that the instructions immediately following the IF Statement are to be executed, if the condition evaluates to TRUE. IF function usually ends with an ‘END IF’ statement which tells the application that it is the last line of the IF function.
  • 28. How it works: The conditions along with the IF Statements will be evaluated sequentially. This means, first of all the IF Statement with ‘condition_1’ will be evaluated, if it evaluates to TRUE then statements inside the first IF block will be executed and rest of the blocks (ELSEIF’s and ELSE blocks) will be skipped. But, if the First IF Statement evaluates to FALSE then the ELSEIF statement following it will be evaluated. If it evaluates to TRUE then the instructions inside the ELSEIF Block will be sequentially executed and rest of the blocks (ELSEIF’s and ELSE blocks) will be skipped. However in case, it also evaluates to FALSE then the next ELSEIF statement will be evaluated and so on. Finally, if all the IF and ELSEIF’s evaluate to FALSE then the ELSE block will be executed. Note: Remember that out of IF, ELSEIF’s and ELSE code blocks; only a single code block will be executed at a time based on the condition. How to Use IF Statement in VBA: Now let’s understand how to use IF Statement in VBA. Before preceding let’s make our objective very clear. Objective: Here we will generate a random number between 1-10 and then our task is to identify if the generated number is less than 5, equal to 5 or greater than 5. So, we will try to write a VBA program as: Sub IF_Test() Dim num As Integer num = WorksheetFunction.RandBetween(1, 10) If num > 5 Then MsgBox num & " is greater than 5" ElseIf num = 5 Then MsgBox num & " is equal to 5" Else MsgBox num & " is less than 5" End If End Sub Explanation: In the above code we have used the RandBetween function of Excel to generate any random number from 1 – 10. After this we have used an IF statement to check whether this number is greater than 5, equal to 5 or less than 5.
  • 29. Based on the generated number, any one of the three conditions will evaluate to TRUE and suitable message box will pop out. How this code works in three conditions: If Random number is greater than 5: Let’s consider the random number generated is 7. The program starts from Line-1 and executes all the instructions sequentially till Line-4. When it reaches Line-4 it checks ‘If 7 > 5’, which is TRUE. So, it jumps to the instruction immediately beneath it and pops up a message saying “7 is greater than 5”. After this it directly jumps to the Line-10 and comes out of the whole IF Statement. If Random number is equal to 5: Let’s consider the random number generated is 5. In this case when the program control reaches Line-4, it checks ‘If 5 > 5’, which is FALSE. So, it skips the IF Block and jumps to the ELSEIF statement, here it checks ‘If 5 = 5’ which evaluates to TRUE. So, it pops up a message saying “5 is equal to 5”. (I know it’s a weird message, but I just used it for helping you to understand the things.) After this the program control directly jumps to Line-10 , skips the ELSE part and comes out of the whole IF statement. If Random number is less than 5: Let’s consider the random number generated is 3. So, In this case when the program control reaches Line-4 it checks ‘If 3 > 5’, which is FALSE. So, it skips the IF Block and jumps to the ELSEIF block, here it checks ‘If 3 = 5’, which also evaluates to FALSE. Now, as the above two blocks have evaluated to FALSE hence the ELSE block will be executed and pops out a message saying “3 is less than 5”. Later the program control jumps to Line- 10 and ends the IF Statement. 3 Examples of VBA IF Statement: Now, let’s move to some examples of IF Statement in VBA. Example 1: Write a simple program to check whether the number entered by the user is negative or not. Below VBA code can accomplish this: Sub Find_Negative() On Error GoTo catch_error Dim number As Integer number = InputBox("Enter the number: ") If number < 0 Then MsgBox "Entered number is negative!"
  • 30. Else MsgBox "Entered number is positive!" End If Exit Sub catch_error: MsgBox "Oops, Some Error Occurred !" End Sub Explanation: In this code, first of all we are accepting input number from the user. And then we check whether that number is greater than zero or not. If the number is less than zero, then IF block is executed and a message is displayed to the user saying, “Entered number is negative!”. But however, if the entered number is greater than zero then the program jumps to the Else block where it displays a message to the user saying, “Entered number is positive!”. Example 2: Write a VBA code to tell if the number entered by user is even or odd. Below is the code to do this: Sub Find_Even_Odd() On Error GoTo catch_error Dim number As Integer number = InputBox("Enter the number: ") If number Mod 2 = 0 Then MsgBox "Entered number is Even!" Else MsgBox "Entered number is Odd!" End If Exit Sub catch_error: MsgBox "Some Error Occurred" End Sub Explanation: In this code, just like the previous example first of all we are accepting input number from the user. And then we check whether the Modulus of that number with 2 is zero or not. If the Modulus is zero that means the number is divisible by 2 and hence is Even. But however, if the modulus result is non-zero that means number is not perfectly divisible by 2 and hence it is Odd. Example 3: Write a simple program to check if the string entered by user is Palindrome or not. A Palindrome string is that which reads the same forward as it does backward for example: level, civic etc. Below is the code to accomplish this task:
  • 31. Sub Check_Palindrome() On Error GoTo catch_error Dim word As String Dim Rev_Word As String word = InputBox("Enter the string ") Rev_Word = StrReverse(word) If LCase(word) = LCase(Rev_Word) Then MsgBox "Entered String is Palindrome !" Else MsgBox "Entered String is non Palindrome !" End If Exit Sub catch_error: MsgBox "Some Error Occured" End Sub Explanation: The logic of this code is quite simple, first of all we have asked user to enter a text sting. And then with the use of VBA StrReverse function (inbuilt function to reverse a text string) we have reversed the text string entered by the user. Finally, we are matching both the strings i.e. user entered string and reversed string in an IF statement to check whether both of them are same or different. If both are same that means the entered string is palindrome. Using IF statement with And & Or operators: Logical operators make it possible for you to check multiple condition at a time, inside a single IF statement. There are many logical operators in VBA like: And, Or, Not, AndAlso,OrElse, and Xor but in most cases we only deal with the first three. Note: All the above mentioned operators are binary (i.e. they accept at least two operands) except NOT. NOT is unary because it takes a single operand. Now, let’s have a look at their truth tables: Condition NOT Result True False False True After seeing the above truth table you can clearly see that Not just returns the opposite logic of the condition.
  • 32. Condition1 Condition2 AND Result OR Result True True True True True False False True False True False True False False False False See that AND only returns a TRUE value if both the conditions are TRUE. While OR returns TRUE if at-least any one of the two conditions is TRUE. Now, let’s have a look at some examples of Logical Operators with IF Statement: Example 4: Write a program to ask user his favorite color. If the color entered by the user is ‘White’ or ‘Black’, then display a message to tell him that you like the same color. Below is the code to do this: Sub Fav_Color() On Error GoTo catch_error Dim color As String color = InputBox("Enter your favorite color: ") If LCase(color) = "white" Or LCase(color) = "black" Then MsgBox "Oh Really! I too like the same." Else MsgBox "Nice Choice" End If Exit Sub catch_error: MsgBox "Some Error Occurred" End Sub See how I have used Or operator to check combination of multiple conditions in my program. Example 5: In the below table we have a Grade Table. Our task is to write a program that accepts Marks from user and displays the corresponding Grade.
  • 33. Below is the code to accomplish this: Sub Grade_Marks() On Error GoTo catch_error Dim Marks As Integer Marks = InputBox("Enter your marks: ") If Marks <= 100 And Marks >= 85 Then MsgBox "Grade A" ElseIf Marks < 85 And Marks >= 75 Then MsgBox "Grade B" ElseIf Marks < 75 And Marks >= 65 Then MsgBox "Grade C" ElseIf Marks < 65 And Marks >= 55 Then MsgBox "Grade D" ElseIf Marks < 55 And Marks >= 45 Then MsgBox "Grade E" ElseIf Marks < 45 Then MsgBox "Fail" End If Exit Sub catch_error: MsgBox "Some Error Occurred" End Sub In this code see how I have used the AND operator to produce the required conditions. Note: As a better coding practice it is always nice to use Select Case statements instead of writing multiple ELSEIF statements (just like we have seen in above example). Select Case statements execute faster and look cleaner than IF THEN ELSE. Recommend Reading: Select Case Statement So, this was all about VBA IF Statement. Do read this post if this long article has bored you and don’t forget to share your ideas and thoughts with us in the comments section. Filed Under: Formulas TaggedWith: Excel All Versions
  • 34. About Ankit Kaul Ankit is the founder of Excel Trick. He is tech Geek who loves to sit in front of his square headed girlfriend (his PC) all day long. :D. Ankit has a strong passion for learning Microsoft Excel. His only aim is to turn you guys into 'Excel Geeks'. se an Image as a Background in Excel Generally most of us have seen Excel as plain and monotonous piece of software. But have you ever thought how you can use your creativity to create amazing and attractive spreadsheets? In this post, I am going to share one such technique, here we are going to learn how to add background images in your Excel worksheets. So grab a cup of coffee, get relaxed and read on: Option 1: Adding a Background Image to your worksheet: For Excel 2003: 1. First of all open the worksheet where you wish to add the background. 2. After this navigate to ‘Format’ > ‘Sheet’ > ‘Background’. 3. Now, browse through all the available images, select the image that you wish to add and click the insert button as shown in the below image.
  • 35. 4. This will add the picture that you just selected as the sheet background. For Excel 2007, 2010 and 2013: 1. First open the worksheet where you have to add the background. 2. Next, navigate to ‘Page Layout’ Tab in the ribbon and click the ‘Background’ option. 3.This will open a sheet background window, select the image that you wish to use as a background and then click the insert button.
  • 36. 4. Now the image that you just selected will be used in the background your worksheet.
  • 37. 5. The resultant will look somewhat like the above image. Few Important tips about spreadsheet backgrounds:  Try to use contrast colours to make you spreadsheets more readable. For example- if you use a dark colour font on a light colour background image, it will be easier to read.  You can also use the shortcut Alt + P G to add an image background to your worksheets.  The image in your spreadsheet background can increase the overall size of the spreadsheet. So, only select those images that have small sizes.  You cannot add a background image to multiple worksheets at once. You can only add the background to one worksheet at a time.  Remove gridlines on your spreadsheets when you are using a background image, this makes them look smooth.  It should be noted that when you add an image background to your spreadsheet using the above method then it won’t show up when you print the sheet. To add printable backgrounds to your spreadsheet use the second option. How to Remove the Background Image in Excel: To remove the background in image follow the below steps: For Excel 2003: 1. First open the spreadsheet, where you have already added an image as background. 2. Next, navigate to ‘Format’ > ‘Sheet’ > ‘Delete Background’. 3. This will delete the image from the background. For Excel 2007, 2010 and 2013: 1. First of all open the spreadsheet, where you have already added an image as background. 2. After this, navigate to the ‘Page Layout’ tab in the ribbon and click the ‘Delete Background’ option.
  • 38. 3.Now, the image in the background of your worksheet will be deleted. Option 2: Adding a Printable image to your worksheet: In this method we will are not going to add the image as a background but instead we will add the image on top of another object. And then we will adjust the object so that it fits in the whole printable area. To use the method follow the below steps: 1. Open the worksheet where you wish to add your image background. Before proceeding further make sure that you have filled the required data to your spreadsheet. 2. Next, navigate to ‘Insert’ Tab > ‘Shapes’ > ‘Rectangle’, and draw a rectangle on your sheet.
  • 39. 3. After this, right click on the rectangle and select the option ‘Format Shape’ as shown in image.
  • 40. 4. This will open the ‘Format Shape’ options, click the ‘Fill’ option, in the ‘Fill’ type select the ‘Gradient or Texture’ radio button. Then using the ‘File’ button select the picture of your choice as the background and set its transparency according to your needs.
  • 41. 5. Now adjust the image such that it shows in the printable area and then print the sheet. So, this was all from my side. Hope you would have liked this post. Filed Under: How To's, Interesting Tagged With: Excel All Versions About Ankit Kaul Ankit is the founder of Excel Trick. He is tech Geek who loves to sit in front of his square headed girlfriend (his PC) all day long. :D. Ankit has a strong passion for learning Microsoft Excel. His only aim is to turn you guys into 'Excel Geeks'. Learn Excel with Us!  Excel VLOOKUP Tutorial  Microsoft Excel IF Statement  Excel Web App Viewers  What is Excel VBA  HLOOKUP - Excel Formula Training Session  Spell Check In Excel  Top 50 Excel Based Games
  • 42.  Microsoft Excel Shortcuts And Functions Keys  Excel SUMIF and SUMIFS Functions  FileSystemObject in VBA Stay Connected With Us! Join 5.3 K People Following Us RSS Facebook Twitter Stay Updated via Email Newsletter Enter your em Join Recent Posts  Use an Image as a Background in Excel  Excel Function Keys and Shortcuts  Named Range in Excel  How to Use Excel Sparklines  Adding Current Date and Time Stamp in Excel  NETWORKDAYS Function In Excel  Sum Cells based on Background Color  Getting Familiar with VB Editor (VBE) : VBA Basics 002  What is Excel VBA? : Excel VBA Basics 001  Calculating Weighted Average in Excel Visit the Excel Trick Store
  • 43. © Copyright 2012-2015 Excel Trick · All Rights Reserved || SiteMap
  • 44. MAX PRODUCTIVITY Smarter, faster ways to get things done  Home  Productivity Software 5 essential tips for creating Excel macros Credit: Image:Rob Schultz    
  • 45.    1COMMENT JD Sartain | @jdsartain journalist,PCWorld  Feb 17, 2015 3:30 AM Excel macros save you time and headaches by automating common, repetitive tasks. And you don’t have to be a programmer or know Visual Basic Applications (VBA) to write one. With Excel 2013, it’s as simple as recording your keystrokes. Use these tips to make macro recording a cinch. 1. Macro names Keep macro names short (but descriptive), especially if you record a lot of macros, so you can easily identify them in the Macro Dialog Box. The system also provides a field for Description, though not everyone uses it. Macro names must begin with a letter and cannot contain spaces, symbols, or punctuation marks. After the first letter, you can use more letters, numbers, or the underscore character, but the maximum length is 80 characters. 2. Use relative (not absolute) cell addresses Absolute means that the exact cell locations are recorded into the macro—hardcoded cell addresses such as A6 or B12, which limits the macro’s ability to function if anything changes, new data is added/removed, or the list gets longer. Relative means the macro’s recorded keystrokes are relative to the starting cell’s location. The default in Excel is Absolute, but you can change this to Relative on the Stop Recording toolbar: Click Developer>Record Macro. 1. In the Record Macro dialog box, enter a macro name and Shortcut Key (if applicable). Choose Personal Macro Workbook in the Store Macro In box, enter a description (if desired), and click OK.
  • 46. 2. The dialog box disappears, and the Record Macro button changes to a Stop Recording button. Click the Relative Reference button next—it turns dark green to indicate that it’s active. 3. Enter your keystrokes, formulas, and so forth, then click the Stop Recording button and run your macro. JD Sartain Record macros using Relative Cell addresses.
  • 47. 3. Always begin at Home For Absolute reference macros, always begin in the Home position (cell A1)—with your cursor and your data. If you saved your macro in the Personal Macro Workbook (recommended), you can reuse this macro on other worksheets with similar data. Regardless of where your cursor is positioned when you begin recording the macro, even if it’s already located in cell A1, your first macro keystroke must be Ctrl+Home. Example: Imagine that every month you receive dozens of spreadsheets from all your branch offices that you must first combine, then organize, and calculate to produce one monthly report. You can write a macro to perform all of these functions, including opening and combining all the worksheets into one combined spreadsheet. For this exercise, I’ll just address the final spreadsheet with the combined data. 1. Create a new workbook in Excel (e.g., April Report). Your cursor is automatically located in the Home position (A1). Do not move it to accommodate titles, field headers, or anything else. It must be positioned in A1. 2. Open the first branch workbook and copy the entire spreadsheet’s data (minus the column headers) to cell A1 in your April Report spreadsheet. The data begins in A1 and ends in G55. 3. Open the second branch workbook and copy the entire spreadsheet’s data (minus the column headers) to cell A56 in your April Report spreadsheet. Continue this process until the data in all workbooks are copied into your April Report spreadsheet. 4. If the other spreadsheets’ data contains formulas, choose Paste>Special>Valuesfor your Paste options. Do not copy the formulas or the formats. 5. Don’t worry about a worksheet title, column headers, or formatting (such as column widths, fonts, etc.) at this point. Just copy the data and run the macro. 6. After the data is calculated, you can Insert Rows to add column headers, spreadsheet titles, and other information. Then you can format the column widths, change fonts, add attributes, and place borders or boxes if you'd like. (You can also create an additional macro to perform formatting tasks.) 4. Always navigate with directional keys Use the directional keys (End-Down, Ctrl+Up, etc.) to position your cursor so you can add, change, or delete the data inside the spreadsheet as needed. Using the mouse to navigate is more complicated and not as reliable. When it comes to macros, use the mouse only for selecting or clicking menu options.
  • 48. 5. Keep macros small and specific Keep your macros small and specific to the tasks at hand. The bigger the macro, the slower it runs, especially if it’s required to perform many functions or calculate a lot of formulas in a large spreadsheet. Also, if you combine all the tasks into one long macro and it fails, it takes forever to locate the point of failure. If you run each macro separately, you can quickly review the results and
  • 50. Step through an Excel macro with F8. In the April Report example, you wouldn't combine the calculation macro with the format macro. You'd use one macro to combine all the branch workbooks into one final spreadsheet, a second macro to calculate the data, a third macro to format the spreadsheet, a fourth macro to create charts, and perhaps a fifth macro to print. If a macro fails, you can troubleshoot it by stepping through it one line at a time. It’s like slow motion, only you control each time the next event occurs using the F8 key. ClickDeveloper>Macro, select your macro from the list, then click the Step Into button. Shrink the Code window down and place it on the bottom right side of the screen so you can see your spreadsheet behind it. Press F8 each time you want the macro to proceed to the next step. The macro stops when it reaches the error. You can then repair the error or record a new macro. Related:  Productivity  Microsoft Office  Excel JD Sartain journalist JD Sartain is a technology journalist from Boston. She writes a monthly "Case Studies" column for CIO, a weekly "Max Productivity" column for PCWorld, and she's been a regular freelance writer at Network World for nine years. More by JD Sartain
  • 51. Here are samples of what you will find in Sectio of the downloadable Tutorial on Excel macro Print this page to read it at home, at the office, on the bus or the train ExcelMacros Section1: Programming Macrosin Excel In this first section you will learn how easy it is to record macros with the Macro Recorder and to c other macros of your own in the Visual Basic Editor. You will discover that: - the Macro Recorder is not only a recorder but it is the best teacher and it will be a great assista code for you) even when you become an expert at programming in VBA. - the Visual Basic Editor is the most user friendly development environment that tells you immedia there are mistakes in your sentences so that you do not have to wait at the end of your project to that something that you have written is wrong. - in the Visual Basic Editor you will create these powerful and useful userforms - in the Visual Basic editor you will test your macros step by step, modify them and improve them After section 1, you will be able to copy all the macros available on the internet and use them effic your own workbooks Here is a sample of what you will find in chapter 1 of the downloadable Tutorial on Excel macros The Visual Basic Editor in Excel (VBE) When you want somebody to do some work for you, you open your Email program and you send message in a language that he understands (English, Spanish, French...). When you want Excel t
  • 52. some work for you, you open the Visual Basic Editor and you write the instructions in a language understands VBA (Visual Basic for Application). You will develop, test and modify VBA procedures (macros) in the Excel Visual Basic Editor (VBE very user-friendly development environment. VBA procedures developed in the VBE become part workbook in which they are developed and when the workbook is saved the VBA components (inc macros, modules, userforms and other components that you will discover in the next 32 lessons) at the same time. So, when you send the workbook to the "Recycling Bin" the VBA procedures (m are destroyed. Notes Special note for users of Excel 2007: Until the 2007 versions of Excel the user did not need to i anything to work with macros in Excel. If you are using Excel 2007 see how to install the Visual B Editor for Excel from your Office CD. IMPORTANT NOTE 1: There are no risks to your computer or to Excel in completing the task be any time if you feel uncomfortable, just close Excel without saving the workbook and try again late For users of Excel 1997 to 2006: The first thing that you need to do is to make sure that the sec of Excel is set at either "Low" or "Medium" so that you can use the macros (VBA procedures) that develop. From the menu bar of Excel select "Tools" then "Macro" then "Security" and select "Med For users of Excel 2007 to 2013: From the "Developer" ribbon click on the "Macro Security" butt Check the second level "Disable all Macros with Notification" and you are set. Setting up the Visual Basic Editor in Excel (VBE) The Visual Basic Editor is a program within Excel that allows you to communicate with Excel. We it and start by setting it up so that working within it becomes easy and efficient. Print this page, open Excel and open a new workbook (Book1). On your keyboard press the "ALT" key (left of the space bar) and hold, strike the "F11"key (the F1 at the top of your keyboard).You now see the Visual Basic Editor. Again press "ALT/F11" and you into Excel. Use the "ALT/F11" key to go from Excel to the VBA and back. When you first open the VBE you will see is a window somewhat like the image below.
  • 53. If there are any open windows within the VBE like in the image below click on the Xs to close them a gray rectangle filling up the bottom part of the screen like in the image above.
  • 54. The Three Windows in the Visual Basic Editor To be efficient when working with the VBE there should always be 3 windows showing like in the below; the Project Window (1), the Code Window ( 2), and the Properties Window (3), arranged image below. You can resize the windows by left-clicking where the red stars are, holding and mo sideways or up and down. We will study each of the three windows in lessons 2, 3 and 4 but first them up in the VBE.
  • 55. In the exercise below we will setup the 3 windows of the VBE. Exercise 1 (Create your first macro and use it) Remember that you will perform this task only once as each time you will open the VBE it will rem Step 1: Close all the windows that are open in the VBE to end up with this:
  • 56. Step 2: Go to the menu bar "View" and click "Project Explorer". The result will be somewhat like t below:
  • 57. If the project window already appears as a column on the left side of the screen there is nothing e you have to do for now. If the project window appears in the middle of the gray area like above, rig in the white space in the middle of the project window and check "Dockable". Then click on the to of the Project window, hold and drag it left until the cursor (white arrow) touches the middle of the of the screen. When you let go of the mouse button the end result should be like shown in the ima below. Congratulations you have setup the first major window of the VBE.
  • 58. Step 3: Move your cursor on the line separating the project window and the gray rectangle. When to two small parallel lines and arrows click, hold and move the lines sideways. Resize the two win you want them. Step 4: Go back to the menu bar "View" and click "Properties Window". The Properties window w somewhat like in the image below.
  • 59. If the Properties window is already located below the Project window there is nothing left to do. If like in the image above, right-click in the white space in the middle of the Properties window and c "Dockable". Then click on the top blue bar of the Properties window and drag it left and down unti cursor (white arrow) touches the center of the bottom of the Project window. When you let go of th button the end result should be as the image below. Congratulations you have setup the second m window of the VBE.
  • 60. Step 5: Move your cursor on the line separating the project window and the properties window. W turns to two small parallel lines and arrows click, hold and move the lines vertically. Resize the tw windows as you want them. Step 6: To add the code window to the setup, you just have to double click on the name of a com the Project window (Sheet1, Sheet2, Sheet3 or ThisWorkbook) and its code window appears with gray rectangle. You can maximize any Code window by clicking on its "Maximize" button . The final result looks like the image below. The words "Option Explicit" might not be present in yo window. We will address this issue later in the lesson on variables (Lesson 19). You might also ha VBAProject named FUNCRES.XLA or FUNCRES.XLAM in the project window. Forget about this now.
  • 61. Step 6: Now go to Excel and close it. Re-open Excel, go to the VBE (ALT/F11) and you will see th VBE setup persists. Congratulations, you are now ready to work in the Visual Basic Editor. We will discover more about each of these three windows in chapter s 2 (Project Window), 3 (Pr Window) and 4 (Code Windows). Remember that you can use "ALT/F11" to navigate from Excel to the VBE and back. Close the VBE and close Excel without saving anything. Here is a sample of what you will find in chapter 2 of the downloadable Tutorial on Excel macros The Project Window in the VBE of Excel Note: Print this page, open Excel and a open a new workbook. Use ALT/F11 to open the Visual B Editor as you learned in lesson 1.
  • 62. As you can see, the Project window shows you all the workbooks that are open ("Book1") in the e below) and their components. You can use the + and - signs to show the details. A new Excel workbook includes three sheets and another component named "ThisWorkbook". As see later in lesson 9 on events "ThisWorkbook" is a component in which you will store the macro called VBA procedures) that should start automatically when the workbook is opened. Working within the Project Window We will now complete a brief exercise to learn how easy it is to work within the Project Window. Exercise 2 (Create your first macro and use it) Step 1: Using the ALT/F11 key go back to Excel. Step 2: Add a sheet. Right-click on the tab of Sheet2 and select "Insert".
  • 63. Step 3: In the dialog window that appears, click on "OK". Step 4: Using the "ALT/F11" key, go back to the Visual Basic Editor and see that a sheet has bee to the workbook. Notice that the worksheets are sorted alphabetically in the Project window even not in the workbook.
  • 64. If you have purchased and downloaded the course on Excel Macros and opened the Excel file tutorial-editor.xls" plus a new workbook you will see this: In the picture above you can see that the VBAProject named "Book1.xls" has 3 sheets and
  • 65. ThisWorkbook.The workbook "vba-tutorial-editor.xls" has 7 sheets, two userforms, two modules p "ThisWorkbook" object. - Userforms are dialog windows (see example image below) that you develop to communicate wit users of your Excel programs and ask them to supply information or make choices. - Modules are folders in which you save one or many of your macros. You can export and save th modules to be used later in other workbook. In the complete lesson 2 you will learn how to add any type of components and how to remove, im export and manage them from the Project window. Close the VBE and close Excel without saving anything. Here is a sample of what you will find in chapter 3 of the downloadable Tutorial on Excel macros The Properties Window in the VBE of Excel Note: Print this page, open Excel and a open a new workbook. Use ALT/F11 to open the Visual B Editor as you learned in lesson 1. The Properties window shows you the properties of the component that is selected in the Project (single click). For example in the new workbook if you single click on "Sheet1" in the Project Wind see the properties of sheet1 in the Properties Window like in the image below.
  • 66. As you can see, a worksheet has 12 properties that you can change in this Properties window. No there are 2 "Name" properties. On the first line there is the programmatical name of the sheet (Sh You will discover later the advantages and disadvantages of changing this property. The second " property (9th line) is the name (or caption) that appears on the tab of the sheet in Excel. Changing the "Name" Property Exercise 3 (Create your first macro and use it) Step 1: Go to Excel (ALT/F11) and notice the names on the three tabs of "Sheet1" as in the image Step 2: We will change the name (Caption) on the tab of "sheet1" to "Introduction". To do so right the tab of the sheet and the following dialog window appears:
  • 67. Step 3: Select "Rename". The menu disappears and the name of Sheet1 is highlighted. Enter "Introduction" and this new name will replace "Sheet1" when you click "Enter". The end result is il in the image below. Step 4: Come back to the Visual Basic Editor (ALT/F11) and notice in the Properties window that property "Name" (the ninth property, the one without the parentheses) has changed to "Introductio As you have now learned the name of the sheet can be changed from Excel. We will now comple smal exercise to change the name from the VBE Properties window. Exercise 4 (Create your first macro and use it) Step 1: In the VBE select "Sheet2" in the Project window. On line 9 of the Properties window doub
  • 68. on "Sheet2" and enter the name Spreadsheet. Click "Enter" Step 2: Go to Excel and notice that you now have a sheet named "Spreadsheet" . Setting and modifying properties of objects in the Properties Windows is something that you will h a lot when you start developing userforms (see lessons 24 to 33). Until then you will change a small number of properties including the very important "Visible" prop the sheets to one of its three values. To see the equivalent of the image below, select Sheet2(Spreadsheet) in the Project window. Click on the word "Visible" on the 12th line of the Pro window. A dropdown arrow appears in the cell to the right. Click on the arrow and you can select three properties. In lesson 3 of the downloadable the tutorial on VBA for Excel you will discover how useful the "xlSheetVeryHidden" property can be. This property of a sheet can be used -- for example, to hide in a budgeting application or prices in an estimation application -- making sensitive data inaccess unauthorized users of your workbooks. You will also learn how to name your modules and work with a few other properties of the objects appearing in the Project Window. Close the VBE an Here is a sample of what you will find in chapter 4
  • 69. of the downloadable Tutorial on Excel macros The Code Window in the VBE of Excel Note: Print this page, open Excel and a open a new workbook. Use ALT/F11 to navigate from the Basic Editor to Excel as you learned in lesson 1. The Code Window is where 90% of the VBA work is done; writing VBA sentences, testing your VB procedures (macros) and modifying them when needed. To illustrate everything that you can do in the Code window we will start by creating a small macro empty workbook. Exercise 6 (Create your first macro and use it) Step 1: In Excel notice that cells A1, A2 and A3 of "Sheet1" are empty. Go to the Visual Basic Edi Step 2: Double click on "Sheet1" in the Project Window. On the right is the Code window of "Shee For the purpose of this exercise we will develop a small macro within the code window of a sheet. later develop the habit of creating modules and organizing your macros within them. Step 3: Click anywhere in the Code window Step 4: You can either copy/paste the following macro from your browser to the code window of " or key it in. If you decide to key it in you will start by entering the first line and then when you press enter the V add the final Line "End Sub". Enter the rest of the code within the two lines. Make sure that everyt there including all the quotation marks, periods, parentheses, equal signs and spaces. Sub proFirst() Range("A1").Value = 34 Range("A2").Value = 66 Range("A3").Formula = "=A1+A2" Range("A1").Select End Sub
  • 70. Step 5: Click on any line of the macro, go to the menu bar at the top of the VBE screen and click " then click "Run Sub/Userform". Step 6: Go to Excel (ALT/F11) and see what has happened to cells A1, A2 and A3 Congratulations you have run and tested you first macro. Go to Excel and "Sheet1" and see that w macro was ordering Excel to do has been done. The value of cell "A1" is 34, the value of cell "A2" there is a formula in cell A3 that sums cells A1 and A2. Step 7: Go to Excel and clear the cells A1, A2 and A3 of "Sheet1". On the menu bar go to "Tool" a on "Macros". In the dialog window select "proFirst" and click on run. You have run the macro from the menu bar of Excel. In lesson 9 on Events you will discover many ways to start a macro. NOTE: You cannot change the font or its color in the code window. You input appears in b comments appear in green, reserved words in blue and when you make a mistake the font turns to red. NOTE: For many users of an earlier versions of Excel the wheel of the mouse wheel does n in the code window. To enable your mouse, download and install the free fix offered in thedownloadable tutorial. There are plenty of other operations that you can execute in the code window. For example, you c macro line by line (step by step), go back a few lines and make corrections, use breakpoints to te part of a macro. In section 2 (VBA lessons 11 to 23) you will learn the VBA vocabulary to write macros. Here is a sample of what you will find in chapter 5 of the downloadable Tutorial on Excel macros
  • 71. Developing Macros in Excel Note: Print this page, open Excel and a open a new workbook. Use ALT/F11 to open the Visual B Editor as you learned in lesson 1. Most macros are developed in the code window of modules. For the purpose of this exercise doub on "Sheet1" in the project window Enter sub proTest() without using a capital "S" as the beginning of "sub". After entering the closin parenthesis click on "Enter". You get these two lines of code: Sub proTest() End Sub VBE adds the line "End Sub" and capitalizes the "S" of "Sub" . The VBE capitalizes letters approp when the word is spelled correctly. This is one interesting feature that you should always use whe macros. Make it tour habit never to use capital letters when writing code. In this way, whenever V unexpected fails to capitalize a letter, you will know that something is wrong. Two exceptions to your otherwise consistent use of lower-case are: (1), when you declare variabl 19); and (2), when you name macros (as you did above). You will see why in later lessons. You may now write a procedure within the two lines of code above. For example your VBA proced look like this. You can copy/paste the macro below from your browser to the VBE Code window, o in. Make sure that everything is there including all the quotation marks and periods, parentheses, signs, and spaces. Note: Make sure that you copy/paste this code in a NEW workbook not one created in a previous Sub proTest() Sheets("Sheet1").Select Range("C1").Select Do Until Selection.Offset(0, -2).Value = "" Selection.Value = Selection.Offset(0, -2).Value & " " & Selection.Offset(0, -1) Selection.Offset(1, 0).Select Loop Range("A1").Select End Sub The procedure above will go down column "C" and assemble the first names of column "A" and th
  • 72. names of column "B" with a space in between. It will perform this task all the way down until there more first names in column "A" . It will then place the cursor in cell "A1". To test this macro (VBA procedure) follow the steps below: Step 1: Go to Excel (ALT/F11) and enter first names in cell A1 to A5. Step 2: Enter surnames in cells B1 to B5. Step 3: Come back to the VBE (ALT/F11) and click within the macro in the code window. Step 4: From the menu bar select "Run/Run Sub/Userform". Step 5: Go back to Excel and see the result. You can erase everything in column C Excel and retry with more names and surnames. Try it again removing the first name in cell A3. Notice that the macro stops on line 2. Here is a sample of what you will find in chapter 6 of the downloadable Tutorial on Excel macros Testing Macros in the VBE for Excel Testing the VBA procedure step by step NOTE: While you are running the macro step by step you can stop the execution at any tim clicking on the stop button in the toolbar.
  • 73. Testing is the most time-consuming part of any VBA project. During the development of a project use 20% of your time analysing and designing, 15% programming and 65% testing. During the testing phase, you will correct bugs, typos and the logical errors. More importantly you improve your original project, fine tune it, discover better ways to do things and add code. In lesson 4 you have created your first macro and tested it using the "Run" button. You can also te macro step by step. Print this page, open Excel and a open a new workbook. Use ALT/F11 to open the Visual Basic E you learned in lesson 1. Step 1: Go to Excel and make sure that cells A1, A2 and A3 of Sheet1 are empty. Step 2: In VBE go to the Code window of Sheet1 and copy/paste the following macro: Sub proFirst() Range("A1").Value = 34 Range("A2").Value = 66 Range("A3").Formula = "=A1+A2" Range("A1").Select End Sub Step 3: Click anywhere within the macro and then press the F8 key at the top of your keyboard. V highlights the first line of code in yellow. Step 4: Right-click on the small yellow arrow and see a menu appear
  • 74. In lesson 4 of the downloadable Tutorial on VBA for Excel you will learn about these precious items and everything else that you can do in the Code window. For now let's finish testing this ma by step. Step 5: Press on "F8" a second time. No line has been executed yet and if you go to Excel you wi cells A1 to A3 are still empty. The next time you press "F8" , VBE will execute the yellow-highlighte Step 6: Press "F8" a third time. The yellow-highlighted line is now "Range("A2").Value = 66". VBE executed the previous line "Range("A1").Value = 34" has been executed so if you go to Excel (AL you will see 32 in cell A1. Step 7: Come back to VBE (ALT/F11) and press "F8" again. Go to Excel and see what happened A2. Step 8: Come back to VBE (ALT/F11) and press "F8" again. Go to Excel and see that there is a fo cell A3. Step 9: Come back to the VBE (ALT/F11) and press "F8" again, cell A1 is now selected in Excel. Step 10: Press "F8" again. Nothing happens in Excel but "End Sub" is highlighted in yellow Step 11: Press "F8" again. Nothing happens in Excel no more lines in VBE are highlighted in yello
  • 75. The macro hac been tested, the test is over. In the code change the addresses A1, A2 and A3 respectively to B1, B2 and B3. Test the macro it as many times as you want. You have tested a macro step by step. In the downloadable tutorial you will learn how to test pa macro, how to come back a few lines, make changes and re-execute these lines. You will also dis most important functionality, how to share the screen between Excel and VBE. In no other programming environment can you test a procedure step by step while seeing in the spreadsheet on a single screen. In the picture below you can see the Visual Basic Editor on the left side of a screen and Excel on side. While you press the F8 key to execute the macro step by step in the Visual Basic Editor, you what is happening in the Excel spreadsheet. You will discover the split screen function in lesson 6 thedownloadable the course on VBA for Excel (Macros).
  • 76. Here is a sample of what you will find in chapter chapter 7 of the downloadable Tutorial on Excel macros The Macro Recorder IMPORTANT NOTE 1: There are no risks to your computer or to Excel in completing the exercise At any time if you feel uncomfortable just close Excel without saving the workbook and retry later. IMPORTANT NOTE 2 (for Excel 2007 ONLY) : You can only complete the exercises below if you installed VBA for Excel on your computer. If you do not have, click here. One of the tools that makes the programming environment in Excel unique is the Excel Macro Re When you start the macro recorder anything you do in Excel is recorded as a new macro. That ma macro recorder the best VBA teacher and also a great assistant who will write a lot of the words a
  • 77. sentences that you need without a single typo. It will also be there when you do not remember so that you do not use often. Even after many years of programming you will still use the macro reco not to learn anymore but to write code (VBA words and sentences). With the Excel macro recorder you can not develop a macro that will damage Excel or you computer so try anything and learn. In this lesson on line you will record a macro and run it. Recording Your First New Macro: Step 1: Print this page. Step 2: Open Excel and a new workbook. Step 3: Go to the "Developer" ribbon to click on Step 4: A small window appears titled "Record Macro". We will review its components in thedown tutorial. For now just click on "OK". When you do so the small window disappears and in the "Developer" ribbon i by telling you that you are going in the right direction. The macro recorder is ON Step 5: In the sheet below (Sheet1) select cells B1 to B5, go to "Sheet2", select cell B6, come ba "Sheet1" and select cells D2 to D5. Step 6: In the "Developer" ribbon click on
  • 78. Running your first recorded macro Step 1: Select cell "A1" of "Sheet1". Step 2: In the "Developer" ribbon click on Step 3: In the window that appears Macro1 is selected. Again we will forget about the components of this window because we will study them in thedown tutorial. For now, just click "Run". Step 4: See how fast the macro runs. You do not even see Excel go to Sheet2 (but it does). At th the execution cells D2 to D5 are selected. What took you around 5 seconds to do manually (step 5 of the first exercise) took Excel a fraction second. Excel can work much faster than you can. Welcome to the marvelous world of VBA for E (Macros). You can repeat steps 1 to 4 of this second exercise as often as you like. Looking at your first recorded macro
  • 79. To complete this third exercise you must have studied chapters 1 to 4. Go to the Visual Basic editor and you will see the following macro in the code window when you d click on Module 1 in the Project Window: Sub Macro1() ' Macro1 Macro Range("B1:B5").Select Sheets("Sheet2").Select Range("B6").Select Sheets("Sheet1").Select Range("D2:D5").Select End Sub As you can see the macro recorder recorded your instructions in a language that Excel understan You can now use VBA's written code to have Excel perform this task. Never forget that the Excel macro recorder is your best teacher and will remain a great assistant f rest of your VBA developer's life. Here is a sample of what you will find in chapter 8 of the downloadable Tutorial on Excel macros Macros Help and Assistance There is plenty of help and assistance available within Excel when you develop macros. As you h discovered in the previous lesson the Macro Recorder is a great teacher and assistant. In this les investigate the two other sources of assistance within the Visual Basic Editor of Excel: the Help F the Object Browser. Here is how the Object Browser appers when you call it. ALL the VBA words are presented in this including useful examples. The search function is powerful.
  • 80. Here is a sample of what you will find in chapter 9 of the downloadable Tutorial on Excel macros Starting, triggering a Macro in Excel Note 2: Print this page, open Excel and a open a new workbook. Use ALT/F11 to open the Visua Editor as you learned in lesson 1. When does the VBA procedure (macro) start? When an EVENT happens. The event is what trigg VBA Excel procedure. In earlier lessons you have used an event to start your macros. In the Visu Editor you have gone to the menu bar and clicked on "Run/Run Sub/Userform" and the macro wa executed. You have also clicked on the F8 key at the top of your keyboard and the macro got exe by line.
  • 81. You do not want your user to go to the Visual Basic Editor to trigger a macro. A lot of other events happen to start a macro. The event that is mostly (85%) of macros used is clicking on a button. Th can be on the worksheet or on a userform that you would develop. The event can also be: openin workbook, selecting a sheet, the value of a cell changing due to a manual input or due to the reca of a formula, clicking on a selected keystroke or going to the right menu item in Excel. Preparing the Exercise on Events To complete the following exercises, copy paste the code below from your browser to the code wi "Sheet1" of the new Excel workbook as you have learned in previous lessons. Sub proFirst() Range("A1" ).Value = 34 Range("A2" ).Value = 66 Range("A3" ).Formula = "=A1+A2" Range("A1" ).Select End Sub Macros Triggered from the Developer Ribbon Step 1: Select "Macros" from the "Developer" ribbon. You will see the "Macro" dialog window belo
  • 82. Step 2: "Sheet1.proFirst" being selected in the list box and its name appearing in the text box abo box just click "Run". The macro is automatically executed Step 3: Erase the contents of cells A1, A2 and A3 You now see that colleagues must have installed VBA on their own computer to be able to use yo macros from the "Developer" ribbon. Macros Triggered by a Keystroke In this second first exercise on events we will get the macro to be keyboard activated by capital "s (Shift/S). First you need to program a key. To do so: Step 1: Select "Macros" from the "Developer" ribbon. You will see the "Macro" dialog window belo Step 2: "Sheet1.proFirst" being selected in the list box and its name appearing in the text box abo box just click on "Options". A new dialog window "Macro Options" appears:
  • 83. Step 3: In the shortcut key text box enter a capital "s" "SHIFT/s" and then click "OK". Click "Cance dialog window Step 4: If you now click "CTRL/SHIFT/S" the macro will be executed instantly. Macros Triggered by Clicking on a Text Box on the Worksheet More than 90% of the macros are triggered by a click on a button located on a worksheet. We prefer using text boxes rather than VBA command buttons because they are much easier to m and allow much more creativity in the design. You can use the font that you like and the backgrou that fits your needs. If you are a little creative you can add 3D effects, special borders and others. Step 1: From the "Insert ribbon" click on the "Text Box" icon once. Lower the curser toward the sh and hold the left button of the mouse and stretch the text box to the desired dimension. Step 2: Right click on the text box, select "Assign Macro" from the menu and the "Assign Macro" d window appears:
  • 84. Step 3: Select "Sheet1.proFirst" from the list box and its name appears in the text box above the l just click on "OK". Step 3: Click away from the text box on the Excel sheet. Step 4: Left click on the text box and the macro is executed. You can assign macros to text boxes, images or WordArt using the same approach. Here is a sample of what you will find in lchapter10 of the downloadable Tutorial on Excel macros VBA Macros Security and Protection in Excel Note 1: You will change the security setting one single time. You will not have to do it again. Tell colleagues about it specially if you want to send them Excel workbooks with macros. The setting s here is totally safe and you will not make your computer vulnerable to any virus. Special note for users of Excel 2007: See how to install the Visual Basic Editor from your Of CDand set the security level of your Excel. If you send a workbook with macros to a colleague and he can not get them to work it is probably his security setting is at "High" . Tell him how to change his level of security by going to the "Deve
  • 85. ribbon, clicking on "Macro Security", selecting "Macro Settings and checking the second level "Di Macros with Notification" and you are set. From then on each time you open a workbook that contains macros a temporary status bar appea the grid in Excel: Click on "Options" and the following dialog window will appear.
  • 86. Adopt the same attitude as you have with documents attached to Emails. If you know the origin of you may enable the macros if not click on "Disable Macros" and you are fully protected. You can workbook but the VBA procedures (macros) are not operational. You can go to the Visual Basic E take a look at the macros. If nothing looks suspicious close the workbook and re-open it enabling macros. Password Protecting the code As an Excel-VBA Developer you might want to protect your code so that nobody else may modify VBE editor go to "Tools/VBAProject Properties/Protection" . Check the box and submit a passwor sure that you save the password somewhere that you will remember. If ever you loose the passw important workbook you can always buy a program on the Internet that will allow you to view the c if it is password protected. Remember that passwords are like any locks, they only keep the honest people out. To organize your discovery of Excel macros, the downloadable Tutorial on Excel Macros is in three sections (all 3 sections part of the single download):
  • 87. Section 1: Excel Macros Programming (Chapters 1 to 10) This section is about recording, writing, modifying and testing macros in the Visual Basic Editor. You will a learn about security and discover "events" (an event is what starts the macro). Section 2: Excel VBA Vocabulary (Chapters 11 to 23) Developing a macro is communicating with Excel and to do so you need to use a language called Visual B Applications (VBA). In section 2 you will learn all the VBA vocabulary that is essential to work with busines (accounting, sales, production and others). Section 3: Forms and Controls in VBA for Exce (Chapters 24 to 33) The userform is a small or large dialog window that you create and allows the user to submit values that w by your macros. To these userforms you will add controls (command buttons, text boxes, list boxes and ot program them. Home » Excel-VBA-Tutorial » VBA-Code-Presentation Excel VBA Tutorial Part 1 - VBA Code Presentation When learning to produce VBA code, it is important, from the very start, that you adopt good habits in terms of code presentation, so that it is easy to read the code and understand how it works. While you may, at the time you are writing the code, have a clear idea of what it does and how it works, you need to consider what the code will look like when you return to it in 6 months' time. Worse still, what if someone else needs to work on your code and has to figure out how it works? This page discusses comments, code indentation and line breaks all of which will assist in making your code clearer and easier to interpret. Comments The single most important practice for writing clear, decipherable code is to add frequent comments. Comments are lines in your code which act as notes to yourself or others, to explain what the code means or what it is doing. Comments are not executed during the running of the program, so have no impact on the result your macro. VBA considers any line that starts with an apostraphe (') to be a comment and the Excel VBA editor highlights these lines by colouring them in green, so you can see, at a glance, that they are comments and will not be executed.
  • 88. See the example below, which shows comments used to clarify the details of a simple Sub procedure: ' Sub procedure to search cells A1-A100 of the current active ' sheet, and find the cell containing the supplied string Sub Find_String(sFindText As String) Dim i As Integer ' Integer used in 'For' loop Dim iRowNumber As Integer ' Integer to store result in iRowNumber = 0 ' Loop through cells A1-A100 until 'sFindText' is found For i = 1 To 100 If Cells(i, 1).Value = sFindText Then ' A match has been found to the supplied string ' Store the current row number and exit the 'For' Loop iRowNumber = i Exit For End If Next i ' Pop up a message box to let the user know if the text ' string has been found, and if so, which row it appears on If iRowNumber = 0 Then MsgBox "String " & sFindText & " not found" Else MsgBox "String " & sFindText & " found in cell A" & iRowNumber End If End Sub
  • 89. Don't worry if you don't understand some of the code in the example above - this will be explained later in this tutorial. The example has been included simply to show how comments are used to explain each section of the code. It is easy to get lazy about adding comments to your code, but it really is worth making the effort. The minutes invested in ensuring your code is well documented could save you hours of frustration in the long term. Code Indentation Another way of assisting in making your code readable is by adding indentations to it. You can see how, in the example above, the code has been indented within the main Sub procedure and then indented further inside individual blocks of code. These indented sections enable you to easily see where each block of code starts and ends. Line Breaks Your code can also be made more readable by inserting line breaks in the middle of long lines of code. In VBA, if you want to split a line up, you need to add a space followed by an underscore ( _) just before the line break. This tells the VBA compiler that the current line of code continues on the following line. The following example shows how simple line breaks can be used to make long lines of code much easier to read and understand. Consider the following 'If' statement: If (index = 1 And sColor1 = "red") Or (index = 2 And sColor1 = "blue") Or (index = 3 And sColor1 = "green") Or (index = 4And sColor1 = "brown") Then By adding line breaks the same 'If' statement can be presented as follows: If (index =1 AndsColor1 = "red") Or _ (index =2 AndsColor1= "blue") Or_ (index =3 AndsColor1= "green") Or_ (index =4 AndsColor1= "brown") Then
  • 90. When the 'If' statement is broken up over four lines, you can see the different conditions within the 'If' statement much more clearly. This example illustrates how presenting your code in a clear way can help you to produce readable code, which will help you to avoid introducing bugs or errors. xcel VBA Tutorial Part 3 - Excel Visual Basic Arrays Excel Visual Basic arrays are structures which are used to store a set of related variables of the same type. Each of the entries in the array can be accessed by an index number. For example, if you had 20 members of a team and you wanted to store all the names for use in your VBA code. You could declare 20 variables to hold the team member names, as follows: Dim Team_Member1 As String Dim Team_Member2 As String . . . Dim Team_Member20 As String Alternatively, you could use the much simpler and more organised method of storing the Team members in an array of 20 String variables: Dim Team_Members(1 To 20) As String Once you have declared the array as above, each entry of the array is populated as follows: Team_Members(1) = "John Smith" . .
  • 91. . A further advantage of storing your data in an array, rather than in individual variables, arises if you want to perform the same action on every member of the list. If your team member names were stored in 20 individual variables, you would need 20 lines of code to carry out a specific action on each name. However, if you have stored your names in an array, you can use a simple loop to carry out the action for each entry in the array. This is shown in the example code below, which prints out each name in the Team_Members array to a cell in Column A of the current Excel Worksheet: For i = 1 To 20 Cells(i,1).Value = Team_Members(i) Next i It is clear from the above that handling an array of 20 names is much less cumbersome and more organised than handling 20 individual variables, but imagine if you had 1,000 names to store! And imagine you wanted to store Surnames separately from Forenames! It is clear that it would soon become almost impossible to handle this amount of data without the use of Arrays in your VBA code. Multi-Dimensional Excel Visual Basic Arrays The Visual Basic Arrays discussed above are one-dimensional, in that they refer to one list of Names. However, arrays can have multiple dimensions. An array having two dimensions acts as a grid of values. For example, imagine that you want to store daily sales figures for the month of January, for 5 different teams. You would need a 2-dimensional array, consisting of 5 sets of figures over 31 days. You would then declare the array as follows: Dim Jan_Sales_Figures(1 To 31, 1 To 5) As Currency
  • 92. In order to access the entries in the array 'Jan_Sales_Figures', you need to use two indices, refering to the day of the month and the team number. For example, the sales figures for Team2 on January 15th would be referenced as: Jan_Sales_Figures(15, 2) You can declare arrays with 3 or more dimensions in the same way - i.e. by adding further dimensions into the declaration and using a further index to reference the array entries. Declaring Excel Visual Basic Arrays The above sections have already given some examples of Visual Basic Array declarations, but it is worth discussing this further. As seen above, a one-dimensional array can be declared as follows: Dim Team_Members(1 To 20) As String This declaration tells the VBA compiler that the array 'Team_Members' has 20 variables, which are referenced by indices 1 to 20. However, we could also decide to number our array variables from 0 to 19, in which case the declaration would be: Dim Team_Members(0 To 19) As String In fact, the default form of array indexing is to start at 0, so if you omit the start index from the declaration, and simply declare the array as: Dim Team_Members(19) As String Then the VBA compiler will understand this to be an array of 20 variables, which are indexed from 0 to 19.
  • 93. The same rules are applied to declarations of multi-dimensional Visual Basic arrays. As shown in the previous example, a two-dimensional array is declared by separating the dimension indices by a comma: Dim Jan_Sales_Figures(1 To 31, 1 To 5) As Currency However, if we omit the start indices from both dimensions, as follows: Dim Jan_Sales_Figures(31, 5) As Currency this is understood to be a two-dimensional array in which the first dimension has 32 entries, indexed from 0 to 31 and the second dimension has 6 entries, indexed from 0 to 5. Dynamic Arrays In the above examples, the arrays all have fixed dimensions. However, in many cases, we don't know how big an array is going to be before run time. We could solve this be declaring a huge array, in an attempt to cover the maximum possible size needed, but this would use up an unnecessarily large amount of memory and could slow down your program. A better option would be to use a Dynamic array, which is an array that can be sized and re-sized as many times as you like, during the execution of a macro. A dynamic array is declared with empty parentheses, as follows: Dim Team_Members() As String You then need to declare the dimension of the array during the execution of the code, using the ReDim statement: ReDim Team_Members(1 To 20) If, during the execution of the code, you need to extend the size of your array, you can use ReDim again:
  • 94. If Team_Size > 20 Then ReDim Team_Members(1 To Team_Size) End If It should be noted that resizing a dynamic array in this way will result in the loss of all the values that had previously been stored in the array. If you want to avoid this loss, and keep the values that have previously been assigned to the array, you need to use the "Preserve" keyword, as shown below: If Team_Size > 20 Then ReDim Preserve Team_Members(1 To Team_Size) End If The disadvantage of using the "Preserve" keyword when resizing Visual Basic Arrays is that you can only change the upper bound of an array, not the lower bound. Also, if you have a multi- dimensional array, the use of the "Preserve" keyword limits you to changing only the last dimension of the array. Excel VBA Tutorial Part 4 - VBA Function & Sub Procedures Built-In VBA Functions Before creating your own VBA Functions, it is useful to know that Excel VBA already has a large number of built-in functions that you can use in your code. You can view a list of these from the VBA Editor:  From an Excel Workbook, open up the VBA Editor (by pressing ALT-F11);  Press F2 to open up the Object Browser;  Select VBA in the drop-down listin the top left corner of the Object Browser;
  • 95.  The listthat appears shows the VBA built in classes, members and functions. If you click on a function name a brief description appears at the bottom of the window; Pressing F1 brings up the online help for that function. Alternatively, a list of built-in VBA functions, with examples, is provided on the VBA Functions page or the Tech on the Net website. User-Defined VBA Function & Sub Procedures In Excel Visual Basic, a set of commands to perform a specific task is placed into a procedure, which can be aFunction procedure or a Sub procedure (also known as functions and subroutines). The main difference between a VBA Function procedure and a Sub procedure is that a Function procedure returns a result, whereas a Sub procedure does not. Therefore, if you wish to perform a task that returns a result (e.g. summing of a group of numbers), you will generally use a Function procedure, but if you just need a set of actions to be carried out (e.g. formatting a set of cells), you might choose to use a Sub procedure. Arguments VBA procedures can be passed data via arguments, which are declared in the procedure definition. For example, you might have a VBA Sub procedure that adds an Integer to every cell in the current range. You could supply the value of the integer to the Sub via an argument, as follows: Sub AddToCells(i As Integer) . . . End Sub Note that it is not essential for VBA Functions or Subs to have arguments. Some procedures may not require them.
  • 96. Optional Arguments You can also define VBA procedures to have Optional arguments. These are arguments that the user can supply if they want, but if they are omitted, the procedure will assign a default value to them. To return to the example above, if we wanted to make the supplied integer argument optional, this would be declared as follows: Sub AddToCells(Optional i As Integer = 0) In this case, the supplied integer, i, has a default value of 0. You can use multiple Optional arguments in a VBA procedure, as long the Optional arguments are all positioned at the end of the argument list. Passing Arguments By Value and By Reference When arguments are passed to VBA procedures, they can be passed in two ways:  ByVal - The argumentispassedby Value.Thismeansthatjustthe value (i.e.acopy of the argument) ispassedto the procedure andtherefore,anychanges thatare made to the argumentinside the procedure will be lostwhenthe procedure isexited.  ByRef - The argumentispassedbyReference.Thismeansthatthe addressof the argumentispassed to the procedure.Anychangesthatare made to the argumentinside the procedure will be remembered whenthe procedure isexited. You can specify whether an argument is passed to a VBA procedure by value or by reference by using the ByVal or theByRef keyword when defining the procedure. This is shown below: Sub AddToCells(ByVal i As Integer) . . . End Sub In this case, the integer i is passed by Value. Any changes that are made to i will be lost when you exit the Sub procedure.
  • 97. Sub AddToCells(ByRef i As Integer) . . . End Sub In this case, the integer i is passed by Reference. When you exit the Sub, any changes that have been made to i will be remembered by the variable that was passed into the Sub procedure. It should be noted that by default, in VBA, arguments are passed by Reference. Therefore, if you do not use the ByValor the ByRef keyword, the arguments will be passed by Reference. Before discussing further properties of VBA Function and Sub procedures, it is useful to look at the two types of procedure individually. The following two sections provide a brief discussion of VBA Function and VBA Sub procedures, along with simple examples. VBA Function Procedures The VBA editor recognises a Function procedure, because the commands are positioned between the following start and end commands: Function . . . End Function As previously mentioned, VBA function procedures (unlike sub procedures) return a value. The return values have the following rules:  The data type of the returnedvalue mustbe declared inthe Functionheader.  The value to be returnedmustbe assignedtoa variable havingthe same name asthe Function.This variable doesnotneedtobe declared,asitalreadyexistsasa part of the function.
  • 98. This is illustrated in the following example. VBA Function Procedure Example: Perform a Mathematical Operation on 3 Numbers The following code shows an example of a simple VBA Function procedure that receives three arguments, each of which are 'Doubles' (double precision floating point numbers). The Function returns a further 'Double', which is the sum of the first two arguments, minus the third argument: Function SumMinus(dNum1 As Double, dNum2 As Double, dNum3 As Double) As Double SumMinus = dNum1 + dNum2 - dNum3 End Function The above very simple VBA Function procedure illustrates the way in which data arguments are supplied to a procedure. It is also seen that the Function procedure return type is defined as being a 'Double' (i.e. by the term "As Double" which is included after the Function arguments). The above example also shows how the Function procedure result is stored in a variable that has the same name as the Function. Calling VBA Function Procedures If the above simple Function procedure is typed into a Module in the Visual Basic Editor, it will then be available to be called from other VBA procedures or to be used in the worksheets of your Excel workbook. Calling a VBA Function Procedure From Another Procedure You can call a Function procedure from within another VBA procedure by simply assigning the Function to a variable. The following example shows a call to the simple SumMinus function that was defined above: Sub main()
  • 99. Dim total as Double total = SumMinus(5, 4, 3) End Sub Calling a VBA Function Procedure From A Worksheet You can call VBA Function procedures from an Excel Worksheet, in the same way as you can call any of the built-in Excel functions. Therefore, you could call the SumMinus Function procedure by typing the following into any cell of your worksheet: =SumMinus(10, 5, 2) VBA Sub Procedures The VBA editor recognises a Sub procedure, because the commands are positioned between the following start and end commands: Sub . . . End Sub VBA Sub Procedure Example 1: Center and Apply Font Size to a Selected Range of Cells The following code shows an example of a simple VBA Sub procedure that applies formatting to the current selected cell range. The cells are formatted to be aligned centrally (both horizontally and vertically) and to have a user-supplied font size: