excelSamples
https://www.excel-easy.com/examples.html
Must Watch!
MustWatch
1 Range: A range in Excel is a collection of two or more cells.
This chapter gives an overview of some very important range operations.
2 Formulas and Functions: A formula is an expression which calculates the value of a cell.
Functions are predefined formulas and are already available in Excel.
Basics
1 Ribbon: Excel selects the ribbon's Home tab when you open it.
Learn how to use the ribbon.
2 Workbook: A workbook is another word for your Excel file.
When you start Excel, click Blank workbook to create an Excel workbook from scratch.
3 Worksheets: A worksheet is a collection of cells where you keep and manipulate the data.
Each Excel workbook can contain multiple worksheets.
4 Format Cells: When we format cells in Excel, we change the appearance of a number without changing the number itself.
5 Find & Select: Learn how to use Excel's Find, Replace and Go To Special feature.
6 Templates: Instead of creating an Excel workbook from scratch, you can create a workbook based on a template.
There are many free templates available, waiting to be used.
7 Data Validation: Use data validation in Excel to make sure that users enter certain values into a cell.
8 Keyboard Shortcuts: Keyboard shortcuts allow you to do things with your keyboard instead of your mouse to increase your speed.
9 Print: This chapter teaches you how to print a worksheet and how to change some important print settings in Excel.
10 Share: Learn how to share Excel data with Word documents and other files.
11 Protect: Encrypt an Excel file with a password so that it requires a password to open it.
Functions
Discover how functions in Excel help you save time.
If you are new to functions in Excel, we recommend you to read our introduction to Formulas and Functions first.
1 Count and Sum: The most used functions in Excel are the functions that count and sum.
You can count and sum based on one criteria or multiple criteria.
2 Logical: Learn how to use Excel's logical functions, such as IF, AND, OR and NOT.
3 Cell References: Cell references in Excel are very important.
Understand the difference between relative, absolute and mixed reference, and you are on your way to success.
4 Date & Time: To enter a date in Excel, use the "/" or "-" characters.
To enter a time, use the ":" (colon).
You can also enter a date and a time in one cell.
5 Text: Excel has many functions to offer when it comes to manipulating text strings.
6 Lookup & Reference: Learn all about Excel's lookup & reference functions, such as VLOOKUP, HLOOKUP, MATCH, INDEX and CHOOSE.
7 Financial: This chapter illustrates Excel's most popular financial functions.
8 Statistical: An overview of some very useful statistical functions in Excel.
9 Round: This chapter illustrates three functions to round numbers in Excel.
ROUND, ROUNDUP and ROUNDDOWN.
10 Formula Errors: This chapter teaches you how to deal with some common formula errors in Excel.
11 Array Formulas: This chapter helps you understand array formulas in Excel.
Single cell array formulas perform multiple calculations in one cell.
Data Analysis
This section illustrates the powerful features Excel has to offer to analyze data.
1 Sort: You can sort your Excel data on one column or multiple columns.
You can sort in ascending or descending order.
2 Filter: Filter your Excel data if you only want to display records that meet certain criteria.
3 Conditional Formatting: Conditional formatting in Excel enables you to highlight cells with a certain color, depending on the cell's value.
4 Charts: A simple Excel chart can say more than a sheet full of numbers.
As you'll see, creating charts is very easy.
5 Pivot Tables: Pivot tables are one of Excel's most powerful features.
A pivot table allows you to extract the significance from a large, detailed data set.
6 Tables: Master Excel tables and analyze your data quickly and easily.
7 What-If Analysis: What-If Analysis in Excel allows you to try out different values (scenarios) for formulas.
8 Solver: Excel includes a tool called solver that uses techniques from the operations research to find optimal solutions for all kind of decision problems.
9 Analysis ToolPak: The Analysis ToolPak is an Excel add-in program that provides data analysis tools for financial, statistical and engineering data analysis.
VBA
Excel VBA (Visual Basic for Applications) is the name of the programming language of Excel.
1 Create a Macro: With Excel VBA you can automate tasks in Excel by writing so called macros.
In this chapter, learn how to create a simple macro.
2 MsgBox: The MsgBox is a dialog box in Excel VBA you can use to inform the users of your program.
3 Workbook and Worksheet Object: Learn more about the Workbook and Worksheet object in Excel VBA.
4 Range Object: The Range object, which is the representation of a cell (or cells) on your worksheet, is the most important object of Excel VBA.
5 Variables: This chapter teaches you how to declare, initialize and display a variable in Excel VBA.
6 If Then Statement: Use the If Then statement in Excel VBA to execute code lines if a specific condition is met.
7 Loop: Looping is one of the most powerful programming techniques.
A loop in Excel VBA enables you to loop through a range of cells with just a few codes lines.
8 Macro Errors: This chapter teaches you how to deal with macro errors in Excel.
9 String Manipulation: In this chapter, you'll find the most important functions to manipulate strings in Excel VBA.
10 Date and Time: Learn how to work with dates and times in Excel VBA.
11 Events: Events are actions performed by users which trigger Excel VBA to execute code.
12 Array: An array is a group of variables.
In Excel VBA, you can refer to a specific variable (element) of an array by using the array name and the index number.
13 Function and Sub: In Excel VBA, a function can return a value while a sub cannot.
14 Application Object: The mother of all objects is Excel itself.
We call it the Application object.
The application object gives access to a lot of Excel related options.
15 ActiveX Controls: Learn how to create ActiveX controls such as command buttons, text boxes, list boxes etc.
16 Userform: This chapter teaches you how to create an Excel VBA Userform.
300 Examples
You can find related examples and features on the right side of each chapterat the bottom of each chapter.
Below you can find 100 popular examples.
1 Find Duplicates: This example teaches you how to find duplicate values (or triplicates) and how to find duplicate rows in Excel.
2 Drop-down List: Drop-down lists in Excel are helpful if you want to be sure that users select an item from a list, instead of typing their own values.
3 Vlookup: The VLOOKUP function is one of the most popular functions in Excel.
This page contains many easy to follow VLOOKUP examples.
4 Histogram: This example teaches you how to make a histogram in Excel.
5 Regression: This example teaches you how to run a linear regression analysis in Excel and how to interpret the Summary Output.
6 Percent Change: The percent change formula is used very often in Excel.
For example, to calculate the Monthly Change and Total Change.
7 Pareto Chart: A Pareto chart combines a column chart and a line graph.
The Pareto principle states that, for many events, roughly 80% of the effects come from 20% of the causes.
8 Loan Amortization Schedule: This example teaches you how to create a loan amortization schedule in Excel.
9 Random Numbers: Excel has two very useful functions when it comes to generating random numbers.
RAND and RANDBETWEEN.
10 Remove Duplicates: This example teaches you how to remove duplicates in Excel.
11 If: The IF function is one of the most used functions in Excel.
This page contains many easy to follow IF examples.
12 Lock Cells: You can lock cells in Excel if you want to protect cells from being edited.
13 Standard Deviation: This page explains how to calculate the standard deviation based on the entire population using the STDEV.P function in Excel and how to estimate the standard deviation based on a sample using the STDEV.S function in Excel.
14 Count Unique Values: This example shows you how to create an array formula that counts unique values.
15 Gantt Chart: Excel does not offer Gantt as chart type, but it's easy to create a Gantt chart by customizing the stacked bar chart type.
16 Countif: The powerful COUNTIF function in Excel counts cells based on one criteria.
This page contains many easy to follow COUNTIF examples.
17 Budget: This example shows you how to create a budget in Excel.
18 Line Chart: Line charts are used to display trends over time.
Use a line chart if you have text labels, dates or a few numeric labels on the horizontal axis.
19 Transpose: Use the 'Paste Special Transpose' option to switch rows to columns or columns to rows in Excel.
You can also use the TRANSPOSE function.
20 Correlation: We can use the CORREL function or the Analysis Toolpak add-in in Excel to find the correlation coefficient between two variables.
21 Time Sheet: This example teaches you how to create a simple timesheet calculator in Excel.
22 Offset: The OFFSET function in Excel returns a cell or range of cells that is a specified number of rows and columns from a cell or range of cells.
23 Pie Chart: Pie charts are used to display the contribution of each value (slice) to a total (pie).
Pie charts always use one data series.
24 Data Tables: Instead of creating different scenarios, you can create a data table to quickly try out different values for formulas.
You can create a one variable data table or a two variable data table.
25 t-Test: This example teaches you how to perform a t-Test in Excel.
The t-Test is used to test the null hypothesis that the means of two populations are equal.
26 Advanced Filter: This example teaches you how to apply an advanced filter in Excel to only display records that meet complex criteria.
27 Frequency Distribution: Did you know that you can use pivot tables to easily create a frequency distribution in Excel? You can also use the Analysis Toolpak to create a histogram.
28 Scatter Plot: Use a scatter plot (XY chart) to show scientific XY data.
Scatter plots are often used to find out if there's a relationship between variable X and Y.
29 Anova: This example teaches you how to perform a single factor ANOVA (analysis of variance) in Excel.
A single factor or one-way ANOVA is used to test the null hypothesis that the means of several populations are all equal.
30 Compare Two Lists: This example describes how to compare two lists using conditional formatting.
31 Compound Interest: What's compound interest and what's the formula for compound interest in Excel? This example gives you the answers to these questions.
32 Sumif: The powerful SUMIF function in Excel sums cells based on one criteria.
This page contains many easy to follow SUMIF examples.
33 Bar Chart: A bar chart is the horizontal version of a column chart.
Use a bar chart if you have large text labels.
34 Concatenate: Use CONCATENATE, CONCAT, TEXTJOIN or the & operator in Excel to concatenate (join) two or more text strings.
35 Freeze Panes: If you have a large table of data in Excel, it can be useful to freeze rows or columns.
This way you can keep rows or columns visible while scrolling through the rest of the worksheet.
36 Weighted Average: To calculate a weighted average in Excel, simply use SUMPRODUCT and SUM.
37 Index and Match: Use INDEX and MATCH in Excel and impress your boss.
Instead of using VLOOKUP, use INDEX and MATCH.
To perform advanced lookups, you'll need INDEX and MATCH.
38 Delete Blank Rows: This example teaches you how to delete blank rows or rows that contain blank cells.
39 Sumproduct: To calculate the sum of the products of corresponding numbers in one or more ranges, use Excel's powerful SUMPRODUCT function.
40 Merge Cells: Merge cells into one large cell to make clear that a label in Excel applies to multiple columns.
Use CONCATENATE, TEXTJOIN or Flash Fill to merge cells without losing data.
41 Subtract: There's no SUBTRACT function in Excel.
However, there are several ways to subtract numbers in Excel.
Are you ready to improve your Excel skills?
42 Percentage: Calculating percentages in Excel is easy.
Percentage simply means 'out of 100', so 72% is '72 out of 100' and 4% is '4 out of 100', etc.
43 Contains Specific Text: To check if a cell contains specific text, use ISNUMBER and SEARCH in Excel.
There's no CONTAINS function in Excel.
44 Pmt: The PMT function in Excel calculates the payment for a loan based on constant payments and a constant interest rate.
This page contains many easy to follow PMT examples.
45 Calculate Age: To calculate the age of a person in Excel, use DATEDIF and TODAY.
The DATEDIF function has three arguments.
46 Wrap Text: Wrap text in Excel if you want to display long text on multiple lines in a single cell.
47 Indirect: Use the INDIRECT function in Excel to convert a text string into a valid reference.
You can use the & operator to create text strings.
48 Multiply: To multiply numbers in Excel, use the asterisk symbol (*) or the PRODUCT function.
Learn how to multiply columns and how to multiply a column by a constant.
49 Subtotal: Use the SUBTOTAL function in Excel instead of SUM, COUNT, MAX, etc.
to ignore rows hidden by a filter or to ignore manually hidden rows.
50 Goal Seek: If you know the result you want from a formula, use Goal Seek in Excel to find the input value that produces this formula result.
51 CAGR: There's no CAGR function in Excel.
However, simply use the RRI function in Excel to calculate the compound annual growth rate (CAGR) of an investment over a period of years.
52 If Cell is Blank: Use the IF function and an empty string in Excel to check if a cell is blank.
Use IF and ISBLANK to produce the exact same result.
53 Average: The AVERAGE function in Excel calculates the average (arithmetic mean) of a group of numbers.
54 Substring: There's no SUBSTRING function in Excel.
Use MID, LEFT, RIGHT, FIND, LEN, SUBSTITUTE, REPT, TRIM and MAX in Excel to extract substrings.
55 Count Characters: Learn how to count the number of characters in a cell or range of cells and how to count how many times a specific character occurs in a cell or range of cells.
56 Sum: Use the SUM function in Excel to sum a range of cells, an entire column or non-contiguous cells.
57 Compare Two Columns: To compare two columns, use IF, ISERROR and MATCH in Excel.
You can display the duplicates or the unique values.
58 Divide: There's no DIVIDE function in Excel.
Simply use the forward slash (/) to divide numbers in Excel.
59 Remove Spaces: The TRIM function in Excel removes leading spaces, extra spaces and trailing spaces.
Use the SUBSTITUTE function to remove all spaces or non-breaking spaces.
60 Move Columns: To move columns in Excel, use the shift key or use Insert Cut Cells.
You can also change the order of all columns in one magic move.
61 Hide Columns or Rows: Sometimes it can be useful to hide columns or rows in Excel.
62 Check Mark: To insert a check mark symbol in Excel, simply press SHIFT + P and use the Wingdings 2 font.
You can also insert a checkbox in Excel.
63 Insert Row: To quickly insert a row in Excel, select a row and use the shortcut CTRL SHIFT +.
64 Comparison Operators: Use comparison operators in Excel to check if two values are equal to each other, if one value is greater than another value, etc.
65 NPV: The correct NPV formula in Excel uses the NPV function to calculate the present value of a series of future cash flows and subtracts the initial investment.
66 Bullet Points: This page illustrates three ways to insert bullet points in Excel.
67 AverageIf: The AVERAGEIF function in Excel calculates the average of cells that meet one criteria.
AVERAGEIFS calculates the average of cells that meet multiple criteria.
68 Box and Whisker Plot: This example teaches you how to create a box and whisker plot in Excel.
A box and whisker plot shows the minimum value, first quartile, median, third quartile and maximum value of a data set.
69 Hyperlinks: Use the 'Insert Hyperlink' dialog box in Excel to create a hyperlink to an existing file, a web page or a place in this document.
You can also use the HYPERLINK function.
70 Shade Alternate Rows: This example shows you how to use conditional formatting to shade alternate rows.
71 IRR: Use the IRR function in Excel to calculate a project's internal rate of return.
72 Time Difference: Calculating the difference between two times in Excel can be tricky.
Times are handled internally as numbers between 0 and 1.
73 Quick Analysis: Use the Quick Analysis tool in Excel to quickly analyze your data.
Quickly calculate totals, quickly insert tables, quickly apply conditional formatting and more.
74 Strikethrough: This example teaches you how to apply strikethrough formatting in Excel.
75 Today's Date: To enter today's date in Excel, use the TODAY function.
To enter the current date and time, use the NOW function.
76 Sparklines: Sparklines in Excel are graphs that fit in one cell.
Sparklines are great for displaying trends.
Excel offers three sparkline types: Line, Column and Win/Loss.
77 Forecast: The FORECAST.LINEAR function in Excel predicts a future value along a linear trend.
The FORECAST.ETS function in Excel predicts a future value using Exponential Triple Smoothing, which takes into account seasonality.
78 Slicers: Use slicers in Excel to quickly and easily filter pivot tables.
Connect multiple slicers to multiple pivot tables to create awesome reports.
79 Split Cells: To split the contents of a cell into multiple cells, use the Text to Columns wizard, flash fill or formulas.
80 Calendar: This example describes how to create a calendar in Excel (2023 calendar, 2024 calendar, etc).
If you are in a hurry, simply download the Excel file.
81 Xlookup: If you have Excel 365, use XLOOKUP instead of VLOOKUP.
The XLOOKUP function is easier to use and has some additional advantages.
82 Flash Fill: Flash fill is a great Excel tool.
Learn how to use flash fill to automatically extract data, combine data, and much more.
83 Square Root: The square root of a number is a value that, when multiplied by itself, gives the number.
The SQRT function in Excel returns the square root of a number.
84 Absolute Reference: An absolute reference in Excel refers to a fixed location on a worksheet.
When you copy a formula, an absolute reference never changes.
85 Randomize List: This article teaches you how to randomize (shuffle) a list in Excel.
86 Circular Reference: A circular reference in Excel occurs when a formula directly or indirectly refers to its own cell.
This is not possible.
87 Running Total: This page teaches you how to create a running total (cumulative sum) in Excel.
A running total changes each time new data is added to a list.
88 AutoFit: You probably know how to change the width of a column in Excel, but do you also know how to automatically fit the widest entry in a column?
89 PDF: This page teaches you how to convert an Excel file to a PDF file.
90 Dependent Drop-down Lists: This example describes how to create dependent drop-down lists in Excel.
91 Add or Subtract Time: Use the TIME function in Excel to add or subtract hours, minutes and seconds.
To add up times in Excel, simply use the SUM function.
92 Frequency: The FREQUENCY function in Excel calculates how often values occur within the ranges you specify in a bin table.
93 Trendline: This example teaches you how to add a trendline to a chart in Excel.
94 Not Equal To: In Excel, <> means not equal to.
The <> operator in Excel checks if two values are not equal to each other.
Let's take a look at a few examples.
95 Weekdays: Use WEEKDAY, NETWORKDAYS and WORKDAY to create cool weekday formulas in Excel.
Are you ready to improve your Excel skills?
96 AutoFill: Use AutoFill in Excel to automatically fill a series of cells.
This page contains many easy to follow AutoFill examples.
97 Entire Rows and Columns: This example teaches you how to select entire rows and columns in Excel VBA.
Are you ready?
98 Combination Chart: A combination chart is a chart that combines two or more chart types in a single chart.
99 Copy a Formula: Simply use CTRL + c and CTRL + v to copy and paste a formula in Excel.
Use the fill handle in Excel to quickly copy a formula to other cells.
100 Rank: The RANK function in Excel returns the rank of a number in a list of numbers.
Use RANK.AVG to return the average rank if more than one number has the same rank.
VBA+
1 Create a Macro:
Swap Values
Run Code from a Module
Macro Recorder
Use Relative References
FormulaR1C1
Add a Macro to the Toolbar
Enable Macros
Protect Macro
2 MsgBox:
MsgBox Function
InputBox Function
3 Workbook and Worksheet Object:
Path and FullName
Close and Open
Loop through Books and Sheets
Sales Calculator
Files in a Directory
Import Sheets
Programming Charts
4 Range Object:
CurrentRegion
Dynamic Range
Resize
Entire Rows and Columns
Offset
From Active Cell to Last Entry
Union and Intersect
Test a Selection
Possible Football Matches
Font
Background Colors
Areas Collection
Compare Ranges
5 Variables:
Option Explicit
Variable Scope
Life of Variables
Type Mismatch
6 If Then Statement:
Logical Operators
Select Case
Tax Rates
Mod Operator
Prime Number Checker
Find Second Highest Value
Sum by Color
Delete Blank Cells
7 Loop:
Loop through Defined Range
Loop through Entire Column
Do Until Loop
Step Keyword
Create a Pattern
Sort Numbers
Randomly Sort Data
Remove Duplicates
Complex Calculations
Knapsack Problem
8 Macro Errors:
Debugging
Error Handling
Err Object
Interrupt a Macro
Subscript Out of Range
Macro Comments
9 String Manipulation:
Separate Strings
Reverse Strings
Convert to Proper Case
Instr
Count Words
10 Date and Time:
Compare Dates and Times
DateDiff Function
Weekdays
Delay a Macro
Year Occurrences
Tasks on Schedule
Sort Birthdays
11 Events:
BeforeDoubleClick Event
Highlight Active Cell
Create a Footer Before Printing
Bills and Coins
Rolling Average Table
12 Array:
Dynamic Array
Array Function
Month Names
Size of an Array
13 Function and Sub:
User Defined Function
Custom Average Function
Volatile Functions
ByRef and ByVal
14 Application Object:
StatusBar
Read Data from Text File
Write Data to Text File
Vlookup
15 ActiveX Controls:
Text Box
List Box
Combo Box
Check Box
Option Buttons
Spin Button
Loan Calculator
16 Userform:
Userform and Ranges
Currency Converter
Progress Indicator
Multiple List Box Selections
Multicolumn Combo Box
Dependent Combo Boxes
Loop through Controls
Controls Collection
Userform with Multiple Pages
Interactive Userform
1 Run Code from a Module: As a beginner to Excel VBA, you might find it difficult to decide where to put your VBA code. This example teaches you how to run code from a module.
2 Macro Recorder: The Macro Recorder, a very useful tool included in Excel VBA, records every task you perform with Excel. All you have to do is record a specific task once. Next, you can execute the task over and over with the click of a button.
3 Add a Macro to the Toolbar: If you use an Excel macro frequently, you can add it to the Quick Access Toolbar. This way you can quickly access your macro.
4 InputBox Function: You can use the InputBox function in Excel VBA to prompt the user to enter a value.
5 Close and Open: The Close and Open Method in Excel VBA can be used to close and open workbooks. Remember, the Workbooks collection contains all the Workbook objects that are currently open.
6 Files in a Directory: Use Excel VBA to loop through all closed workbooks and worksheets in a directory and display all the names.
7 Import Sheets: In this example, we will create a VBA macro that imports sheets from other Excel files into one Excel file.
8 Programming Charts: Use Excel VBA to create two programs. One program loops through all charts on a sheet and changes each chart to a pie chart. The other program changes some properties of the first chart.
9 CurrentRegion: You can use the CurrentRegion property in Excel VBA to return the range bounded by any combination of blank rows and blank columns.
10 Entire Rows and Columns: This example teaches you how to select entire rows and columns in Excel VBA. Are you ready?
11 Offset: The Offset property in Excel VBA takes the range which is a particular number of rows and columns away from a certain range.
12 From Active Cell to Last Entry: This example illustrates the End property of the Range object in Excel VBA. We will use this property to select the range from the Active Cell to the last entry in a column.
13 Background Colors: Changing background colors in Excel VBA is easy. Use the Interior property to return an Interior object. Then use the ColorIndex property of the Interior object to set the background color of a cell.
14 Compare Ranges: Learn how to create a program in Excel VBA that compares randomly selected ranges and highlights cells that are unique.
15 Option Explicit: We strongly recommend to use Option Explicit at the start of your Excel VBA code. Using Option Explicit forces you to declare all your variables.
16 Logical Operators: The three most used logical operators in Excel VBA are: And, Or and Not. As always, we will use easy examples to make things more clear.
17 Select Case: Instead of multiple If Then statements in Excel VBA, you can use the Select Case structure.
18 Mod Operator: The Mod operator in Excel VBA gives the remainder of a division.
19 Delete Blank Cells: In this example, we will create a VBA macro that deletes blank cells. First, we declare two variables of type Integer.
20 Loop through Defined Range: Use Excel VBA to loop through a defined range. For example, when we want to square the numbers in the range A1:A3.
21 Do Until Loop: VBA code placed between Do Until and Loop will be repeated until the part after Do Until is true.
22 Sort Numbers: In this example, we will create a VBA macro that sorts numbers. First, we declare three variables of type Integer and one Range object.
23 Remove Duplicates: Use Excel VBA to remove duplicates. In column A we have 10 numbers. We want to remove the duplicates from these numbers and place the unique numbers in column B.
24 Debugging: This example teaches you how to debug code in Excel VBA.
25 Error Handling: Use Excel VBA to create two programs. One program simply ignores errors. The other program continues execution at a specified line upon hitting an error.
26 Subscript Out of Range: The 'subscript out of range' error in Excel VBA occurs when you refer to a nonexistent collection member or a nonexistent array element.
27 Separate Strings: Let's create a program in Excel VBA that separates strings. Place a command button on your worksheet and add the following code lines.
28 Instr: Use Instr in Excel VBA to find the position of a substring in a string. The Instr function is quite versatile.
29 Compare Dates and Times: This example teaches you how to compare dates and times in Excel VBA.
30 DateDiff Function: The DateDiff function in Excel VBA can be used to get the number of days, weeks, months or years between two dates.
31 Highlight Active Cell: Learn how to create a program in Excel VBA that highlights the row and column of the Active Cell (selected cell). This program will amaze and impress your boss.
32 Dynamic Array: If the size of your array increases and you don't want to fix the size of the array, you can use the ReDim keyword. Excel VBA then changes the size of the array automatically.
33 User Defined Function: Excel has a large collection of functions. In most situations, those functions are sufficient to get the job done. If not, you can use Excel VBA to create your own function.
34 Read Data from Text File: Use Excel VBA to read data from a text file. This file contains some geographical coordinates we want to import into Excel.
35 Vlookup: Use the WorksheetFunction property in Excel VBA to access the VLOOKUP function. All you need is a single code line.
36 List Box: Use Excel VBA to place a list box on your worksheet. A list box is a list from where a user can select an item.
37 Check Box: A check box is a field which can be checked to store information. To create a check box in Excel VBA, execute the following steps.
38 Loan Calculator: This page teaches you how to create a simple loan calculator in Excel VBA. The worksheet contains the following ActiveX controls: two scrollbars and two option buttons.
39 Currency Converter: Use Excel VBA to create a Userform that converts any amount from one currency into another.
40 Progress Indicator: Learn how to create a progress indicator in Excel VBA. We've kept the progress indicator as simple as possible, yet it looks professional. Are you ready?
AutoFill
Use AutoFill in Excel to automatically fill a series of cells.
This page contains many easy to follow AutoFill examples.
The sky is the limit!
1. For example, enter the value 10 into cell A1 and the value 20 into cell A2.
2. Select cell A1 and cell A2 and drag the fill handle down.
The fill handle is the little green box at the lower right of a selected cell or selected range of cells.
Note: AutoFill automatically fills in the numbers based on the pattern of the first two numbers.
3. Enter Jan into cell A1.
4. Select cell A1 and drag the fill handle down.
AutoFill automatically fills in the month names.
5. Enter Product 1 into cell A1.
6. Select cell A1 and drag the fill handle down.
AutoFill automatically fills in the product names.
7. Enter Friday into cell A1.
8. Select cell A1 and drag the fill handle down.
AutoFill automatically fills in the day names.
9. Enter the date 1/14/2019 into cell A1.
10. Select cell A1 and drag the fill handle down.
AutoFill automatically fills in the days.
11. Instead of filling in days, use the AutoFill options to fill in weekdays (ignoring weekend days), months (see example below) or years.
Note: also see the options to fill the formatting only and to fill a series without formatting.
12. Enter the date 1/14/2019 into cell A1 and the date 1/21/2019 into cell A2.
13. Select cell A1 and cell A2 and drag the fill handle down.
AutoFill automatically fills in the dates based on the pattern of the first two dates.
14. Enter the time 6:00 AM into cell A1.
15. Select cell A1 and drag the fill handle across.
AutoFill automatically fills in the times.
16. When Excel doesn't recognize a list, simply create a custom list.
17. Learn how to use Flash Fill to automatically extract data, combine data, and much more.
If you have Excel 365 or Excel 2021, you can also use the SEQUENCE function to fill a series of cells.
This function is pretty cool.
18. The SEQUENCE function below generates a two-dimensional array.
Rows = 7, Columns = 4, Start = 0, Step = 5.
19. The SEQUENCE function below generates a list of odd numbers.
Rows = 10, Columns = 1, Start = 1, Step = 2.
Note: the SEQUENCE function, entered into cell A1, fills multiple cells.
Wow! This behavior in Excel 365/2021 is called spilling.
Fibonacci Sequence
It's easy to create all sorts of sequences in Excel.
For example, the Fibonacci sequence.
1. The first two numbers in the Fibonacci sequence are 0 and 1.
2. Each subsequent number can be found by adding up the two previous numbers.
3. Click on the lower right corner of cell A3 and drag it down.
Result.
The Fibonacci Sequence in Excel.
Custom Lists
If you create a custom list in Excel, you can easily fill a range with your own list of departments, clients, cities, credit card numbers, etc.
This can save time and reduce errors.
First, we will look at an example of a built-in list.
1. Type Sun into cell B2.
2. Select cell B2, click on the lower right corner of cell B2 and drag it across to cell H2.
How does Excel know this?
3. On the File tab, click Options.
4. Under Advanced, go to General and click Edit Custom Lists.
Here you can find the built-in 'days of the week' lists.
Also notice the 'months of the year' lists.
5. To create your own custom list, type some list entries, and click Add.
Note: you can also import a list from a worksheet.
6. Click OK.
7. Type London into cell C2.
8. Select cell C2, click on the lower right corner of cell C2 and drag it down to cell C5.
Note: a custom list is added to your computer's registry, so you can use it in other workbooks.
Hide Columns or Rows
Hide | Unhide | Multiple Columns or Rows | Hidden Tricks
Sometimes it can be useful to hide columns or rows in Excel.
Hide
To hide a column, execute the following steps.
1. Select a column.
2. Right click, and then click Hide.
Result:
Note: to hide a row, select a row, right click, and then click Hide.
Unhide
To unhide a column, execute the following steps.
1. Select the columns on either side of the hidden column.
2. Right click, and then click Unhide.
Result:
Note: to unhide a row, select the rows on either side of the hidden row, right click, and then click Unhide.
Multiple Columns or Rows
To hide multiple columns, execute the following steps.
1. Select multiple columns by clicking and dragging over the column headers.
2. To select non-adjacent columns, hold CTRL while clicking the column headers.
3. Right click, and then click Hide.
Result:
To unhide all columns, execute the following steps.
4. Select all columns by clicking the Select All button.
5. Right click a column header, and then click Unhide.
Result:
Note: in a similar way, you can hide and unhide multiple rows.
Hidden Tricks
Impress your boss with the following hidden :-) tricks.
To hide and show columns with the click of a button, execute the following steps.
1. Select one or more columns.
2. On the Data tab, in the Outline group, click Group.
3. To hide the columns, click the minus sign.
4. To show the columns again, click the plus sign.
Note: to ungroup the columns, first, select the columns.
Next, on the Data tab, in the Outline group, click Ungroup.
Finally, to hide cells in Excel, execute the following steps.
1. Select a range of cells.
2. Right click, and then click Format Cells.
The 'Format Cells' dialog box appears.
3. Select Custom.
4. Type the following number format code: ;;;
5. Click OK.
Result:
Note: the data is still there.
Try it yourself.
Download the Excel file, hide cells, select one of the hidden cells and look at the formula bar.
Skip Blanks
Use the 'Paste Special Skip Blanks' option and Excel will not overwrite existing values with blanks.
1. Select the range B1:B12.
2. Right click, and then click Copy.
3. Select cell A1.
4. Right click, and then click Paste Special.
5. Check Skip Blanks.
6. Click OK.
AutoFit
AutoFit Column Width | AutoFit Row Height
You probably know how to change the width of a column in Excel, but do you also know how to automatically fit the widest entry in a column?
AutoFit Column Width
The default width of a column is 64 pixels.
1. You can change the width of a column by clicking and dragging the right border of the column header.
2. To automatically fit the widest entry in a column, double click the right border of a column header.
3. To autofit multiple columns, first select multiple columns by clicking and dragging over the column headers.
Note: to select non-adjacent columns, hold CTRL while clicking the column headers.
4. Next, double click the right border of one of the column headers.
5. To change the width of all columns, first select all columns by clicking the Select All button.
6. Next, change the width of a column.
AutoFit Row Height
The techniques described above can also be used to change the height of a row.
Instead of clicking the right border of a column header, simply click the bottom border of a row header.
There's one more way to autofit columns or rows.
1. First, select multiple rows by clicking and dragging over the row headers.
2. On the Home tab, in the Cells group, click Format.
3. Click AutoFit Row Height.
Result:
Note: you can also use this technique to set a row height or a column width (see screenshot at step 3).
Be careful, don't think in pixels here.
The default width of a column is 8.43 units and the default height of a row is 15.00 units.
Transpose
Paste Special Transpose | Transpose Function | Transpose Table without Zeros | Transpose Magic
Use the 'Paste Special Transpose' option to switch rows to columns or columns to rows in Excel.
You can also use the TRANSPOSE function.
Paste Special Transpose
To transpose data, execute the following steps.
1. Select the range A1:C1.
2. Right click, and then click Copy.
3. Select cell E2.
4. Right click, and then click Paste Special.
5. Check Transpose.
6. Click OK.
Transpose Function
To insert the TRANSPOSE function, execute the following steps.
1. First, select the new range of cells.
2. Type in =TRANSPOSE(
3. Select the range A1:C1 and close with a parenthesis.
4. Finish by pressing CTRL + SHIFT + ENTER.
Note: the formula bar indicates that this is an array formula by enclosing it in curly braces {}.
To delete this array formula, select the range E2:E4 and press Delete.
5. If you have Excel 365 or Excel 2021, simply select cell E2, enter the TRANSPOSE function and press Enter.
Bye bye curly braces.
Note: the TRANSPOSE function, entered into cell E2, fills multiple cells.
Wow! This behavior in Excel 365/2021 is called spilling.
Transpose Table without Zeros
The TRANSPOSE function in Excel converts blank cells to zeros.
Simply use the IF function to fix this problem.
1. For example, cell B4 below is blank.
The TRANSPOSE function converts this blank cell to a zero (cell G3).
2. If blank, the IF function below returns an empty string (two double quotes with nothing in between) to transpose.
Transpose Magic
The 'Paste Special Transpose' option is a great way to transpose data but if you want to link the source cells to the target cells, you need a few magic tricks.
1. Select the range A1:E2.
2. Right click, and then click Copy.
3. Select cell A4.
4. Right click, and then click Paste Special.
5. Click Paste Link.
Result.
6. Select the range A4:E5 and replace all equal signs with xxx.
Result.
7. Use 'Paste Special Transpose' to transpose this data.
8. Select the range G1:H5 and replace all occurrences of 'xxx' with equal signs (the exact opposite of step 6).
Note: for example, change the value in cell C2 from 16 to 36. The value in cell H3 will also change from 16 to 36.
Split Cells
Split a Cell | Text to Columns | Flash Fill | Formulas to Split Cells
To split a cell in Excel, add a new column, change the column widths and merge cells.
To split the contents of a cell into multiple cells, use the Text to Columns wizard, flash fill or formulas.
Split a Cell
Use the following trick to "split" a cell in Excel.
1. For example, task B starts at 13:00 and requires 2 hours to complete.
Suppose task B starts at 13:30. We would like to split cell B3 and color the right half.
2. Select column C.
3. Right click, and then click Insert.
Result:
4. The default width of a column is 64 pixels.
Change the width of column B and C to 32 pixels.
5. Select cell B1 and cell C1.
6. On the Home tab, in the Alignment group, click the down arrow next to Merge & Center and click Merge Cells.
Result:
7. Repeat steps 5-6 for cell B2 and cell C2 (and cell B4 and cell C4).
8. Change the background color of cell B3 to No Fill.
Result:
Note: suppose task A ends at 15:30. Use the trick explained above to "split" cell E2. Download the Excel file and give it a try.
Text to Columns
To split the contents of a cell into multiple cells, use the Text to Columns wizard.
For example, let's split full names into last and first names.
1. Select the range with full names.
2. On the Data tab, in the Data Tools group, click Text to Columns.
The following dialog box appears.
3. Choose Delimited and click Next.
4. Clear all the check boxes under Delimiters except for the Comma and Space check box.
5. Click Finish.
Result:
Note: this example has commas and spaces as delimiters.
You may have other delimiters in your data.
Experiment by checking and unchecking the different check boxes.
You get a live preview of how your data will be separated.
Flash Fill
Do you like Magic? Instead of using the Text to Columns wizard, use flash fill to quickly split data into multiple columns.
1. First, split the contents of one cell into multiple cells.
2. Select cell B1 and press CTRL + E (flash fill shortcut).
3. Select cell C1 and press CTRL + E.
4. Select cell D1 and press CTRL + E.
Note: flash fill in Excel only works when it recognizes a pattern.
Download the Excel file and give it a try.
Visit our page about Flash Fill to learn more about this great Excel tool.
Formulas to Split Cells
One drawback when using these tools is that the output will not automatically update when the source data changes.
Create formulas to overcome this limitation.
Let's split full names into first and last names.
1. The formula below returns the first name.
2. The formula below returns the last name.
3. Select the range B2:C2 and drag it down.
Note: visit our page about separating strings to understand the logic behind these formulas.
4. If you have Excel 365, use the new TEXTSPLIT function to split text into rows or columns using delimiters.
Note: the TEXTSPLIT function, entered into cell B2, fills multiple cells (B2 and C2).
Wow! This behavior is called spilling.
Flash Fill
Example 1 | Example 2 | Example 3 | Example 4 | Example 5 | Flash Fill Limitations
Flash fill is a great Excel tool.
Learn how to use flash fill to automatically extract data, combine data, and much more.
Example 1
Use flash fill in Excel to extract the numbers in column A below.
1. First, tell Excel what you want to do by entering the value 4645 into cell B1.
2. On the Data tab, in the Data Tools group, click Flash Fill (or press CTRL + E).
Result:
Example 2
Use flash fill in Excel to combine the last names in column A below and the first names in column B below to create email addresses.
1. First, tell Excel what you want to do by entering a correct email address in cell C1.
2. On the Data tab, in the Data Tools group, click Flash Fill (or press CTRL + E).
Result:
Example 3
Use flash fill in Excel to reformat the numbers in column A below.
1. First, tell Excel what you want to do by entering a correct social security number in cell B1.
2. On the Data tab, in the Data Tools group, click Flash Fill (or press CTRL + E).
Result:
Example 4
Use flash fill in Excel to rearrange the numbers in column A below.
1. First, tell Excel what you want to do by entering a new credit card number in cell B1 (for example, swap the first 4 numbers with the last 4 numbers).
2. On the Data tab, in the Data Tools group, click Flash Fill (or press CTRL + E).
Result:
Example 5
Use flash fill in Excel to extract letters from text strings.
1. First, tell Excel what you want to do by entering the letters from the first text string in cell B1.
2. On the Data tab, in the Data Tools group, click Flash Fill (or press CTRL + E).
Result:
Flash Fill Limitations
Flash fill in Excel only works when it recognizes a pattern, and sometimes needs a little help.
For example, use flash fill in Excel to extract the numbers in column A below.
1. First, tell Excel what you want to do by entering the value 130 into cell B1.
2. On the Data tab, in the Data Tools group, click Flash Fill (or press CTRL + E).
Result:
Note: flash fill did not correctly extract the decimal numbers (only the digits after the decimal point).
3. Immediately after executing step 2, change the value in cell B3 to 26.2 and Excel will correctly extract all other decimal numbers for you.
Finally, flash fill does not automatically update your results when your source data changes.
4. For example, if you change the number in cell A1 to 200, Excel will not update the number in cell B1.
Move Columns
Shift Key | Insert Cut Cells | Magic Move
To move columns in Excel, use the shift key or use Insert Cut Cells.
You can also change the order of all columns in one magic move.
Shift Key
To quickly move columns in Excel without overwriting existing data, press and hold the shift key on your keyboard.
1. First, select a column.
2. Hover over the border of the selection.
A four-sided arrow appears.
3. Press and hold the Shift key on your keyboard.
4. Click and hold the left mouse button.
5. Move the column to the new position.
6. Release the left mouse button.
7. Release the shift key.
Result:
To move multiple columns in Excel without overwriting existing data.
8. First, select multiple columns by clicking and dragging over the column headers.
9. Repeat steps 2-7.
Result:
Note: in a similar way, you can move a single row or multiple rows in Excel.
Insert Cut Cells
If you prefer the old-fashioned way, execute the following steps.
1. First, select a column.
2. Right click, and then click Cut.
3. Select a column.
The column will be inserted before the selected column.
4. Right click, and then click Insert Cut Cells.
Result:
Note: in a similar way, you can move multiple columns, a single row or multiple rows.
Magic Move
Finally, you can change the order of all columns in one magic move.
Are you ready?
1. Select row 1.
2. Right click, and then click Insert.
3. Use the first row to indicate the new order of the columns (Sales, Quarter, Country, Last Name).
4. Select the data.
5. On the Data tab, in the Sort & Filter group, click Sort.
The Sort dialog box appears.
6. Click Options.
7. Click Sort left to Right and click OK.
8. Select Row 1 from the 'Sort by' drop-down list and click OK.
9. Delete row 1.
Result:
Note: this technique is pretty impressive if you need to rearrange the order of many columns.
ROW function
The ROW function in Excel returns the row number of a reference.
For example, =ROW(C4) returns 4. The ROW function can be quite useful.
1. The ROW function below returns 8.
2. If the reference is omitted, the ROW function returns the row number of the cell containing the ROW formula.
3. To clearly see this, select cell A2, click on the lower right corner of cell A2, and drag the ROW function down to cell A9.
4. If the reference is a range, the ROW function (entered in a single cell) returns the row number of the topmost row.
Note: to return all 5 row numbers, first select the range A1:A5 (or another range of the same size), enter =ROW(C3:F7) and finish by pressing CTRL + SHIFT + ENTER.
If you have Excel 365 or Excel 2021, simply select cell A1, enter =ROW(C3:F7) and press Enter.
5. Don't confuse the ROW function with the ROWS function.
The ROWS function counts the number of rows in a range.
Why using the ROW function in Excel?
6. For example, you can use the ROW function to sum every nth row in Excel (in the example below, every 3rd row).
Tip: use ROW, MOD and conditional formatting to shade alternate rows in Excel.
Most Used Functions
Let's check out the 10 most used Excel functions.
Visit our section about functions for detailed explanations and more awesome functions.
Tip: download the Excel file and try to insert these functions.
1. COUNT
To count the number of cells that contain numbers, use the COUNT function in Excel.
Note: use COUNTA to count all cells that are not empty.
COUNTA stands for count all.
2. SUM
To sum a range of cells, use the SUM function in Excel.
The SUM function below sums all values in column A.
Note: you can also use the SUM function to sum an entire row.
For example, =SUM(5:5) sums all values in the 5th row.3. IF
The IF function checks whether a condition is met, and returns one value if true and another value if false.
Explanation: if the score is greater than or equal to 60, the IF function shown above returns Pass, else it returns Fail.
To quickly copy this formula to the other cells, click on the lower right corner of cell C2 and drag it down to cell C6.
4. AVERAGE
To calculate the average of a group of numbers, use the AVERAGE function (no rocket science here).
The formula below calculates the average of the top 3 numbers in the range A1:A6.
Explanation: the LARGE function returns the array constant {20,15,10}.
This array constant is used as an argument for the AVERAGE function, giving a result of 15.
5. COUNTIF
The COUNTIF function below counts the number of cells that contain exactly star + a series of zero or more characters.
Explanation: an asterisk (*) matches a series of zero or more characters.
Visit our page about the COUNTIF function for more information and examples.
6. SUMIF
The SUMIF function below sums values in the range B1:B5 if the corresponding cells in the range A1:A5 contain exactly circle + 1 character.
Explanation: a question mark (?) matches exactly one character.
Visit our page about the SUMIF function for more information and examples.
7. VLOOKUP
The VLOOKUP function below looks up the value 53 (first argument) in the leftmost column of the red table (second argument).
The value 4 (third argument) tells the VLOOKUP function to return the value in the same row from the fourth column of the red table.
Note: visit our page about the VLOOKUP function to learn more about this powerful Excel function.
8. MIN
To find the minimum value, use the MIN function.
It's as simple as it sounds.
9. MAX
To find the maximum value, use the MAX function.
Note: visit our chapter about statistical functions to learn much more about Excel and Statistics.
10. SUMPRODUCT
To calculate the sum of the products of corresponding numbers in one or more ranges, use Excel's powerful SUMPRODUCT function.
Explanation: the SUMPRODUCT function performs this calculation: (2 * 1000) + (4 * 250) + (4 * 100) + (2 * 50) = 3500.
Subtract
There's no SUBTRACT function in Excel.
However, there are several ways to subtract numbers in Excel.
Are you ready to improve your Excel skills?
1. For example, the formula below subtracts numbers in a cell.
Simply use the minus sign (-) as the subtraction operator.
Don't forget, always start a formula with an equal sign (=).
2. The formula below subtracts the value in cell A2 and the value in cell A3 from the value in cell A1.
3. As you can imagine, this formula can get quite long.
Simply use the SUM function to shorten your formula.
For example, the formula below subtracts the values in the range A2:A9 from the value in cell A1.
Take a look at the screenshot below.
To subtract the numbers in column B from the numbers in column A, execute the following steps.
4a.
First, subtract the value in cell B1 from the value in cell A1.
4b.
Next, select cell C1, click on the lower right corner of cell C1 and drag it down to cell C6.
Take a look at the screenshot below.
To subtract a number from a range of cells, execute the following steps.
5a.
First, subtract the value in cell A8 from the value in cell A1. Fix the reference to cell A8 by placing a $ symbol in front of the column letter and row number ($A$8).
5b.
Next, select cell B1, click on the lower right corner of cell B1 and drag it down to cell B6.
Explanation: when we drag the formula down, the absolute reference ($A$8) stays the same, while the relative reference (A1) changes to A2, A3, A4, etc.
If you're not a formula hero, use Paste Special to subtract in Excel without using formulas!
6. For example, select cell C1.
7. Right click, and then click Copy (or press CTRL + c).
8. Select the range A1:A6.
9. Right click, and then click Paste Special.
10. Click Subtract.
11. Click OK.
Note: to subtract numbers in one column from numbers in another column, at step 6, simply select a range instead of a cell.
Multiply
To multiply numbers in Excel, use the asterisk symbol (*) or the PRODUCT function.
Learn how to multiply columns and how to multiply a column by a constant.
1. The formula below multiplies numbers in a cell.
Simply use the asterisk symbol (*) as the multiplication operator.
Don't forget, always start a formula with an equal sign (=).
2. The formula below multiplies the values in cells A1, A2 and A3.
3. As you can imagine, this formula can get quite long.
Use the PRODUCT function to shorten your formula.
For example, the PRODUCT function below multiplies the values in the range A1:A7.
4. Here's another example.
Explanation: =A1*A2*A3*A4*A5*A6*A7*B1*B2*B3*B4*C1*8 produces the exact same result.
Take a look at the screenshot below.
To multiply two columns together, execute the following steps.
5a.
First, multiply the value in cell A1 by the value in cell B1.
5b.
Next, select cell C1, click on the lower right corner of cell C1 and drag it down to cell C6.
Take a look at the screenshot below.
To multiply a column of numbers by a constant number, execute the following steps.
6a.
First, multiply the value in cell A1 by the value in cell A8. Fix the reference to cell A8 by placing a $ symbol in front of the column letter and row number ($A$8).
6b.
Next, select cell B1, click on the lower right corner of cell B1 and drag it down to cell B6.
Explanation: when we drag the formula down, the absolute reference ($A$8) stays the same, while the relative reference (A1) changes to A2, A3, A4, etc.
If you're not a formula hero, use Paste Special to multiply in Excel without using formulas!
7. For example, select cell C1.
8. Right click, and then click Copy (or press CTRL + c).
9. Select the range A1:A6.
10. Right click, and then click Paste Special.
11. Click Multiply.
12. Click OK.
Note: to multiply numbers in one column by numbers in another column, at step 7, simply select a range instead of a cell.
Divide
There's no DIVIDE function in Excel.
Simply use the forward slash (/) to divide numbers in Excel.
1. The formula below divides numbers in a cell.
Use the forward slash (/) as the division operator.
Don't forget, always start a formula with an equal sign (=).
2. The formula below divides the value in cell A1 by the value in cell B1.
3. Excel displays the #DIV/0! error when a formula tries to divide a number by 0 or an empty cell.
4. The formula below divides 43 by 8. Nothing special.
5. You can use the QUOTIENT function in Excel to return the integer portion of a division.
This function discards the remainder of a division.
6. The MOD function in Excel returns the remainder of a division.
Take a look at the screenshot below.
To divide the numbers in one column by the numbers in another column, execute the following steps.
7a.
First, divide the value in cell A1 by the value in cell B1.
7b.
Next, select cell C1, click on the lower right corner of cell C1 and drag it down to cell C6.
Take a look at the screenshot below.
To divide a column of numbers by a constant number, execute the following steps.
8a.
First, divide the value in cell A1 by the value in cell A8. Fix the reference to cell A8 by placing a $ symbol in front of the column letter and row number ($A$8).
8b.
Next, select cell B1, click on the lower right corner of cell B1 and drag it down to cell B6.
Explanation: when we drag the formula down, the absolute reference ($A$8) stays the same, while the relative reference (A1) changes to A2, A3, A4, etc.
If you're not a formula hero, use Paste Special to divide in Excel without using formulas!
9. For example, select cell C1.
10. Right click, and then click Copy (or press CTRL + c).
11. Select the range A1:A6.
12. Right click, and then click Paste Special.
13. Click Divide.
14. Click OK.
Note: to divide numbers in one column by numbers in another column, at step 9, simply select a range instead of a cell.
Square Root
The square root of a number is a value that, when multiplied by itself, gives the number.
The SQRT function in Excel returns the square root of a number.
1. First, to square a number, multiply the number by itself.
For example, 4 * 4 = 16 or 4^2 = 16.
Note: to insert a caret ^ symbol, press SHIFT + 6.
2. The square root of 16 is 4.
3. Instead of using the SQRT function, you could also use an exponent of 1/2. Don't forget the parentheses.
4. If a number is negative, the SQRT function returns the #NUM! error.
5. You can use the ABS function to remove the minus sign (-) from a negative number.
Excel has no built-in function to calculate the nth root of a number.
To calculate the nth root of a number, simply raise that number to the power of 1/n.
6. For example, 5 * 5 * 5 or 5^3 is 5 raised to the third power.
7. The cube root of 125 is 5.
8. For example, 2 * 2 * 2 * 2 * 2 * 2 or 2^6 is 2 raised to the sixth power.
9. The sixth root of 64 is 2.
Percentage
Enter a Percentage | Percentage of Total | Increase by Percentage | Percentage Change
Calculating percentages in Excel is easy.
Percentage simply means 'out of 100', so 72% is '72 out of 100' and 4% is '4 out of 100', etc.
Enter a Percentage
To enter a percentage in Excel, execute the following steps.
1. First, enter a decimal number.
2. On the Home tab, in the Number group, click the percentage symbol to apply a Percentage format.
Result.
Note: to change the percentage in cell A1, simply select cell A1 and type a new percentage (do not type a decimal number).
Percentage of Total
To calculate the percentage of a total in Excel, execute the following steps.
1. Enter the formula shown below.
This formula divides the value in cell A1 by the value in cell B1. Simply use the forward slash (/) as the division operator.
Don't forget, always start a formula with an equal sign (=).
2. On the Home tab, in the Number group, click the percentage symbol to apply a Percentage format.
Result.
3. On the Home tab, in the Number group, click the Increase Decimal button once.
Result.
Note: Excel always uses the underlying precise value in calculations, regardless of how many decimals you choose to display.
Increase by Percentage
To increase a number by a percentage in Excel, execute the following steps.
1. Enter a number in cell A1. Enter a decimal number (0.2) in cell B1 and apply a Percentage format.
2. To increase the number in cell A1 by 20%, multiply the number by 1.2 (1+0.2).
The formula below does the trick.
Note: Excel uses a default order in which calculations occur.
If a part of the formula is in parentheses, that part will be calculated first.
3. To decrease a number by a percentage, simply change the plus sign to a minus sign.
Percentage Change
To calculate the percentage change between two numbers in Excel, execute the following steps.
1. Enter an old number in cell A1 and a new number in cell B1.
2. First, calculate the difference between new and old.
3. Next, divide this result by the old number in cell A1.
Note: Excel uses a default order in which calculations occur.
If a part of the formula is in parentheses, that part will be calculated first.
4. On the Home tab, in the Number group, click the percentage symbol to apply a Percentage format.
Result.
5. The (New-Old)/Old formula always works.
Note: visit our page about the percent change formula for a practical example.
Named Range
Create a named range or a named constant and use these names in your Excel formulas.
This way you can make your formulas easier to understand.
To create a named range, execute the following steps.
1. Select the range A1:A4.
2. On the Formulas tab, in the Defined Names group, click Define Name.
3. Enter a name and click OK.
There's an even quicker way of doing this.
4. Select the range, type the name in the Name box and press Enter.
5. Now you can use this named range in your formulas.
For example, sum Prices.
To create a named constant, execute the following steps.
6. On the Formulas tab, in the Defined Names group, click Define Name.
7. Enter a name, type a value, and click OK.
8. Now you can use this named constant in your formulas.
If the tax rate changes, use the Name Manager to edit the value and Excel automatically updates all the formulas that use TaxRate.
9. On the Formulas tab, in the Defined Names group, click Name Manager.
10. Select TaxRate and click Edit.
Note: use the Name Manager to view, create, edit and delete named ranges.
If your data has labels, you can quickly create named ranges in Excel.
11. For example, select the range A1:D13.
12. On the Formulas tab, in the Defined Names group, click Create from Selection.
13. Check Top row and Left column and click OK.
14. Excel created 12 + 3 = 15 named ranges! Simply select a range and look at the Name box.
15. Use the intersect operator (space) to return the intersection of two named ranges.
Note: try it yourself.
Download the Excel file, create the named ranges quickly and easily (start with step 11) and lookup any value in this two-dimensional range.
Dynamic Named Range
A dynamic named range expands automatically when you add a value to the range.
1. For example, select the range A1:A4 and name it Prices.
2. Calculate the sum.
3. When you add a value to the range, Excel does not update the sum.
To expand the named range automatically when you add a value to the range, execute the following the following steps.
4. On the Formulas tab, in the Defined Names group, click Name Manager.
5. Click Edit.
6. Click in the "Refers to" box and enter the formula =OFFSET($A$1,0,0,COUNTA($A:$A),1)
Explanation: the OFFSET function takes 5 arguments.
Reference: $A$1, rows to offset: 0, columns to offset: 0, height: COUNTA($A:$A) and width: 1. COUNTA($A:$A) counts the number of values in column A that are not empty.
When you add a value to the range, COUNTA($A:$A) increases.
As a result, the range returned by the OFFSET function expands.
7. Click OK and Close.
8. Now, when you add a value to the range, Excel updates the sum automatically.
Paste Options
Paste | Values | Formulas | Formatting | Paste Special
This example illustrates the various paste options in Excel.
Cell B5 below contains the SUM function which calculates the sum of the range B2:B4. Furthermore, we changed the background color of this cell to yellow and added borders.
Paste
The Paste option pastes everything.
1. Select cell B5, right click, and then click Copy (or press CTRL + c).
2. Next, select cell F5, right click, and then click Paste under 'Paste Options:' (or press CTRL + v).
Result.
Values
The Values option pastes the result of the formula.
1. Select cell B5, right click, and then click Copy (or press CTRL + c).
2. Next, select cell D5, right click, and then click Values under 'Paste Options:'
Result.
Note: to quickly replace the formula in cell B5 with its own result, select cell B5, press F2 (to edit the formula) and press F9.
Formulas
The Formulas option only pastes the formula.
1. Select cell B5, right click, and then click Copy (or press CTRL + c).
2. Next, select cell F5, right click, and then click Formulas under 'Paste Options:'
Result.
Formatting
The Formatting option only pastes the formatting.
1. Select cell B5, right click, and then click Copy (or press CTRL + c).
2. Next, select cell D5, right click, and then click Formatting under 'Paste Options:'
Result.
Note: the Format Painter copy/pastes formatting even quicker.
Paste Special
The Paste Special dialog box offers many more paste options.
To launch the Paste Special dialog box, execute the following steps.
1. Select cell B5, right click, and then click Copy (or press CTRL + c).
2. Next, select cell D5, right click, and then click Paste Special.
The Paste Special dialog box appears.
Note: here you can also find the paste options described above.
You can also paste comments only, validation criteria only, use the source theme, all except borders, column widths, formulas and number formats, values and number formats.
You can also use the Paste Special dialog box to perform quick operations, skip blanks and transpose data.
Discount
Calculate Percentage Discount | Calculate Discounted Price | Calculate Original Price
If you know the original price and the discounted price, you can calculate the percentage discount.
If you know the original price and the percentage discount, you can calculate the discounted price, etc.
Calculate Percentage Discount
If you know the original price and the discounted price, you can calculate the percentage discount.
1. First, divide the discounted price by the original price.
Note: you're still paying $60 of the original $80. This equals 75%.
2. Subtract this result from 1.
Note: if you're still paying 75%, you're not paying 25% (the percentage discount).
3. On the Home tab, in the Number group, click the percentage symbol to apply a Percentage format.
Result.
Calculate Discounted Price
If you know the original price and the percentage discount, you can calculate the discounted price.
1. First, subtract the percentage discount from 1.
Note: you're still paying 75%.
2. Multiply this result by the original price.
Note: you're still paying 75% of the original $80. This equals $60.
Calculate Original Price
If you know the discounted price and the percentage discount, you can calculate the original price.
Take a look at the previous screenshot.
To calculate the discounted price, we multiplied the original price by (1 - Percentage Discount).
1. To calculate the original price, simply divide the discounted price by (1 - Percentage Discount).
Formula Bar
Where is the Formula Bar? | Edit a Formula | Show Formula Bar | Expand Formula Bar | Insert Function
The formula bar in Excel displays the value or formula of the active cell.
You can use the formula bar to enter or edit formulas.
Where is the Formula Bar?
The formula bar is located below the ribbon and above the worksheet area.
To enter a formula, execute the following steps.
1. Select a cell.
2. To let Excel know that you want to enter a formula, type an equal sign (=).
3. For example, type the formula A1*A2 and press Enter.
Excel displays the result (50) in the cell and the formula in the formula bar.
Note: use the asterisk symbol (*) to multiply numbers in Excel.
Edit a Formula
You can use the formula bar to quickly edit a formula in a cell (or to change the value in a cell).
1. Select a cell containing a formula.
2. Click in the formula bar and change the formula.
Note: use the forward slash (/) to divide numbers in Excel.
3. Press Enter.
Show Formula Bar
Show the formula bar so you can see formulas in cells.
If your formula bar is missing, execute the following steps.
1. On the View tab, in the Show group, check the Formula Bar box.
Note: to hide the formula bar, uncheck the Formula Bar box.
Sometimes this can be useful if you want to view more of your worksheet area.
Expand Formula Bar
When you have a very long formula (for example, a nested IF formula), you can always expand the formula bar.
1. Hover over the bottom of the formula bar.
A two-headed arrow appears.
2. Click and hold the left mouse button.
3. Drag the bar down.
Note: instead of executing steps 1-3, simply use the keyboard shortcut Ctrl + Shift + U to expand the formula bar.
Visit our page about the IF function to learn more about this great Excel function.
Insert Function
If you're new to functions in Excel, you can use the Insert Function button on the formula bar to search for a function.
1. First, select cell A3 and press Delete (on your keyboard) to delete the formula in cell A3.
2. Click the Insert Function button.
Excel opens the Insert Function dialog box.
3. You can search for a function or browse functions by category.
4. Select a function and click OK.
Excel opens the Functions Arguments dialog box.
5. Excel automatically adds the range A1:A2 (the arguments or input passed to the function).
6. Click OK.
Result.
Note: the formula =(A1+A2)/2 gives the exact same result.
Functions are predefined formulas and are already available in Excel.
Visit our popular section about functions to learn more about this important Excel topic.
Quick Access Toolbar
Quick Access Toolbar 101 | Commands Not in the Ribbon
If you use an Excel command frequently, you can add it to the Quick Access Toolbar.
By default, the Quick Access Toolbar contains four commands: AutoSave, Save, Undo and Redo.
Quick Access Toolbar 101
To add a command to the Quick Access Toolbar, execute the following steps.
1. Right click the command, and then click Add to Quick Access Toolbar.
2. You can now find this command on the Quick Access Toolbar.
3. To remove a command from the Quick Access Toolbar, right click the command, and then click Remove from Quick Access Toolbar.
Commands Not in the Ribbon
To add a command to the Quick Access Toolbar that isn't on the ribbon, execute the following steps.
1. Click the down arrow.
2. Click More Commands.
3. Under Choose commands from, select Commands Not in the Ribbon.
4. Select a command and click Add.
Note: by default, Excel customizes the Quick Access Toolbar for all documents (see orange arrow).
Select the current saved workbook to only customize the Quick Access Toolbar for this workbook.
5. Click OK.
6. You can now find this command on the Quick Access Toolbar.
Customize the Ribbon
The ribbon in Excel can be customized.
You can easily create your own tab and add commands to it.
1. Right click anywhere on the ribbon, and then click Customize the Ribbon.
2. Click New Tab.
3. Add the commands you like.
4. Rename the tab and group.
Note: you can also add new groups to existing tabs.
To hide a tab, uncheck the corresponding check box.
Click Reset, Reset all customizations, to delete all Ribbon customizations.
5. Click OK.
Result.
Developer Tab
Turn on the Developer tab in Excel if you want to create a macro, export and import XML files or insert controls.
To add the Developer tab to the ribbon, execute the following steps.
1. Right click anywhere on the ribbon, and then click Customize the Ribbon.
2. Under Customize the Ribbon, on the right side of the dialog box, select Main tabs (if necessary).
3. Check the Developer check box.
4. Click OK.
5. You can find the Developer tab next to the View tab.
Status Bar
Status Bar 101 | Customize Status Bar | Status Bar Secrets
The status bar in Excel can be quite useful.
By default, the status bar at the bottom of the window displays the average, count and sum of selected cells.
Status Bar 101
The status bar in Excel can do the math for you.
1. Select the range A1:A3.
2. Look at the status bar to see the average, count and sum of these cells.
3. To quickly change the workbook view, use the 3 view shortcuts on the status bar.
Note: visit our page about workbook views to learn more about this topic.
4. Use the zoom slider on the status bar to quickly zoom in or out to a preset percentage.
Note: use the ribbon to zoom to a specific percentage or to zoom to a selection.
Customize Status Bar
Many status bar options are selected by default.
Right click the status bar to activate even more options.
1. Right click the status bar.
2. For example, click Caps Lock.
Note: this doesn't turn on Caps Lock (see image above, Caps Lock is still turned off).
The status bar displays the Caps Lock status now.
3. Press the Caps Lock key on your keyboard.
4. Excel displays the text Caps Lock in the status bar.
5. Right click the status bar.
6. For example, click Minimum.
7. Select the range A1:A3.
8. Look at the status bar to see the average, count, minimum and sum of these cells.
Status Bar Secrets
Here's a little secret: Excel uses the status bar in many other situations.
If you don't like this, hide the status bar.
1. For example, filter a table.
2. Excel uses the status bar to display the number of visible records.
3. Hover over a cell with one or more comments.
4. Excel uses the status bar to display the name of the author.
5. If you have Excel 2016, use the shortcut CTRL + SHIFT + F1 to hide the ribbon and the status bar.
6. To only hide the status bar, add the following code line to the Workbook Open Event:
Application.DisplayStatusBar = False
7. Use the StatusBar property in Excel VBA to display a message on the status bar.
Note: if you're new to Excel, you can skip step 6 and step 7.
Checkbox
Insert a Checkbox | Link a Checkbox | Create a Checklist | Dynamic Chart | Delete Checkboxes | Powerful Checkboxes
Inserting a checkbox in Excel is easy.
For example, use checkboxes to create a checklist or a dynamic chart.You can also insert a check mark symbol.
Insert a Checkbox
To insert a checkbox, execute the following steps.
1. On the Developer tab, in the Controls group, click Insert.
2. Click Check Box in the Form Controls section.
3. For example, draw a checkbox in cell B2.
4. To remove "Check Box 1", right click the checkbox, click the text and delete it.
Link a Checkbox
To link a checkbox to a cell, execute the following steps.
1. Right click the checkbox and click Format Control.
2. Link the checkbox to cell C2.
3. Test the checkbox.
4. Hide column C.
5. For example, enter a simple IF function.
6. Uncheck the checkbox.
Note: read on for some cool examples.
Create a Checklist
To create a checklist, execute the following steps.
1. Draw a checkbox in cell B2.
2. Click on the lower right corner of cell B2 and drag it down to cell B11.
3. Right click the first checkbox and click Format Control.
4. Link the checkbox to the cell next to it (cell C2).
5. Repeat step 4 for the other checkboxes.
6. Insert a COUNTIF function to count the number of items packed.
7. Hide column C.
8. Insert an IF function that determines if you're good to go.
9. Click all the checkboxes.
Note: we created a conditional formatting rule to automatically change the background color of cell B16. Try it yourself.
Download the Excel file and test the checklist (second sheet).
Dynamic Chart
Let's take a look at one more cool example that uses checkboxes.
A dynamic chart.
1. For example, create a combination chart with two data series (Rainy Days and Profit).
2. Add two checkboxes.
3. Right click the first checkbox and click Format Control.
Link this checkbox to cell B15.
4. Right click the second checkbox and click Format Control.
Link this checkbox to cell C15.
5. Uncheck the second checkbox.
Cell C15 below changes to FALSE.
We're now going to create two new data series.
6. Insert the IF function shown below.
Use the fill handle to copy this formula down to cell F13.
7. Repeat this step for the new Profit data series.
Explanation: if the checkbox is checked, the old and new data series are the same.
If the checkbox is unchecked, the new data series changes to a range with #N/A errors.
8. Use the new data series to create the combination chart.
To achieve this, select the chart, right click, and then click Select Data.
9. Uncheck the first checkbox and check the second checkbox.
Note: try it yourself.
Download the Excel file and test the dynamic chart (third sheet).
Delete Checkboxes
To delete multiple checkboxes, execute the following steps.
1. Hold down CTRL and use the left mouse button to select multiple checkboxes.
2. Press Delete.
Powerful Checkboxes
Finally, you can use VBA to create powerful checkboxes in Excel.
Instead of inserting a Form control, simply insert an ActiveX control.
1. Insert a checkbox (ActiveX control).
2. At step 6, you can add your own code lines to automate all kinds of tasks.
For example, add the following code lines to hide and unhide column F.If CheckBox1.Value = True Then Columns("F").Hidden = True
If CheckBox1.Value = False Then Columns("F").Hidden = False
Note: maybe coding is one step too far for you at this stage, but it shows you one of the many other powerful features Excel has to offer.
Themes
Excel offers themes to change the look of your workbook with the click of a button.
Each theme consists of 12 colors, two fonts (Headings and Body) and effects for shapes and SmartArt.
1. On the Page Layout tab, in the Themes group, you can see that the workbook below uses the standard Office theme.
2. On the Home tab, in the Font group, you can view the Theme Colors and Theme Fonts (Calibri Light and Calibri) of this theme.
To change the theme of a workbook, execute the following steps.
3. On the Page Layout tab, in the Themes group, click Themes and choose the Badge theme.
4. On the Home tab, in the Font group, you can view the Theme Colors and Theme Fonts (Impact and Gill Sans MT) of this theme.
Note: on the Page Layout tab, in the Themes group, click Colors, Customize Colors to create new theme colors or click Fonts, Customize Fonts to create new theme fonts.
Next, click Themes, Save Current Theme to save your theme in the Document Themes folder.
You can now use this theme in all your workbooks.
You can even use this theme in Word and PowerPoint!
View Multiple Workbooks
If you want to view multiple Excel workbooks at the same time, execute the following steps.
1. First, open two or more workbooks.
2. On the View tab, in the Window group, click Arrange All.
3. Select the desired arrange setting.
For example, click Horizontal.
4. Click OK.
5. On the View tab, in the Window group, click View Side by Side (by default, Synchronous Scrolling is activated), to scroll both workbooks at the same time.
AutoRecover
File that was never saved | Saved at least once | Versions | Options
Excel periodically saves a copy of your Excel file.
Learn how to recover a file that was never saved and how to recover a file that has been saved at least once.
If Excel crashes, it displays the Document Recovery Pane, the first time you open Excel again.
This is a quick way to recover the last autosaved file.
File that was never saved
If you've never saved a file and you accidentally click Don't Save below when you close Excel (or Excel crashes), execute the following steps to recover the last autosaved file.
Note: Excel tells you if a recent copy will be available.
1. On the File tab, click Info.
2. Click Manage Workbook, Recover Unsaved Workbooks.
3. Click the last autosaved file.
Saved at least once
If you've saved a file at least once and you accidentally click Don't Save below when you close Excel (or Excel crashes), execute the following steps to recover the last autosaved file.
Note: Excel tells you if a recent copy will be available.
1. Open the Excel file!
2. On the File tab, click Info.
3. Under Manage Workbook, click the last autosaved file.
Versions
When you are working on an Excel file, Excel saves all previous autosaved files under Manage Workbook.
1. On the File tab, click Info.
2. At any time, you can go back to a previous version of your Excel file.
Note: Excel deletes all previous autosaved files when you close the Excel file.
Options
To change the AutoRecover options, execute the following steps.
1. On the File tab, click Options, Save.
Note: you can save AutoRecover information every x minutes, change the AutoRecover file location, etc.
Save in 97-2003 Format
If you save your Excel files in 97-2003 format (.xls instead of the new .xlsx format), users who do not have Excel 2007 or later installed on their computer, can still open your Excel files.
1. Open a workbook.
2. On the File tab, click Save As.
3. Select Excel 97-2003 Workbook (*.xls) from the drop-down list.
4. Click Save.
To automatically save your Excel files in 97-2003 format, execute the following steps.
5. On the File tab, click Options
6. On the left side, click Save and select Excel 97-2003 Workbook from the drop-down list.
7. Click OK.
Note: Excel will always give you a warning if features are not supported in 97-2003 format, so you can save the file in the new .xlsx format (Excel Workbook).
Zoom
In most cases, you can use the minus and plus symbols in the status bar to quickly zoom the document.
Use the buttons on the View tab to zoom to a specific percentage and to zoom to a selection.
1. To quickly zoom the document, use the minus and plus symbols in the status bar.
To zoom to a specific percentage, execute the following steps.
2. On the View tab, in the Zoom group, click Zoom.
3. Enter a number (between 10 and 400) and click OK.
To zoom to a selection, execute the following steps.
4. First, select a range of cells.
5. On the View tab, in the Zoom group, click Zoom to Selection.
Split
Split Horizontally | Split Vertically | Split into Four Panes
You can split your Excel worksheet into panes to view multiple distant parts of your worksheet at once.
Simply use the split bar to change the size of each pane.
Split Horizontally
To split your worksheet (window) into an upper and lower part (pane), execute the following steps.
1. First, select a cell in column A.
2. On the View tab, in the Window group, click Split.
3. Notice the two vertical scroll bars.
For example, use the lower vertical scroll bar to move to row 49. As you can see, the first 6 rows remain visible.
4. To change the window layout, use the horizontal split bar that divides the panes.
Note: to remove the split, simply double click the split bar.
Split Vertically
To split your sheet into a left and right pane, execute the following steps.
1. First, select a cell in row 1.
2. On the View tab, in the Window group, click Split.
Tip: you can also use the shortcut Alt + W + S to quickly enable or disable split screen in Excel.
Result:
Conclusion: you'll have two horizontal scroll bars after splitting your worksheet vertically.
Split into Four Panes
You can even split your sheet into four panes.
To achieve this, execute the following steps.
1. First, select a cell that is not in column A or row 1.
2. On the View tab, in the Window group, click Split.
Result:
Note: any changes you make to one pane are immediately reflected in the other panes.
Freeze Panes
Freeze Top Row | Unfreeze Panes | Freeze First Column | Freeze Rows | Freeze Columns | Freeze Cells | Magic Freeze Button
If you have a large table of data in Excel, it can be useful to freeze rows or columns.
This way you can keep rows or columns visible while scrolling through the rest of the worksheet.
Freeze Top Row
To freeze the top row, execute the following steps.
1. On the View tab, in the Window group, click Freeze Panes.
2. Click Freeze Top Row.
3. Scroll down to the rest of the worksheet.
Result.
Excel automatically adds a dark grey horizontal line to indicate that the top row is frozen.
Unfreeze Panes
To unlock all rows and columns, execute the following steps.
1. On the View tab, in the Window group, click Freeze Panes.
2. Click Unfreeze Panes.
Freeze First Column
To freeze the first column, execute the following steps.
1. On the View tab, in the Window group, click Freeze Panes.
2. Click Freeze First Column.
3. Scroll to the right of the worksheet.
Result.
Excel automatically adds a dark grey vertical line to indicate that the first column is frozen.
Freeze Rows
To freeze rows, execute the following steps.
1. For example, select row 4.
2. On the View tab, in the Window group, click Freeze Panes.
3. Click Freeze Panes.
4. Scroll down to the rest of the worksheet.
Result.
All rows above row 4 are frozen.
Excel automatically adds a dark grey horizontal line to indicate that the first three rows are frozen.
Freeze Columns
To freeze columns, execute the following steps.
1. For example, select column E.
2. On the View tab, in the Window group, click Freeze Panes.
3. Click Freeze Panes.
4. Scroll to the right of the worksheet.
Result.
All columns to the left of column E are frozen.
Excel automatically adds a dark grey vertical line to indicate that the first four columns are frozen.
Freeze Cells
To freeze cells, execute the following steps.
1. For example, select cell C3.
2. On the View tab, in the Window group, click Freeze Panes.
3. Click Freeze Panes.
4. Scroll down and to the right.
Result.
The orange region above row 3 and to the left of column C is frozen.
Magic Freeze Button
Add the magic Freeze button to the Quick Access Toolbar to freeze the top row, the first column, rows, columns or cells with a single click.
1. Click the down arrow.
2. Click More Commands.
3. Under Choose commands from, select Commands Not in the Ribbon.
4. Select Freeze Panes and click Add.
5. Click OK.
6. To freeze the top row, select row 2 and click the magic Freeze button.
7. Scroll down to the rest of the worksheet.
Result.
Excel automatically adds a dark grey horizontal line to indicate that the top row is frozen.
Note: to unlock all rows and columns, click the Freeze button again.
To freeze the first 4 columns, select column E (the fifth column) and click the magic Freeze button, etc.
Group Worksheets
You can group worksheets in Excel if you want to edit multiple worksheets at the same time.
Our workbook contains 3 similar worksheets (North, Mid and South) and a blank fourth worksheet.
1. To group worksheets, hold down CTRL and click the sheet tabs of the sheets you want to group.
2. Release CTRL.
Now you can edit multiple worksheets at the same time.
3. For example, on the North sheet, change the value of cell B2 to $1000 and delete row 4.
4. Go to the other two worksheets and you'll see that these worksheets have been edited as well.
5. To ungroup, right click one of the sheet tabs and click Ungroup Sheets or click any sheet tab outside the group.
For example, the sheet tab of Sheet4. Consolidate
You can use Excel's Consolidate feature to consolidate your worksheets (located in one workbook or multiple workbooks) into one worksheet.
Below you can find the workbooks of three districts.
Before you start: if your worksheets are identical, it's probably easier to create 3D-references (if you have one workbook) or External References (if you have multiple workbooks) to consolidate your data.
As you can see, the worksheets are not identical.
However, the beauty of the Consolidate feature is that it can easily sum, count, average, etc this data by looking at the labels.
This is a lot easier than creating formulas.
1. Open all three workbooks.
2. Open a blank workbook.
On the Data tab, in the Data Tools group, click Consolidate.
3. Choose the Sum function to sum the data.
4. Click in the Reference box, select the range A1:E4 in the district1 workbook, and click Add.
5. Repeat step 4 for the district2 and district3 workbook.
6. Check Top row, Left column and Create links to source data.
Note: if you don't check Top row and Left column, Excel sums all cells that have the same position.
For example, cell B2 (in district1.xlsx) + cell B2 (in district2.xlsx) + cell B2 (in district3.xlsx).Because our worksheets are not identical, we want Excel to sum cells that have the same labels.
If you check Create links to source data, Excel creates a link to your source data (your consolidated data will be updated if your source data changes) and creates an outline.
7. Click OK.
Result.
View Multiple Worksheets
If you want to view multiple Excel worksheets at the same time, execute the following steps.
1. Open a workbook.
2. On the View tab, in the Window group, click New Window.
Excel opens a new window containing another view of the document.
3. On the View tab, in the Window group, click Arrange All.
4. Select the desired arrange setting.
For example, click Horizontal.
5. Click OK.
The titles (view-multiple-worksheets:1 and view-multiple-worksheets:2) indicate that two windows of the same file are open.
6. In the lower window, select the sheet tab of Wk2. You can now view the sales in week 1 and week 2 at the same time.
Note: any changes you make to one window are immediately reflected in the other window.
7. On the View tab, in the Window group, click View Side by Side (by default, Synchronous Scrolling is activated), to scroll both worksheets at the same time.
Finally, to quickly switch between sheets in Excel, use the following handy keyboard shortcuts.
8. To quickly move to the next worksheet, press CTRL + Page Down.
9. To quickly move to the previous worksheet, press CTRL + Page Up.
Get Sheet Name
To return the sheet name in a cell, use CELL, FIND and MID in Excel.
There's no built-in function in Excel that can get the sheet name.
1. The CELL function below returns the complete path, workbook name and current worksheet name.
Note: instead of using A1, you can refer to any cell on the first worksheet to get the name of this worksheet.
2. Use the FIND function to find the position of the right bracket.
Add 1 to return the start position of the sheet name.
3. To extract a substring, starting in the middle of a string, use the MID function.
First argument (formula from step 1).
Second argument (formula from step 2).
Third argument (31).
Explanation: the MID function shown above starts at position 24 and extracts 31 characters (maximum length of a worksheet name).
4. You may want to add text to the name of the sheet.
Simply use the ampersand (&) operator as shown below.
5. To get the name of the second worksheet, simply refer to any cell on the second worksheet.
Pro tip: use Excel VBA to display the sheet names of all Excel files in a directory.
You can find detailed instructions here.
Comments
Insert Comment | Delete Comment | Show Comments
Insert a comment in Excel to start a conversation or to give feedback about the content of a cell.
Old style comments are still available and are now called notes.
Insert Comment
To insert a comment, execute the following steps.
1. Select a cell.
2. Right click, and then click New Comment.
Tip: to insert an old style comment, click New Note.
3. Type your comment and post it.
Excel displays a purple indicator in the upper-right corner of the cell.
4. Hover over the cell to view the comment.
5. To edit a comment, hover over the comment and click Edit.
6. Others can now reply to your comment.
Tip: use OneDrive to share your Excel file with other people.
Delete Comment
To delete a comment, execute the following steps.
1. Select the cell with the comment.
2. Right click, and then click Delete Comment.
Show Comments
To view all comments in an Excel file, execute the following steps.
1. On the Review tab, in the Comments group, click Show Comments.
Tip: instead of using the Review tab, simply click the Comments button in the upper-right corner of the ribbon.
Excel opens the Comments pane with all comments in this Excel file.
Tip: you can also use this pane to edit, reply to, and delete comments.
Spell Check
Learn how to check the spelling of text in Excel, add words to your custom dictionary (or AutoCorrect list) and learn how to change spell checking options.
1. Open a worksheet with some spelling errors.
Note: to spell check the entire worksheet, simply select a single cell.
If you select multiple cells, Excel only checks the spelling for those cells.
2. On the Review tab, in the Proofing group, click Spelling (or press F7).
3. Select a suggestion and click Change to correct the misspelling in cell A2.
Note: use the drop-down list to change the Dictionary language.
4. Click Change All to correct all instances of this misspelling (cell A2 and cell A7).
5. Click Ignore Once to ignore the misspelling in cell A2. Click Ignore All to ignore all instances of this misspelling.
6. Click Add to Dictionary to add this word to your custom dictionary.
7. To edit this list, click Options (see image above) and then click Custom Dictionaries (see image below).
Note: to directly open the Custom Dictionaries dialog box, click File, Options, Proofing and then click Custom Dictionaries.
8. Click AutoCorrect to add this word to your AutoCorrect list (every time you type anwer, Excel will replace it with answer).
9. To edit this list, click Options and then click AutoCorrect Options.
Note: you can also add abbreviations to your AutoCorrect list.
For example, if you type ee.com, Excel can replace it with www.excel-easy.com.
10. To spell check words in a formula bar, select the words and press F7.
11. To spell check the entire workbook, hold down CTRL to select multiple sheets and press F7.
12. By default, Excel ignores words in UPPERCASE, ignores words that contain numbers, ignores internet and file addresses and flags repeated words.
Note: to change these spell checking options, click File, Options, Proofing.
Unhide Sheets
Unhiding sheets in Excel is easy.
A workbook must contain at least one visible worksheet.
To unhide sheets, execute the following steps.
Note: if your worksheet tabs are missing, please go to step 5.
1. Right click a sheet tab and then click Unhide.
The Unhide dialog box appears.
2. Hold down CTRL to select multiple sheets.
Note: in older versions of Excel, you can only unhide one sheet at a time (see step 9 for a workaround).
3. Click OK.
Result.
4. To hide sheets, hold down CTRL to select multiple sheet tabs, right click one of the sheet tabs, and then click Hide.
If your worksheet tabs are missing, execute the following steps.
5. Hover over the left edge of the scrollbar and drag the arrow to the right to show all worksheet tabs.
6. In the screenshot below, there's not a single visible worksheet tab and there's no arrow to show all worksheet tabs.
The sheet tabs are gone.
To show the sheet tabs, execute the following steps.
7. On the File tab, click Options, Advanced, scroll down to Display options for this workbook and check 'Show sheet tabs'.
8. Click OK.
You can also use VBA to hide worksheets.
You can assign the property xlSheetHidden or xlSheetVeryHidden.
You cannot use the Unhide dialog box to unhide very hidden sheets!
9. The following codes lines unhide all hidden and very hidden sheets.
Sub UnHide()
Dim sheet As Worksheet
For Each sheet In Worksheets
sheet.Visible = True
Next
End Sub
Tip: download the Excel file and try it yourself.
You can learn how to run this procedure here: Run Code from a Module.
Chart Sheet
You can find most charts on the same worksheet as the source data (embedded charts).
However, you can also move a chart to a separate sheet that only contains a chart (chart sheet).
To move a chart to a chart sheet, execute the following steps.
1. Select the chart.
2. On the Chart Design tab, in the Location group, click Move Chart.
The Move Chart dialog box appears.
3. Click New sheet and enter a name.
4. Click OK.
Result:
Note: repeat these steps, but instead of New sheet at step 3, click Object in, to move the chart back to the same worksheet as the source data.
Visit our chapter about charts to learn more about this important Excel topic.
Decimal Places
Decrease Decimal | Increase Decimal | Useful Functions
Learn how to show fewer or more decimal places in Excel without changing the number itself.
You can also round a number.
Decrease Decimal
To decrease the number of decimal places displayed for a cell, simply click the Decrease Decimal button in Excel.
1. For example, enter the value 2.175 into cell A1.
2. On the Home tab, in the Number group, click the Decrease Decimal button twice.
Result:
Note: if you look at the formula bar, you can see that cell A1 still contains the value 2.175.
3. We can still use this underlying precise value in calculations.
Note: if you want to use 2.2 to get a result of 6.6, round the value in cell A1.
Increase Decimal
To show more decimal places, use the Increase Decimal button in Excel.
1. For example, select the range B1:B5 below.
Note: these numbers look like integers (whole numbers).
2. On the Home tab, in the Number group, click the Increase Decimal button six times.
Result:
Note: Excel stores the exact values of numbers, even if you can't see all the decimal places (except when you're using functions to change the number of decimal places, which we will see next).
Useful Functions
Excel offers several useful functions to change the number of decimal places of a number.
1. The ROUND function below rounds a number to two decimal places.
Note: if you round a number, you lose precision.
For example, if you're using the value in cell B1 in calculations, Excel uses the value 114.73 (not 114.7261).
2. The TRUNC function in Excel removes decimal places from a given number (without rounding).
Note: if you use the TRUNC function, you lose precision.
Use the second argument to specify how many decimals you want to keep.
3. To extract only the decimal part of a number, use the following formula.
Tip: visit our chapter about rounding numbers in Excel for more information and examples.
Fractions
This example teaches you how to enter a fraction in Excel and how to change the format of a fraction.
1. To enter the mixed fraction 1 4/7 (one and four sevenths), type 1 4/7. To enter the fraction 4/7 (four sevenths) into cell A1, select cell A1 and type 0 4/7 (with a 0 or Excel thinks you want to enter a date).
Now that you've entered a fraction correctly, Excel has applied a Fraction format to cell A1 and you can edit the fraction by simply typing 5/7 (without a 0).
You can find the decimal value of the fraction in the formula bar.
2. Let's take a look at the applied Fraction format.
Select cell A1, right click, and then click Format Cells.
Excel has applied the Up to one digit type.
Note: to enter a fraction like 4/11 into cell A1, change the type to Up to two digits.
To enter a fraction like 1/148 into cell A1, change the type to Up to three digits.
3a.
Excel rounds your fraction if it cannot display the right fraction.
For example, if you type 4/11 into cell A1 (with the Up to one digit type applied), Excel displays 1/3. The formula bar always shows the correct decimal value.
3b.
Change the type to Up to two digits.
Note: of course, if you type 0 4/11 into a new cell, Excel automatically applies the Up to two digits type and correctly displays 4/11.
4. Excel always reduces a fraction to its smallest denominator (bottom number of the fraction).
If you enter the fraction 2/8, Excel converts the fraction to 1/4. However, you can use the As eights (4/8) type to fix the denominator to 8.
5. Sometimes, you cannot find the right denominator for your fraction.
For example, you want to display 40/50, but Excel converts 40/50 to 4/5. However, the As fiftieths (25/50) type is not available.Create a custom number format (# ??/50) to fix this.
Note: change the 50 to 60 to create the As sixtieths (30/60) type, etc.
If you don't want to use a fraction in a calculation, but only want to diplay a fraction somewhere on your worksheet, read on.
6. On the Insert tab, in the Symbols group, click the Pi symbol to add a new equation.
7. Add a fraction to the equation.
8. Add a numerator (top number of the fraction) and a denominator (bottom number of the fraction).
Result:
Note: we increased the font size of the fraction and changed the background color of the cells to White.
Currency vs Accounting
The Currency format and the Accounting format in Excel are very similar to each other.
This example shows the difference.
1. Select the range of cells below.
2. On the Home tab, in the Number group, apply the Currency format (or press Ctrl + Shift + 4).
The Currency format places the dollar sign right next to the number.
3. On the Home tab, in the Number group, select Accounting from the drop-down list (or simply click the $ symbol).
The Accounting format aligns dollar signs and decimal points, displays a dash for zero values and displays negative numbers in parentheses.
You can use the Currency format to display negative numbers with a minus sign, in red, with parentheses, or in red with parentheses.
4. Select a cell with a negative number.
5. Right click, and then click Format Cells (or press CTRL + 1).
6. Select Currency from the Category list.
Next, under Negative Numbers, select the last option (red with parentheses) and click OK.
Result.
Did you know that you can use accounting underlines for your reports?
7. Press CTRL + 1. On the Font tab, you can choose between Single Accounting and Double Accounting.
8. For example, create the following report.
Note: accounting underlines don’t stretch all the way to the edges of a cell.
Visit our page about financial functions in Excel and become a finance expert in no time.
Text to Numbers
In Excel, text is left-aligned and numbers are right-aligned.
This example teaches you how to convert 'text strings that represent numbers' to numbers.
1. Select the range A1:A4 and change the number format to General.
2. Numbers preceded by an apostrophe are also treated as text.
Select cell A5 and manually remove the apostrophe.
3a.
You can also combine step 1 and 2 by adding an empty cell to the range A1:A5. By doing this, you let Excel know that these text strings are numbers.
Copy an empty cell.
3b.
Select the range A1:A5, right click, and then click Paste Special.
3c.
Click Add.
3d.
Click OK.
Result.
All numbers are right-aligned and treated as numbers.
4a.
You can also use the VALUE function.
4b.
Here's another example.
Use the RIGHT function (or any other text function) to extract characters from a text string and then use the VALUE function to convert these characters to a number.
Numbers to Text
In Excel, numbers are right-aligned and text is left-aligned.
This example teaches you how to convert numbers to 'text strings that represent numbers'.
1. Select the range A1:A4 and change the number format to Text.
2. Precede a number by an apostrophe and it will also be treated as text.
3a.
If you add text to a number and still want to format this number, use the TEXT function.
Without using the TEXT function this would be the result.
3b.
With the TEXT function.
Note: #,## is used to add comma's to large numbers.
3c.
Here's another example.
Apply a percentage format.
Note: use 0 to display the nearest integer value.
Use 0.0 for one decimal place.
Use 0.00 for two decimal places, etc.
3d.
And another example.
Format a date.
Note: use less/more m's, d's and y's to change the appearance of the date.
Visit our page about the TEXT function for many more examples.
Custom Number Format
Leading Zeros | Decimal Places | Add Text | Large Numbers | Repeat Characters | Colors | Dates & Times
Excel has many built-in formats that you can use: Currency, Accounting, Date, Time, Percentage, etc.
If you cannot find the right format, you can create a custom number format.
Leading Zeros
For example, you might have codes that consist of 5 numbers.Instead of typing 00041, simply type 41 and let Excel add the leading zeros.
1. Enter the value 41 into cell A1.
2. Select cell A1, right click, and then click Format Cells.
3. Select Custom.
4. Type the following number format code: 00000
5. Click OK.
Note: Excel gives you a live preview of how the number will be formatted (under Sample).
Result:
Note: cell A1 still contains the number 41. We only changed the appearance of this number, not the number itself.
Decimal Places
You can also control the number of decimal places.
Use 0 to display the nearest integer value.
Use 0.0 for one decimal place.
Use 0.00 for two decimal places, etc.
1. Enter the value 839.1274 into cell A1.
2. Use the following number format code: 0.00
Add Text
You can also add text to your numbers.
For example, add "ft".
1. Enter the value 839.1274 into cell A1.
2. Use the following number format code: 0.0 "ft"
Note: remember, we only changed the appearance of this number, not the number itself.
You can still use this number in your calculations.
Large Numbers
You can also control large numbers.
Use one comma (,) to display thousands and use two commas (,,) to display millions.
1. Enter the following values in cells A1, B1, C1 and D1: 1000000, 2500000, 81000000 and 700000.
2. Use the following number format code: 0.0,, "M"
Note: we used 0.0 for one decimal place and "M" to add the letter M.
Repeat Characters
Use the asterisk (*) followed with a character to fill a cell with that character.
1. Type Hi into cell A1.
2. Use the following number format code: @ *-
Note: the @ symbol is used to get the text input.
Colors
You can control positive numbers, negative numbers, zero values and text all at the same time! Each part is separated with a semicolon (;) in your number format code.
1. Enter the following values in cells A1, B1, C1 and A2: 5000000, 0, Hi and -5.89.
2. Use the following number format code: [Green]$#,##0_);[Red]$(#,##0);"zero";[Blue]"Text:" @
Note: #,## is used to add comma's to large numbers.
To add a space, use the underscore "_" followed by a character.
The length of the space will be the length of this character.
In our example, we added a parenthesis ")".
As a result, the positive number lines up correctly with the negative number enclosed in parentheses.
Use two parts separated with a semicolon (;) to control positive and negative numbers only.
Use three parts separated with a semicolon (;) to control positive numbers, negative numbers and zero values only.
Dates and Times
You can also control dates and times.
Use one of the existing Date or Time formats as a starting point.
1. Enter the value 42855 into cell A1.
2. Select cell A1, right click, and then click Format Cells.
3. Select Date and select the Long Date.
Note: Excel gives you a live preview of how the number will be formatted (under Sample).
4. Select Custom.
5. Slightly change the number format code to: mm/dd/yyyy, dddd
6. Click OK.
Result:
General note: a custom number format is stored in the workbook where you create it.
If you copy a value with a custom number format to another workbook, it will also be available in that workbook.
Format Painter
The Format Painter is one of the most underused features of Excel.
The Format Painter copies formatting from one place and applies it to another.
1. For example, select cell B2 below.
2. On the Home tab, in the Clipboard group, click Format Painter.
A moving dashed border appears around cell B2 and the mouse pointer changes to a plus and a paintbrush.
3. Select cell D2.
Note: the Format Painter applies the Currency format, background color and borders of cell B2 to cell D2. That saves time! Instead of selecting cell D2, you can also select a range of cells to apply the format of cell B2 to a range of cells.
4. Double click the Format Painter button to apply the same formatting to multiple cells.
Note: click the Format Painter button again (or press Esc) to exit Format Painter mode.
Cell Styles
Quickly format a cell by choosing a cell style.
You can also create your own cell style in Excel.
Quickly format a range of cells by choosing a table style.
1. For example, select cell B2 below.
2. On the Home tab, in the Styles group, choose a cell style.
Result.
To create your own cell style, execute the following steps.
3. On the Home tab, in the Styles group, click the bottom right down arrow.
Here you can find many more cell styles.
4. Click New Cell Style.
5. Enter a name and click the Format button to define the Number Format, Alignment, Font, Border, Fill and Protection of your cell style.
Simply uncheck a check box if you don't want to control this type of formatting.
6. Click OK.
7. On the Home tab, in the Styles group, apply your own cell style.
Result.
Note: right click a cell style to modify or delete it.
Modifying a cell style affects all cells in a workbook that use that cell style.
This can save a lot of time.
A cell style is stored in the workbook where you create it.
Open a new workbook and click on Merge Styles (under New Cell Style) to import a cell style (leave the old workbook with the cell style open).
Wrap Text
Wrap Text Automatically | Manual Line Break
Wrap text in Excel if you want to display long text on multiple lines in a single cell.
Wrap text automatically or enter a manual line break.
Wrap Text Automatically
1. For example, take a look at the long text string in cell A1 below.
Cell B1 is empty.
2. On the Home tab, in the Alignment group, click Wrap Text.
Result:
3. Click on the right border of the column A header and drag the separator to increase the column width.
4. Double click the bottom border of the row 1 header to automatically adjust the row height.
Note: if you manually set a row height (by clicking on the bottom border of a row header and dragging the separator), Excel does not change the row height when you click the Wrap Text button.
Simply double click the bottom border of a row header to fix this.
5. Enter an extra-long text string in cell B1 and wrap the text in this cell.
Note: by default, Excel aligns text to the bottom (see cell A1).
6. Select cell A1.
7. On the Home tab, in the Alignment group, click Top Align.
Result:
Manual Line Break
To insert a manual line break, execute the following steps.
1. For example, double click cell A1.
2. Place your cursor at the location where you want the line to break.
3. Press Alt + Enter.
Result:
Note: to remove a manual line break, double click a cell, place your cursor at the beginning of the line and press Backspace.
Merge Cells
Merge cells into one large cell to make clear that a label in Excel applies to multiple columns.
Use CONCATENATE, TEXTJOIN or Flash Fill to merge cells without losing data.
1. We start simple.
Enter a label in cell A1.
2. Select the range A1:G1.
3. On the Home tab, in the Alignment group, click Merge & Center.
Result:
This feature only keeps the value in the upper-left cell and deletes all other values!
4. For example, enter a label in cell A1, B1 and C1 and select these cells.
5. On the Home tab, in the Alignment group, click Merge & Center.
Result:
Note: click Merge & Center again to unmerge cells (cell B1 and C1 will be empty).
Press Ctrl + z to undo this action.
6. Use the CONCATENATE function in Excel to merge cells without losing data.
Explanation: this function concatenates (joins) the string in cell A1, a space, and the string in cell B1.
7. If you're using Excel 2016 or later, use TEXTJOIN to merge cells.
This function ignores empty cells (if the second argument is set to TRUE).
We saved the best for last.
You can also use Flash Fill to merge cells.
8. For example, select cell C2 below.
Type the company name and the product type.
We used a colon (:) and a space, but you can use any delimiter.
9. On the Data tab, in the Data Tools group, click Flash Fill (or press CTRL + E).
Result:
Wow! Visit our page about concatenation or flash fill for more information and examples.
Strikethrough
This example teaches you how to apply strikethrough formatting in Excel.
You can still read text with a strikethrough effect.
1. For example, select the range A2:A4.
2. Right click, and then click Format Cells (or press Ctrl + 1).
The 'Format Cells' dialog box appears.
3. On the Font tab, under Effects, click Strikethrough.
4. Click OK.
Result:
You can also use a keyboard shortcut to quickly apply strikethrough formatting in Excel.
5. For example, select cell A7.
6. Press Ctrl + 5.
Result:
Note: simply press Ctrl + 5 again to remove the strikethrough effect.
There's no double strikethrough option in Excel.
7. To apply strikethrough formatting to just part of a cell, first select the text in the formula bar.
8. Press Ctrl + 5.
Let's take a look at 2 more cool ways to quickly apply strikethrough formatting in Excel.
9. Add a strikethrough button to the Quick Access Toolbar.
10. Select cell A5 and click the strikethrough button.
11. Add the following code lines to the BeforeDoubleClick Event:
Target.Font.Strikethrough = True
Cancel = True
12. Double click cell A6.
Note: try it yourself.
Download the Excel file, use the strikethrough button or double click a cell to quickly apply strikethrough formatting.
Superscript and Subscript
It's easy to format a character as superscript (slightly above the baseline) or subscript (slightly below the baseline) in Excel.
1. For example, double click cell A1.
2. Select the value 2.
3. Right click, and then click Format Cells (or press Ctrl + 1).
The 'Format Cells' dialog box appears.
4. On the Font tab, under Effects, click Superscript.
5. Click OK.
Result:
6. Needless to say, a superscript effect cannot return a result.
To square a number, use a formula like this:
Note: to insert a caret ^ symbol, press SHIFT + 6.
7. To format a character as subscript (slightly below the baseline), repeat steps 1-5 but at step 4 click Subscript.
Result:
8. Did you know that you can also insert equations in Excel? On the Insert tab, in the Symbols group, click Equation.
Note: equations in Excel are floating objects and do not return results.
Check Mark
To insert a check mark symbol in Excel, simply press SHIFT + P and use the Wingdings 2 font.
You can also insert a checkbox in Excel.
1. Select cell A1 and press SHIFT + P to insert a capital P.
2. On the Home tab, in the Font group, select the Wingdings 2 font.
To insert a fancy check mark, change the font color to green, change the font size to 12 and apply bold formatting.
3. On the Home tab, in the Alignment group, use the Align buttons to center the check mark horizontally and vertically.
Result.
A check mark in Excel.
4. To insert a fancy red X, press SHIFT + O to insert a capital O and change the font color to red.
5. Now you can create a nice to-do list that uses check marks.
Use CTRL + c and CTRL + v to copy/paste a check mark or red X.
Instead of executing step 1 and 2, you can also use the Insert tab to insert a check mark symbol.
Here you can find other symbols as well.
6. On the Insert tab, in the Symbols group, click Symbol.
7. Select Wingdings 2 from the drop-down list, select a check mark and click Insert.
Note: you can also insert a check mark symbol with a box around it (see picture above).
After inserting one check mark, you can use the Recently used symbols to quickly insert another check mark.
8. Or simply select this check mark: , right click, and then click Copy (or press CTRL + c), open Excel, select a cell, and press CTRL + v.
Note: on the Home tab, in the Alignment group, use the Align buttons to center the check mark horizontally and vertically.
9. The formula below returns a check mark if the price is greater than 500.
Note: you can paste the check mark () directly into the formula bar.
If you're interested, you can also download the accompanying Excel file.
Find Features
To access some more advanced find features in Excel, execute the following steps.
1. Click on Options in the 'Find and Replace' dialog box.
2. Type the text you want to find.
For example, type Ferrari.
3. Select Workbook from the Within drop-down list to find occurrences across all the worksheets.
4. Checking 'Match case' will make your search case-specific.
For example, it will only find Ferrari and not ferrari.
5. Checking 'Match entire cell contents' will only find cells which contain exactly "Ferrari".
For example, cells that contain "Car Ferrari", "Ferrarii" or even "Ferrari " will not be found.
6. A question mark (?) matches exactly one character.
For example, F?rrari will find Ferrari, Forrari and Farrari.
7. An asterisk (*) matches a series of zero or more characters.
For example, F*rrari will find Ferrari, Forrari, Farrari, Foorrari and Faaaaaarrari.
Tip: visit our page about wildcards for more tips and tricks.
Wildcards
One Character | Two Characters | Zero or More Characters | Start With | End With | Tilde | Contain
Excel has 3 wildcards.
A question mark (?) matches exactly one character.
An asterisk (*) matches zero or more characters.
And a tilde (~).
Press CTRL + F to launch the Find and Replace dialog box.
One Character
A single question mark (?) matches exactly one (any) character.
Note: check "Match entire cell contents" to exclude partial matches (we want to count cells).
Two Characters
Use two question marks (??) to match any two characters.
Zero or More Characters
An asterisk (*) matches a series of zero or more characters.
Start With
Use a* to find all cells that start with the letter a.
Note: if we check "Math case", a* will not find "AB" in cell A2.
End With
Use *cd to find all cells that end with the text "cd".
Tilde
To find question marks or asterisks, precede the question mark or asterisk with a tilde (~).
For example, use *~? to find all cells that end with a question mark.
Note: ~? finds a literal question mark.
~* finds a literal asterisk.
~~ finds a literal tilde.
Contain
Use *bc* to find all cells that contain "bc".
Note: download the Excel file and give it a try.
Practice makes perfect.
Also learn how to use wildcards in formulas and how to use wildcards in filters.
Delete Blank Rows
This example teaches you how to delete blank rows or rows that contain blank cells.
1. On the Home tab, in the Editing group, click Find & Select.
2. Click Go To Special.
3. Select Blanks and click OK.
Excel selects the blank cells.
4. On the Home tab, in the Cells group, click Delete.
5. Click Delete Sheet Rows.
Result:
The following awesome trick only removes rows that are completely empty and leaves rows with a few empty cells.
6. Add a Blanks column and insert the COUNTA function.
7. Click on the lower right corner of cell H2 and drag it down to cell H10.
If the COUNTA function returns a 0, the row is "completely empty".
To filter these empty rows, execute the following steps.
8. Select cell H1.
9. On the Data tab, in the Sort & Filter group, click Filter.
Arrows in the column headers appear.
10. Click the arrow next to Blanks.
11. Click on Select All to clear all the check boxes, and click the check box next to 0.
12. Click OK.
Result.
Excel only displays the rows that are completely empty.
13. Delete these rows.
14. Click Filter again to remove the filter.
15. Delete the Blanks column.
Result:
Row Differences
This example teaches you how to quickly highlight cells whose contents are different from the comparison cell in each row.
1. To select the range A1:C15, click on cell A1 and drag it to cell C15.
Note: because we selected the range A1:C15 by clicking on cell A1 first, cell A1 is the active cell (Use ENTER and TAB to change the active cell).
As a result, the comparison cells are in column A.
2. On the Home tab, in the Editing group, click Find & Select.
3. Click Go To Special.
4. Select Row differences and click OK.
For row 2, Excel selects cell B2 because 523 is not equal to the value in cell A2 (522).For row 4, Excel selects cell B4 and cell C4 because 725 is not equal to the value in cell A4 (723), etc.
5. On the Home tab, in the Font group, change the background color of the selected cells.
Result:
Copy Visible Cells Only
By default, Excel copies both visible and hidden cells.
However, it is possible to copy visible cells only.
In this example, row 2 is hidden.
When you copy/paste this range, this is the result:
To copy visible cells only, execute the following easy steps.
1. Select the range A1:A4.
2. On the Home tab, in the Editing group, click Find & Select.
3. Click Go To Special.
4. Click Visible cells only and click OK.
Excel selects the visible cells.
5. Press Ctrl + c to copy the range.
6. Select cell A6 and press Ctrl + v to paste the range.
Result:
Search Box
This example teaches you how to create your own search box in Excel.
If you are in a hurry, simply download the Excel file.
This is what the spreadsheet looks like.
If you enter a search query into cell B2, Excel searches through column E and the results appear in column B.
To create this search box, execute the following steps.
1. Select cell D4 and insert the SEARCH function shown below.
Create an absolute reference to cell B2.
2. Double click the lower right corner of cell D4 to quickly copy the function to the other cells.
Explanation: the SEARCH function finds the position of a substring in a string.
The SEARCH function is case-insensitive.
For Tunisia, string "uni" is found at position 2. For United States, string "uni" is found at position 1. The lower the number, the higher it should be ranked.
3. Both United States and United Kingdom return the value 1. To return unique values, which will help us when we use the RANK function in a moment, slightly adjust the formula in cell D4 as shown below.
4. Again, double click the lower right corner of cell D4 to quickly copy the formula to the other cells.
Explanation: the ROW function returns the row number of a cell.
If we divide the row number by a large number and add it to the result of the SEARCH function, we always have unique values.
However, these small increments won't influence the search rankings.
United States has a value of 1.00006 now and United Kingdom has a value of 1.00009. We also added the IFERROR function.
If a cell contains an error (when a string cannot be found), an empty string ("") is displayed.
5. Select cell C4 and insert the RANK function shown below.
6. Double click the lower right corner of cell C4 to quickly copy the formula to the other cells.
Explanation: the RANK function returns the rank of a number in a list of numbers.
If the third argument is 1, Excel ranks the smallest number first, second smallest number second, etc.
Because we added the ROW function, all values in column D are unique.
As a result, the ranks in column C are unique too (no ties).
7. We are almost there.
We'll use the VLOOKUP function to return the countries found (lowest rank first, second lowest rank second, etc.) Select cell B4 and insert the VLOOKUP function shown below.
8. Double click the lower right corner of cell B4 to quickly copy the formula to the other cells.
9. Change the text color of the numbers in column A to white and hide columns C and D.
Result.
Your own search box in Excel.
Budget
This example shows you how to create a budget in Excel.
1. First, enter the different type of income and expenses in column A.
Note: on the Home tab, in the Font group, you can use the different commands to change the font size and font style of text.
Click on the right border of the column A header to increase the column width.
2. Enter the word Jan into cell B2. Next, select cell B2, click the lower right corner of the cell and drag it across to cell M2. Excel automatically adds the other months.
3. Enter some data.
4. Enter the SUM function into cell B6. To achieve this, select cell B6, type an equal sign (=), enter SUM(, select the range B4:B5, close with a ")" and press Enter.
Note: on the Home tab, in the Font group, you can add a top border.
5. Select cell B6, click the lower right corner of the cell and drag it across to cell M6. Excel copies the function and border to the other cells.
6. Enter the SUM function into cell O4. Remember, select cell O4, type =SUM(, select the range B4:M4, close with a ")" and press Enter.
7. Drag cell O4 down to cell O6.
8. Repeat steps 4 to 7 for the expenses.
9. Add a Short/Extra row.
Explanation: we created two conditional formatting rules to highlight cells lower than 0 and greater than 0. You can follow the link to learn more about this topic.
Maybe this is one step too far for you at this stage, but it shows you one of the many other powerful features Excel has to offer.
Calendar
This example describes how to create a calendar in Excel (2023 calendar, 2024 calendar, etc).
If you are in a hurry, simply download the Excel file.
Note: the instructions below do not teach you how to format the worksheet.
We assume that you know how to change font sizes, font styles, insert rows and columns, add borders, change background colors, etc.
This is what January 2025 looks like.
The big question is: how do we tell Excel that January 2025 starts on a Wednesday?
1. First, to make the formulas easier to understand, we created the following named ranges.
Name |
Cells |
CalendarYear |
K5 |
JanOffset |
=DATE(CalendarYear,1,1)-WEEKDAY(DATE(CalendarYear,1,1)) |
Explanation: dates are stored as numbers in Excel and count the number of days since January 0, 1900. The DATE function returns the number that represents the date.
The DATE function accepts three arguments: year, month and day.
The WEEKDAY function returns a number from 1 (Sunday) to 7 (Saturday) representing the day of the week of a date.
For example, January 1st, 2025 is the same as 45658. This date falls on a Wednesday.In other words, =DATE(CalendarYear,1,1) equals 45658 and WEEKDAY(DATE(CalendarYear,1,1)) equals 4. As a result, JanOffset equals 45658 - 4 = 45654.
2. Let's take a look at the formula in cell B4.
Explanation: JanOffset+1 is nothing more than a date.
In fact, it is (4-1) days earlier than January 1st, 2025. This formula checks if the year of this date equals CalendarYear and the month equals January (1).
If true, it returns the date.
If not, it returns an empty string ("").
3. Let's take a look at the formula in cell E4.
Explanation: JanOffset+4 is nothing more than a date.
In fact, it is (4-4) days earlier than January 1st, 2025. This is the first day of the year! This formula checks if the year of this date equals CalendarYear and the month equals January (1).
This is true! Excel returns the date.
4. We changed the format to "day format" to only display the day of the month.
Note: in a similar way, you can create the formulas for the other days in January and the other months.
This calendar tool lets you create a calendar for every year you want! Just use the Spin Button to increase the calendar year.
Holidays
This example teaches you how to get the date of a holiday for any year (2023, 2024, etc).
If you are in a hurry, simply download the Excel file.
Before you start: the CHOOSE function returns a value from a list of values, based on a position number.
For example, =CHOOSE(3,"Car","Train","Boat","Plane") returns Boat.The WEEKDAY function returns a number from 1 (Sunday) to 7 (Saturday) representing the day of the week of a date.
1. This is what the spreadsheet looks like.
If you enter a year into cell C2, Excel returns all the holidays for that year.
Of course, New Year's Day, Independence Day, Veteran's Day and Christmas Day are easy.
2. All other holidays can be described in a similar way: the xth day in a month (except Memorial day which is slightly different).
Let's take a look at Thanksgiving Day.
If you understand Thanksgiving Day, you understand all holidays.
Thanksgiving is celebrated the 4th Thursday in November.
The calendar below helps you understand Thanksgiving Day 2025.
Explanation: DATE(C2,11,1) reduces to 11/1/2025. WEEKDAY(DATE(C2,11,1)) reduces to 7 (Saturday).
Now the formula reduces to 11/1/2025 + 21 + CHOOSE(7,4,3,2,1,0,6,5) = 11/1/2025 + 21 + 5 = 11/27/2025. We needed the 5 extra days because it takes 5 days until the first Thursday in November.
From there, it takes another 21 days (3 weeks) until the 4rd Thursday in November.
It doesn't matter on which day November 1 falls, the CHOOSE function correctly adds the number of days until the first Thursday in November (notice the pattern in the list of values).
From there, it always takes another 21 days until the 4rd Thursday in November.
Therefore, this formula works for every year.
3. Let's take a look at Martin Luther King Jr.
Day.
This formula is almost the same.
Martin Luther King Jr.
Day is celebrated the 3rd Monday in January.
The first DATE function reduces to the first of January this time.
The base position (0) in the list of values for the CHOOSE function is located at the second spot now (we are looking for a Monday)
The calendar below helps you understand Martin Luther King Jr.
Day 2025.
Explanation: DATE(C2,1,1) reduces to 1/1/2025. WEEKDAY(DATE(C2,1,1)) reduces to 4 (Wednesday).
Now the formula reduces to 1/1/2025 + 14 + CHOOSE(4,1,0,6,5,4,3,2) = 1/1/2025 + 14 + 5 = 1/20/2025. We needed the 5 extra days because it takes 5 days until the first Monday in January.
Meal Planner
This article shows you how to create a meal planner in Excel.
Here's what we are trying to achieve:
1. On the second sheet, create the following named ranges.
Name |
Range Address |
Breakfast |
A2:A10 |
Lunch |
B2:B10 |
Dinner |
C2:C10 |
Note: you can add 7 more breakfast meals in the future without changing the range address.
2. On the first sheet, select cell C4.
3. On the Data tab, in the Data Tools group, click Data Validation.
The 'Data Validation' dialog box appears.
4. In the Allow box, click List.
5. Click in the Source box and type =Breakfast.
6. Click OK.
Result:
7. Repeat steps 2 to 6 for cell D4 and cell E4, but instead of the Breakfast reference use the Lunch and Dinner reference.
8. Select the range C4:E4 and drag it down to row 10. This will copy the drop-down lists to the other days.
Result:
Invoice
This article describes how to create a simple invoice in Excel.
1. Our invoice template is 3 columns wide.
Column A: 417 pixels.
Column B: 70 pixels.
Column C: 90 pixels.
Click on the right border of a column header to change the column width.
2. Enter some data.
3. On the Home tab, in the Font group, you can use the different commands to change font sizes, font styles, add borders, change background colors, etc.
4. To remove the gridlines, select all cells by clicking on the square above row 1 and to the left of column A and change the background color to white.
5. On the Home tab, in the Alignment group, you can use the different commands to align text.
6. Select the range C13:C32 and change the number format to Accounting.
7. Enter the TODAY function into cell C4.
8. Enter the SUM function into cell C32. To achieve this, select cell C32, type =SUM(, select the range C13:C31, close with a ")" and press Enter.
Automated Invoice
This article describes how to automate the generation of invoices in Excel.
If you are in a hurry, simply download the Excel file.
This is what the spreadsheet looks like.
If you select a Client nr from the drop-down list in cell E6, Excel automatically fills in the client information.
If you select a Product nr from one of the drop-down lists in cells A13 through A31, Excel automatically fills in the product information.
Below we'll explain how we automated the entry of the product information.
The same tricks have been used for the client information.
1. On the Products sheet, type the product information.
2. On the Invoice sheet, select cells A13 through A31.
3. On the Data tab, in the Data Tools group, click Data Validation.
4. In the Allow box, click List.
5. Click in the Source box and select the range A2:A5 on the Products sheet.
6. Manually change the 5 to 1048576 (or any other large number) to include more cells.
Now you can add as many new products as you want.
7. Click OK.
8. Select cell B13 and enter the formula shown below.
Explanation: If cell A13 is empty, the formula returns an empty string.
If not, the VLOOKUP function looks for the Product nr (1001) in the leftmost column of the range $A:$C (columns A to C) on the Products sheet, and returns the value in the same row from the second column (col_index_num is set to 2).
9. Select cell C13 and enter the formula shown below.
Explanation: This formula is almost the same as the previous formula.
This time it returns the value in the same row from the third column (col_index_num is set to 3).
10. Select cell E13 and enter the formula shown below.
Explanation: If cell A13 is empty, the formula returns an empty string.
If not, it returns the product of Price and Quantity.
11. To copy the formulas to the other cells, select the range B13:E13 and drag it down to row 31. Use the Format Painter to restore the formatting.
Default Templates
Book.xltx | Sheet.xltx
Book.xltx and Sheet.xltx are two special templates you can create and add to the XLStart folder.
As a result, Excel uses Book.xltx as the basis for new workbooks and Sheet.xltx as the basis for new worksheets.
Book.xltx
To create Book.xltx, execute the following steps.
1. Create a workbook.
For example, change the row height of all rows on the first sheet to 30 pixels.
Note: you can also add a header or footer, change the styles, add or delete sheets, etc.
2. On the File tab, click Save As.
3. Click Browse.
4. Enter Book as filename.
5. Select Excel Template (*.xltx) from the drop-down list.
Excel automatically activates the Templates folder.
Be careful not to store the template here.
Instead, go to the XLStart folder.
It's usually located here:
C:\Users\<username>\AppData\Roaming\Microsoft\Excel\XLSTART
6. Click Save.
7. Close and reopen Excel.
Excel creates a new workbook based on Book.xltx.
Note: to stop using Book.xltx, simply delete the file from the XLStart folder.
To edit Book.xltx, on the File tab, click Open and then click Browse, to open the template.
Edit the file and save the file to its original location.
Sheet.xltx
Repeat the previous steps, but now create a workbook with a single sheet and name it Sheet.xltx.
This template will be used as the basis for new worksheets inserted into existing workbooks.
Time Sheet
This example teaches you how to create a simple timesheet calculator in Excel.
Cells that contain formulas are colored light yellow.
If you are in a hurry, simply download the Excel file.
1. To automatically calculate the next 4 days and dates when you enter a start date, use the formulas below.
2. Select the cells containing the times.
3. Right click, click Format Cells, and select the right Time format.
Use the circled format for cell K12, K13 and K14.
4. To automatically calculate the hours worked each day, the total hours and the overtime hours, use the formulas below.
BMI calculator
Create a BMI calculator in Excel and find out if you are a healthy weight.
Body mass index (BMI) is a measure of body fat based on weight and height that applies to adult men and women.
If you're in a hurry, simply download the Excel file.
Below you can find a screenshot of the BMI calculator.
Note: the instructions below do not teach you how to format the worksheet.
We assume that you know how to change font sizes, font styles, insert rows and columns, add borders, change background colors, etc.
To create this BMI calculator, execute the following steps.
1. Create a drop-down list in cell C5.
2. Insert an IF function into cell D7, D9 and D10 to show the correct units.
3. Select Metric from the drop-down list.
The IF function in cell D10 returns an empty string.
Create a conditional formatting rule that changes the format of cell C10 when you select Metric from the drop-down list (step 6, 7 and 8).
4. Create the BMI formula.
Explanation: C9*12+C10 calculates the height in inches and C9/100 calculates the height in meters.
Using standard units, BMI = 703*pounds/inches^2. Using metric units, BMI = kg/m^2. Excel uses a default order in which calculations occur.
If a part of the formula is in parentheses, that part will be calculated first.
Also remember, Excel performs exponentiation (^) before multiplication (*) and division (/).
5. Enter a weight of 250 pounds.
Excel calculates the body mass index (BMI) and automatically changes the background color of the range C13:E13. This feature is called conditional formatting (step 6, 7 and 8).
6. On the Home tab, in the Styles group, click Conditional Formatting.
7. Click Manage Rules.
The Conditional Formatting Rules Manager appears.
8. From the drop-down list, change Current Selection to This Worksheet, to view all conditional formatting rules in this worksheet.
Note: select a rule and click Edit Rule to take a closer look at each rule.
The first 4 rules correspond with the BMI categories (underweight, normal weight, overweight and obese).
The 5th rule changes the format of cell C10 when you select Metric from the drop-down list (step 3).
Reject Invalid Dates
Outside a Date Range | Sundays and Saturdays
This example teaches you how to use data validation to reject invalid dates.
1. Select the range A2:A4.
2. On the Data tab, in the Data Tools group, click Data Validation.
Outside a Date Range
3. In the Allow list, click Date.
4. In the Data list, click between.
5. Enter the Start date and End date shown below and click OK.
Explanation: all dates between 5/20/2016 and today's date + 5 days are allowed.
All dates outside this date range are rejected.
6. Enter the date 5/19/2016 into cell A2.
Result.
Excel shows an error alert.
Note: to enter an input message and error alert message, go to the Input Message and Error Alert tab.
Sundays and Saturdays
3. In the Allow list, click Custom.
4. In the Formula box, enter the formula shown below and click OK.
Explanation: the WEEKDAY function returns a number from 1 (Sunday) to 7 (Saturday) representing the day of the week of a date.
If a date's weekday is not equal to 1 (Sunday) AND not equal to 7 (Saturday), the date is allowed (<> means not equal to).
In other words, Mondays, Tuesdays, Wednesdays, Thursdays and Fridays are allowed.
Sundays and Saturdays are rejected.
Because we selected the range A2:A4 before we clicked on Data Validation, Excel automatically copies the formula to the other cells.
5. To check this, select cell A3 and click Data Validation.
As you can see, this cell also contains the correct formula.
6. Enter the date 8/27/2016 (Saturday) into cell A2.
Result.
Excel shows an error alert.
Note: to enter an input message and error alert message, go to the Input Message and Error Alert tab.
Budget Limit
This example teaches you how to use data validation to prevent users from exceeding a budget limit.
1. Select the range B2:B8.
Note: cell B10 contains a SUM function that calculates the sum of the range B2:B8.
2. On the Data tab, in the Data Tools group, click Data Validation.
3. In the Allow list, click Custom.
4. In the Formula box, enter the formula shown below and click OK.
Explanation: the sum of the range B2:B8 may not exceed the budget limit of $100. Therefore, we apply data validation to the range B2:B8 (not cell B10!) because this is where the values are entered.
Because we selected the range B2:B8 before we clicked on Data Validation, Excel automatically copies the formula to the other cells.
Notice how we created an absolute reference ($B$2:$B$8) to fix this reference.
5. To check this, select cell B3 and click Data Validation.
As you can see, this cell also contains the correct formula.
6. Enter the value 30 into cell B7.
Result.
Excel shows an error alert.
You cannot exceed your budget limit of $100.
Note: to enter an error alert message, go to the Error Alert tab.
Prevent Duplicate Entries
This example teaches you how to use data validation to prevent users from entering duplicate values.
1. Select the range A2:A20.
2. On the Data tab, in the Data Tools group, click Data Validation.
3. In the Allow list, click Custom.
4. In the Formula box, enter the formula shown below and click OK.
Explanation: The COUNTIF function takes two arguments.
=COUNTIF($A$2:$A$20,A2) counts the number of values in the range A2:A20 that are equal to the value in cell A2. This value may only occur once (=1) since we don't want duplicate entries.
Because we selected the range A2:A20 before we clicked on Data Validation, Excel automatically copies the formula to the other cells.
Notice how we created an absolute reference ($A$2:$A$20) to fix this reference.
5. To check this, select cell A3 and click Data Validation.
As you can see, this function counts the number of values in the range A2:A20 that are equal to the value in cell A3. Again, this value may only occur once (=1) since we don't want duplicate entries.
6. Enter a duplicate invoice number.
Result.
Excel shows an error alert.
You've already entered that invoice number.
Note: to enter an input message and error alert message, go to the Input Message and Error Alert tab.
Product Codes
This example teaches you how to use data validation to prevent users from entering incorrect product codes.
1. Select the range A2:A7.
2. On the Data tab, in the Data Tools group, click Data Validation.
3. In the Allow list, click Custom.
4. In the Formula box, enter the formula shown below and click OK.
Explanation: this AND function has three arguments.
LEFT(A2)="C" forces the user to start with the letter C.
LEN(A2)=4 forces the user to enter a string with a length of 4 characters.
ISNUMBER(VALUE(RIGHT(A2,3))) forces the user to end with 3 numbers.
RIGHT(A2,3) extracts the 3 rightmost characters from the text string.
The VALUE function converts this text string to a number.
ISNUMBER checks whether this value is a number.
The AND Function returns TRUE if all conditions are true.
Because we selected the range A2:A7 before we clicked on Data Validation, Excel automatically copies the formula to the other cells.
5. To check this, select cell A3 and click Data Validation.
As you can see, this cell also contains the correct formula.
6. Enter an incorrect product code.
Result.
Excel shows an error alert.
Note: to enter an input message and error alert message, go to the Input Message and Error Alert tab.
Drop-down List
Create a Drop-down List | Allow Other Entries | Add/Remove Items | Dynamic Drop-down List | Remove a Drop-down List | Dependent Drop-down Lists | Table Magic
Drop-down lists in Excel are helpful if you want to be sure that users select an item from a list, instead of typing their own values.
Create a Drop-down List
To create a drop-down list in Excel, execute the following steps.
1. On the second sheet, type the items you want to appear in the drop-down list.
Note: if you don't want users to access the items on Sheet2, you can hide Sheet2. To achieve this, right click on the sheet tab of Sheet2 and click on Hide.
2. On the first sheet, select cell B1.
3. On the Data tab, in the Data Tools group, click Data Validation.
The 'Data Validation' dialog box appears.
4. In the Allow box, click List.
5. Click in the Source box and select the range A1:A3 on Sheet2.
6. Click OK.
Result:
Note: to copy/paste a drop-down list, select the cell with the drop-down list and press CTRL + c, select another cell and press CTRL + v.
7. You can also type the items directly into the Source box, instead of using a range reference.
Note: this makes your drop-down list case sensitive.
For example, if a user types yes, an error alert will be displayed.Allow Other Entries
You can also create a drop-down list in Excel that allows other entries.
1. First, if you type a value that is not in the list, Excel shows an error alert.
To allow other entries, execute the following steps.
2. On the Data tab, in the Data Tools group, click Data Validation.
The 'Data Validation' dialog box appears.
3. On the Error Alert tab, uncheck 'Show error alert after invalid data is entered'.
4. Click OK.
5. You can now enter a value that is not in the list.
Add/Remove Items
You can add or remove items from a drop-down list in Excel without opening the 'Data Validation' dialog box and changing the range reference.
This saves time.
1. To add an item to a drop-down list, go to the items and select an item.
2. Right click, and then click Insert.
3. Select "Shift cells down" and click OK.
Result:
Note: Excel automatically changed the range reference from Sheet2!$A$1:$A$3 to Sheet2!$A$1:$A$4. You can check this by opening the 'Data Validation' dialog box.
4. Type a new item.
Result:
5. To remove an item from a drop-down list, at step 2, click Delete, select "Shift cells up" and click OK.
Dynamic Drop-down List
You can also use a formula that updates your drop-down list automatically when you add an item to the end of the list.
1. On the first sheet, select cell B1.
2. On the Data tab, in the Data Tools group, click Data Validation.
The 'Data Validation' dialog box appears.
3. In the Allow box, click List.
4. Click in the Source box and enter the formula: =OFFSET(Sheet2!$A$1,0,0,COUNTA(Sheet2!$A:$A),1)
Explanation: the OFFSET function takes 5 arguments.
Reference: Sheet2!$A$1, rows to offset: 0, columns to offset: 0, height: COUNTA(Sheet2!$A:$A) and width: 1. COUNTA(Sheet2!$A:$A) counts the number of values in column A on Sheet2 that are not empty.
When you add an item to the list on Sheet2, COUNTA(Sheet2!$A:$A) increases.
As a result, the range returned by the OFFSET function expands and the drop-down list will be updated.
5. Click OK.
6. On the second sheet, simply add a new item to the end of the list.
Result:
Remove a Drop-down List
To remove a drop-down list in Excel, execute the following steps.
1. Select the cell with the drop-down list.
2. On the Data tab, in the Data Tools group, click Data Validation.
The 'Data Validation' dialog box appears.
3. Click Clear All.
Note: to remove all other drop-down lists with the same settings, check "Apply these changes to all other cells with the same settings" before you click on Clear All.
4. Click OK.
Dependent Drop-down Lists
Want to learn even more about drop-down lists in Excel? Learn how to create dependent drop-down lists.
1. For example, if the user selects Pizza from a first drop-down list.
2. A second drop-down list contains the Pizza items.
3. But if the user selects Chinese from the first drop-down list, the second drop-down list contains the Chinese dishes.
Table Magic
You can also store your items in an Excel table to create a dynamic drop-down list.
1. On the second sheet, select a list item.
2. On the Insert tab, in the Tables group, click Table.
3. Excel automatically selects the data for you.
Click OK.
4. If you select the list, Excel reveals the structured reference.
5. Use this structured reference to create a dynamic drop-down list.
Explanation: the INDIRECT function in Excel converts a text string into a valid reference.
6. On the second sheet, simply add a new item to the end of the list.
Result:
Note: try it yourself.
Download the Excel file and create this drop-down list.
7. When using tables, use the UNIQUE function in Excel 365/2021 to extract unique list items.
Note: this dynamic array function, entered into cell F1, fills multiple cells.
Wow! This behavior in Excel 365/2021 is called spilling.
8. Use this spill range to create a magic drop-down list.
Explanation: always use the first cell (F1) and a hash character to refer to a spill range.
Result:
Note: when you add new records, the UNIQUE function automatically extracts new unique list items and Excel automatically updates the drop-down list.
Dependent Drop-down Lists
This example describes how to create dependent drop-down lists in Excel.
Here's what we are trying to achieve:
The user selects Pizza from a drop-down list.
As a result, a second drop-down list contains the Pizza items.
To create these dependent drop-down lists, execute the following steps.
1. On the second sheet, create the following named ranges.
Name |
Range Address |
Food |
A1:A3 |
Pizza |
B1:B4 |
Pancakes |
C1:C2 |
Chinese |
D1:D3 |
2. On the first sheet, select cell B1.
3. On the Data tab, in the Data Tools group, click Data Validation.
The 'Data Validation' dialog box appears.
4. In the Allow box, click List.
5. Click in the Source box and type =Food.
6. Click OK.
Result:
7. Next, select cell E1.
8. In the Allow box, click List.
9. Click in the Source box and type =INDIRECT($B$1).
10. Click OK.
Result:
Explanation: the INDIRECT function returns the reference specified by a text string.
For example, the user selects Chinese from the first drop-down list.=INDIRECT($B$1) returns the Chinese reference.
As a result, the second drop-down lists contains the Chinese items.
Cm to inches
1 cm = 0.3937 inch and 1 inch = 2.54 cm.
Use a simple formula, the CONVERT function or download our free unit converter to convert from cm to inches or vice versa (see below).
1. First, to convert from centimeters to inches, divide by 2.54. The simple formula below does the trick.
2. To convert from inches to centimeters, multiply by 2.54.
3. You can also use the CONVERT function in Excel to convert from centimeters to inches.
Note: the CONVERT function has three arguments (number, from_unit and to_unit).
4. You can also use the CONVERT function in Excel to convert from inches to centimeters.
Download our free unit converter to quickly and easily convert from cm to inches (or vice versa).
5. Select Length from the category drop-down list.
Explanation: because you selected Length from this drop-down list, the dependent drop-down lists in cell B5 and cell E5 now contain length units.
6. Enter a number and select the correct length units.
Explanation: the unit converter uses worksheet change events to automatically execute VBA code when you change a cell (B2, B4, B5, E4 or E5).
The VBA code uses the CONVERT function to convert from one measurement unit to another and uses the VLOOKUP function to lookup the correct unit abbreviations (cm, in, yd, ft, etc.) stored on the second worksheet.
Kg to lbs
1 kg = 2.20462 lbs (pounds) and 1 lb (pound) = 0.45359 kg.
Use a simple formula, the CONVERT function or download our free unit converter to convert from kg to lbs or vice versa (see below).
1. First, to convert from kg to lbs, multiply by 2.20462. The simple formula below does the trick.
2. To convert from lbs to kg, divide by 2.20462.
3. You can also use the CONVERT function in Excel to convert from kg to lbs.
Note: the CONVERT function has three arguments (number, from_unit and to_unit).
The unit abbreviation lbm stands for pound mass.
4. You can also use the CONVERT function in Excel to convert from lbs to kg.
Download our free unit converter to quickly and easily convert from kg to lbs (or vice versa).
5. Select Mass from the category drop-down list.
Explanation: because you selected Mass from this drop-down list, the dependent drop-down lists in cell B5 and cell E5 now contain mass units.
6. Enter a number and select the correct mass units.
Explanation: the unit converter uses worksheet change events to automatically execute VBA code when you change a cell (B2, B4, B5, E4 or E5).
The VBA code uses the CONVERT function to convert from one measurement unit to another and uses the VLOOKUP function to lookup the correct unit abbreviations (kg, g, lbm, ozm, etc.) stored on the second worksheet.
Function Keys
F1 | F2 | F3 | F4 | F5 | F6 | F7 | F8 | F9 | F10 | F11 | F12
Function keys in Excel allow you to do things with your keyboard instead of your mouse to increase your speed.
F1
Opens Excel Help.
F2
Moves the insertion point to the end of the contents of the active cell.
For example, select cell B6 below and press F2.
Note: turn off Allow editing directly in cells (File, Options, Advanced, Editing Options) and pressing F2 will move the insertion point to the formula bar.
F3
Displays the Paste Name dialog box.
For example, select cell E2 below, type =SUM(, press F3 and select a name.
Note: of course, first create at least one named range.
F4
Cycles through all 4 types of cell references (absolute, mixed reference (2x) and relative).
For example, select cell B5 below, click in the formula bar, move the insertion point in or to the right of G2, and press F4.
Note: if you are not editing a cell, F4 repeats the last action, if possible.
F5
Displays the Go To dialog box.
For example, to select cell C15, in the Reference box, type C15, and click OK.
Note: you can also select named ranges, or click Special to quickly select all cells with formulas, comments, conditional formatting, constants, data validation, etc.
F6
Moves to the next pane in a worksheet that has been split.
F7
Displays the Spelling dialog box (the same as clicking Spelling on the Review tab).
F8
Turns on/off Extend mode.
If Extend mode is turned on, select cell A1 and press → and ↓ a few times.
Note: if Extend mode is turned off, hold down SHIFT and press → and ↓ a few times.
F9
Calculates all open workbooks.
By default, any time you change a value, Excel automatically calculates the workbook.
Turn on Manual calculation (on the Formulas tab, in the Calculation group, click Calculations Options, Manual) and change the value in cell A1 from 5 to 6.
Press F9.
Note: if you are editing a cell, F9 replaces a formula with its own result.
F10
Shows the key tips (the same as pressing ALT).
Key Tips allow you to quickly perform any task available on the Ribbon without using the mouse.
F11
Creates a chart sheet of a selected range.
F12
Brings up the Save As dialog box.
Note: to change the default file location, on the File tab, click Options, Save.
Insert Row
Insert Row | Insert Rows | Insert Cells
To quickly insert a row in Excel, select a row and use the shortcut CTRL SHIFT +.
To quickly insert multiple rows, select multiple rows and use the same shortcut.
Insert Row
To insert a row in Excel, execute the following steps.
1. Select a row.
2. Right click, and then click Insert.
Result:
Note: instead of executing step 2, use the shortcut CTRL SHIFT +.
Insert Rows
To quickly insert multiple rows in Excel, execute the following steps.
1. Select multiple rows by clicking and dragging over the row headers.
2. Press CTRL SHIFT +.
Result:
Insert Cells
Excel displays the Insert Cells dialog box if you don't select a row or multiple rows before using the shortcut CTRL SHIFT +.
1. Select cell A3.
2. Press CTRL SHIFT +.
3a.
Excel automatically selects "Shift cells down".
Click OK.
Result:
3b.
To insert a row, select "Entire row" and click OK.
Result:
Save As
Save As | Save
Use the shortcut F12 to display the Save As dialog box in Excel.
Press CTRL + s to save an existing workbook.
It's good practice to periodically save while you are working on your Excel file.
Save As
To display the Save As dialog box, execute the following steps.
1. On the File tab, click Save As.
2. Click Browse.
Result:
Note: instead of executing step 1 and step 2, simply use the shortcut F12.
3. Choose a file location.
4. Enter a file name.
5. Click Save.
Save
Again, it's good practice to periodically save while you are working on your Excel file.
Saving often can prevent your work from being lost.
1. Edit an existing workbook.
2. Simply press CTRL + s to save the changes.
3. Press F12 (Excel opens the Save As dialog box again) to create a copy of this workbook while keeping the original.
Delete Row
Delete Row | Delete Rows | Delete Cells
To quickly delete a row in Excel, select a row and use the shortcut CTRL - (minus sign).
To quickly delete multiple rows, select multiple rows and use the same shortcut.
Delete Row
To delete a row in Excel, execute the following steps.
1. Select a row.
2. Right click, and then click Delete.
Result:
Note: instead of executing step 2, use the shortcut CTRL - (minus sign).
Delete Rows
To quickly delete multiple rows in Excel, execute the following steps.
1. Select multiple rows by clicking and dragging over the row headers.
2. Press CTRL - (minus sign).
Result:
Delete Cells
Excel displays the Delete Cells dialog box if you don't select a row or multiple rows before using the shortcut CTRL - (minus sign).
1. Select cell A3.
2. Press CTRL - (minus sign).
3a.
Excel automatically selects "Shift cells up".
Click OK.
Result:
3b.
To delete a row, select "Entire row" and click OK.
Result:
Formula to Value
To quickly convert a formula to a value in Excel or to convert multiple formulas to values, execute the following steps.
1. Select a cell with a formula.
2. Press F2 to switch to editing mode.
3. Press F9 to replace this formula with its result.
Don't forget to press Enter.
To copy a formula result to another cell, simply paste as values.
Use the following magic trick to quickly convert multiple formulas to values in Excel.
4. Select a range of cells containing formulas.
Hover over the right border of the selection.
A four-sided arrow appears.
5. Click and hold the right mouse button.
Drag the box to the right.
6. Keep holding down the right mouse button.
Drag the box back to its original position.
7. Release the right mouse button.
From the popup-menu, click Copy Here as Values Only.
Result:
Note: cell D1 contains the value 30 (not a formula), cell D2 contains the value 60 (not a formula), etc.
Scroll Lock
What is Scroll Lock? | Turn off Scroll Lock
When Scroll Lock is turned on, you can use the arrow keys to scroll through the worksheet without changing the active cell.
Excel displays Scroll Lock in the status bar.
What is Scroll Lock?
First, when Scroll Lock is turned off, you can use the arrow keys to change the active cell.
1. For example, select cell A1.
2. Press ↓ twice.
When Scroll Lock is turned on, you can use the arrow keys to scroll through the worksheet without changing the active cell.
3. Select cell A1 again.
4. Again, press ↓ twice.
Note: press CTRL + Backspace to scroll back to the active cell.
Turn off Scroll Lock
To turn off scroll lock, execute the following step(s).
1. Press the Scroll Lock key (Scroll Lock or ScrLk) on your keyboard.
Done.
If your keyboard does not have a Scroll Lock key, launch the on-screen keyboard.
2. Click Start > Settings > Ease of Access > Keyboard > Use the On-Screen Keyboard (or press the Windows logo key + CTRL + O).
3. Click the ScrLk button.
Note: to turn on scroll lock, simply repeat step 1 or step 2 and 3.
When Scroll Lock is turned on, Excel displays Scroll Lock in the status bar (only if the status bar is customized to display the Scroll Lock status).
4. Right click the status bar to display or to hide the Scroll Lock status.
Bullet Points
This page illustrates three ways to insert bullet points in Excel.
You can use a keyboard shortcut, insert a symbol or create a custom number format.
If you have a number pad on the right side of your keyboard, execute step 1 or step 2.
1. To insert a filled round bullet point, press Alt + Numpad 7.
2. To insert a hollow round bullet point, press Alt + Numpad 9.
If you don't have a number pad on the right side of your keyboard, execute step 3 and step 4.
3. On the Insert tab, in the Symbols group, click Symbol.
4. Select a font from the drop-down list, type 2022 in the Character code box and click Insert.
Result.
5. To insert multiple bullet points in a single cell, press Alt + Enter to start a new line in an Excel cell.
Create a custom number format and inserting a bulleted list in Excel will be a piece of cake.
6. Select the range A1:A3.
7. Right click, and then click Format Cells.
8. Select Custom.
9. In the Type box, press Alt + Numpad 7 to insert a bullet point (or copy/paste a bullet point), enter a space and type @
10. Click OK.
11. You can now create a bulleted list by simply typing the list items.
Excel automatically adds the bullet points!
Note: use the Format Painter to quickly copy the bullet point format to other cells.
Line Break
Insert a line break in Excel by pressing Alt + Enter.
When concatenating strings, use CHAR(10) to insert a line break.
To insert a line break, execute the following steps.
1. For example, enter a long text string in cell A1.
2. Double click cell A1.
3. Place your cursor at the location where you want the line to break.
4. Press Alt + Enter.
5. Click on the right border of the column A header and drag the separator to increase the column width.
6. Double click the bottom border of the row 1 header to automatically adjust the row height.
Result:
Note: to remove a line break, double click a cell, place your cursor at the beginning of the line and press Backspace.
7. When concatenating strings, use CHAR(10) to insert a line break.
For example, the address below contains two line breaks.Use the & operator to join strings.
Note: don't forget to enable text wrapping.
8. To quickly remove multiple line breaks in Excel, use the SUBSTITUTE function as shown below.
Explanation: this formula replaces all line breaks with a comma and a space.
Show Formulas
By default, Excel shows the results of formulas.
To show the formulas instead of their results, press CTRL + ` (you can find this key above the tab key).
1. When you select a cell, Excel shows the formula of the cell in the formula bar.
2. To display all formulas, in all cells, press CTRL + ` (you can find this key above the tab key).
3. Press ↓ twice.
Note: as you can see, Excel highlights all cells that are referenced by a formula.
4. To hide all formulas, press CTRL + ` again.
5. If you can't find the grave accent (`) on your keyboard, on the Formulas tab, in the Formula Auditing group, click Show Formulas.
6. To hide all formulas, click Show Formulas again.
7. You can also use the FORMULATEXT function in Excel to display formulas in adjacent cells.
Tip: visit our page about formula auditing in Excel to learn more about tracing precedents, tracing dependents, error checking, etc.
Paste Special
Paste Formulas | Paste Values | Paste Formatting | Transpose
Use the shortcut Ctrl + Alt + V to display the Paste Special dialog box in Excel.
Next, press an underlined letter to paste formulas, values, formatting, etc.
Paste Formulas
To paste formulas only, execute the following steps.
1. Select cell B5 below and press Ctrl + C (copy shortcut).
2. To select cell F5, press → four times and press Ctrl + Alt + V (paste special shortcut).
The Paste Special dialog box appears.
3. Press F (Formulas).
4. Press Enter.
Result - all without using the mouse!
Conclusion: use the shortcut Ctrl + Alt + V + F to paste formulas only.
Visit our page about copying formulas for more tips and tricks.
Paste Values
To paste values only, execute the following steps.
1. Select cell B5 below and press Ctrl + C (copy shortcut).
2. To select cell D5, press → two times and press Ctrl + Alt + V (paste special shortcut).
The Paste Special dialog box appears.
3. Press V (Values).
4. Press Enter.
Result - all without using the mouse!
Conclusion: use the shortcut Ctrl + Alt + V + V to paste values only.
Use F2 and F9 to quickly replace a formula with its result.
Paste Formatting
To paste formatting only, execute the following steps.
1. Select cell B5 below and press Ctrl + C (copy shortcut).
2. To select cell D5, press → two times and press Ctrl + Alt + V (paste special shortcut).
The Paste Special dialog box appears.
3. Press T (Formats).
4. Press Enter.
Result - all without using the mouse!
Conclusion: use the shortcut Ctrl + Alt + V + T to paste formatting only.
You can also use the format painter to quickly copy and paste formatting.
Transpose
To convert a horizontal range to a vertical range, or vice versa, execute the following steps.
1. Select the range A1:C1 below and press Ctrl + C (copy shortcut).
Tip: to select this range without using the mouse, select cell A1, hold down Shift and press → two times.
2. Select cell E2 (using your arrow keys) and press Ctrl + Alt + V (paste special shortcut).
The Paste Special dialog box appears.
3. Press E (Transpose).
4. Press Enter.
Result - all without using the mouse!
Conclusion: use the shortcut Ctrl + Alt + V + E to transpose data.
Follow the link to learn more about this topic!
Workbook Views
Normal | Page Break Preview | Page Layout
Excel offers three different workbook views: Normal, Page Layout and Page Break Preview.
Normal
At any time, you can switch back to Normal view.
1. On the View tab, in the Workbook Views group, click Normal.
Result:
Note: if you switch to another view and return to Normal view, Excel displays page breaks.
Close and reopen the Excel file to hide these page breaks.
To always hide page breaks for this worksheet, click File, Options, Advanced, scroll down to Display options for this worksheet and uncheck Show page breaks.
Page Break Preview
Page Break Preview gives you a nice overview of where pages break when you print the document.
Use this view to easily click and drag page breaks.
1. On the View tab, in the Workbook Views group, click Page Break Preview.
Result:
Note: click and drag the page breaks to fit all the information on one page.
Be careful, Excel doesn't warn you when your printout becomes unreadable.
By default, Excel prints down, then over.
In other words, it prints all the rows for the first set of columns.
Next, it prints all the rows for the next set of columns, etc.
(take a look at the page numbers in the picture above to get the idea).
To switch to Print over, then down, click File, Print, Page Setup, on the Sheet tab, under Page order, click Over, then down.
Page Layout
Use Page Layout view to see where pages begin and end, and to add headers and footers.
1. On the View tab, in the Workbook Views group, click Page Layout.
Result:
Page Breaks
Insert a page break in Excel to specify where a new page will begin in the printed copy.
To insert a horizontal page break, execute the following steps.
1. Select the first row of the new page.
2. On the Page Layout tab, in the Page Setup group, click Breaks.
3. Click Insert Page Break.
Excel displays a solid line (manual page break) to show you where the new page begins.
Dashed lines are page breaks inserted automatically by Excel.
Note: in a similar way, you can select a column to insert a vertical page break.
4. On the File tab, click Print for a print preview.
Note: to remove a horizontal page break, select a cell below the page break that you want to remove and click Breaks, Remove Page Break.
To remove all manual page breaks, click Breaks, Reset All Page Breaks.
You cannot remove automatic page breaks.
Headers and Footers
This example teaches you how to add information to the header (top of each printed page) or footer (bottom of each printed page) in Excel.
1. On the View tab, in the Workbook Views group, click Page Layout, to switch to Page Layout view.
2. Click Add header.
3. On the Header & Footer tab, in the Header & Footer Elements group, click Current Date to add the current date (or add the current time, file name, sheet name, etc).
Result:
Note: Excel uses codes in order to automatically update the header or footer as you change the workbook.
4. You can also add information to the left and right part of the header.
For example, click the left part to add the name of your company.
5. Click somewhere else on the sheet to see the header.
6. On the Header & Footer tab, in the Options group, you can add a different first page header/footer and a different header/footer for odd and even pages.
7. On the View tab, in the Workbook Views group, click Normal, to switch back to Normal view.
Page Numbers
This example teaches you how to insert page numbers in Excel.
1. On the View tab, in the Workbook Views group, click Page Layout, to switch to Page Layout view.
2. Click Add footer.
3. On the Header & Footer tab, in the Header & Footer Elements group, click Page Number to add the page number.
4. Type " of "
5. On the Header & Footer tab, in the Header & Footer Elements group, click Number of Pages to add the number of pages.
Result:
Note: Excel uses codes in order to automatically update the header or footer as you change the workbook.
6. Click somewhere else on the sheet to see the footer.
7. On the Header & Footer tab, in the Options group, you can add a different first page header/footer and a different header/footer for odd and even pages.
8. On the View tab, in the Workbook Views group, click Normal, to switch back to Normal view.
Print Titles
You can specify rows and columns in Excel that will be printed on each printed page.
This can make your printed copy easier to read.
To print titles, execute the following steps.
1. On the Page Layout tab, in the Page Setup group, click Print Titles.
The Page Setup dialog box appears.
2. To repeat row 1 at the top of each printed page, click in the corresponding box and select row 1.
3. Click OK.
Note: in a similar way, you can repeat columns at the left of each printed page.
4. On the File tab, click Print for a print preview.
The labels (LastName, Sales, Country and Quarter) appear on page 1 and page 2.
Center on Page
To center a range of cells on a printed page in Excel automatically, execute the following steps.
1. On the File tab, click Print.
2. Click 'Custom Margins' from the Margins drop-down list.
3. Next, check horizontally and vertically.
4. Click OK.
Print Gridlines and Headings
Print gridlines (the horizontal and vertical lines on your worksheet) and row/column headers (1, 2, 3 etc.
and A, B, C etc.) to make your printed copy easier to read.
To print gridlines and headings in Excel, execute the following steps.
1. On the Page Layout tab, in the Sheet Options group, check Print under Gridlines and check Print under Headings.
2. On the File tab, click Print for a print preview.
Print Area
If you set a print area in Excel, only that area will be printed.
The print area is saved when you save the workbook.
To set a print area, execute the following steps.
1. Select a range of cells.
2. On the Page Layout tab, in the Page Setup group, click Print Area.
3. Click Set Print Area.
4. Save, close and reopen the Excel file.
5. On the File tab, click Print.
Result.
See the print preview below.
Only the print area will be printed.
Note: use the Name Manager to edit and delete print areas.
On the Formulas tab, in the Defined Names group, click Name Manager.
Embed
Embed an Excel worksheet in a Word document and work with Excel in Word.
You can also embed files in Excel.
1. Select the Excel data.
2. Right click, and then click Copy (or press CTRL + c).
3. Open a Word document.
4. In word, on the Home tab, in the Clipboard group, click Paste.
5. Click Paste Special.
The Paste Special dialog box appears.
6. Click Paste, Microsoft Excel Worksheet Object.
7. Click OK.
8. Double click the object to work with it.
For example, format the table and insert a SUM function.
Note: the embedded object is part of the Word file.
There's no link to the original Excel file.
To create a link, at step 6, click Paste Link, Microsoft Excel Worksheet Object.
Now, if you double click the object, Excel opens the Excel file.
To embed a file in Excel, on the Insert tab, in the Text group, click Object.
PDF
This page teaches you how to convert an Excel file to a PDF file.
1. Open a workbook.
2. On the File tab, click Save As.
3. Click Browse.
4. Select PDF from the drop-down list.
5. Click Options.
6. You can publish a selection, active sheet or entire workbook.
7. Click OK and then Click Save.
Share Workbooks
Highlight Changes | Accept/Reject Changes
If you share a workbook in Excel 2016 or older versions, you can work with other people on the same workbook at the same time.
The workbook should be saved to a network location where other people can open it.
You can keep track of the changes other people make and accept or reject those changes.
To share a workbook, execute the following steps.
1. Open a workbook.
2. On the Review tab, in the Changes group, click Share Workbook.
The Share Workbook dialog box appears.
3. On the Editing tab, click the check box and click OK.
Excel saves the workbook.
You can now work with other people on the same workbook at the same time.
The screen above shows you who has the workbook open.
Highlight Changes
You can highlight the changes on screen other users has made.
1. On the Review tab, in the Changes group, click Track Changes.
2. Click Highlight Changes.
The Highlight Changes dialog box appears.
3. Click OK.
Excel highlights the changes on screen.
Apparently, Aiden has changed the Sales of Smith from $16,753.00 to $26,753.00.
Accept/Reject Changes
You can now accept or reject this change.
1. On the Review tab, in the Changes group, click Track Changes.
2. Click Accept/Reject Changes.
3. Click OK.
4. Click Accept to accept the change or Reject to reject the change.
Note: not all features are available in a shared workbook.
OneDrive
Save your Excel files to your OneDrive location and access your files from any computer or share it with other people.
1. Open a workbook.
2. On the File tab, click Save As.
3. Click OneDrive, Sign In.
Note: if you don't have a Microsoft account, click on Sign up to create an account.
If you're using Outlook or Xbox live, you already have a Microsoft account.
4. Type your email address and click Next.
5. Enter your password and click Sign in.
6. Select a folder.
7. Click Save.
You can now edit this Excel file with Excel Online from anywhere without having Excel installed on your computer.
To share this Excel file with other people, execute the following steps.
8. Go to onedrive.live.com and sign in with your Microsoft account.
9. Click the folder selected at step 6.
10. Right click the Excel file and click Share.
11. Enter an e-mail address, add a message and click Send.
The recipient receives a link and can edit the Excel file.
You can now use Excel Online to work with the recipient on this workbook at the same time.
Online
You can edit Excel files with Excel Online from anywhere without having Excel installed on your computer.
1. First, save an Excel file to your OneDrive location.
2. Go to onedrive.live.com and sign in with your Microsoft account.
3. Click an Excel file.
Excel Online opens the workbook in the browser.
4. Edit your Excel file.
Note: there is no need to save your Excel file since all changes are being saved automatically.
Not all features are available in Excel Online.
Let's take a look at one cool new feature that is only available when you save an Excel file to your OneDrive location.
5. Go to onedrive.live.com.
6. Upload a data set to your OneDrive location.
7. Open the Excel file in Excel Online.
8. On the View tab, click New Sheet View.
Excel changes the color of the column and row headers (see picture below) to remind you that a view is active.
9. Use Excel Online to sort and filter this data set.
10. To save this sheet view, simply type a new name and press Enter.
11. Now you can quickly switch between two different sheet views (Mia and Default).
Conclusion: if you're sharing this Excel file with multiple people, everyone can save his/her own sheet view and everyone can see each other's view.
Any changes to this data set will automatically be saved to all sheet views.
That's pretty cool.
Import Access Data
This example teaches you how to import data from a Microsoft Access database.
In Excel, when you import data, you make a permanent connection that can be refreshed.
1. On the Data tab, in the Get & Transform Data group, click Get Data.
2. Click From Database, From Microsoft Access Database.
3. Select the Access file.
4. Click Import.
5. Select a table on the left side of the Navigator window and click Load.
Result.
Your database records in Excel.
6. When your Access data changes, you can easily refresh the data in Excel.
First, select a cell inside the table.
Next, on the Table Design tab, in the External Table Data group, click Refresh.
Microsoft Query
This example teaches you how to import data from a Microsoft Access database by using the Microsoft Query Wizard.
With Microsoft Query, you can select the columns of data that you want and import only that data into Excel.
1. On the Data tab, in the Get & Transform Data group, click Get Data.
2. Click From Other Sources, From Microsoft Query.
The 'Choose Data Source" dialog box appears.
3. Select MS Access Database* and check 'Use the Query Wizard to create/edit queries'.
4. Click OK.
5. Select the database and click OK.
This Access database consists of multiple tables.
You can select the table and columns you want to include in your query.
6. Select Customers and click the > symbol.
7. Click Next.
To only import a specified set of records, filter the data.
8. Click City from the 'Column to filter' list and only include rows where City equals New York.
9. Click Next.
You can sort your data if you want (we don't do it here).
10. Click Next.
11. Click Finish to return the data to Microsoft Excel.
12. Select how you want to view this data, where you want to put it, and click OK.
Result:
13. When your Access data changes, you can easily refresh the data in Excel.
First, select a cell inside the table.
Next, on the Table Design tab, in the External Table Data group, click Refresh.
Import/Export Text Files
Import | Export
This article describes how to import or export text files.
Text files can be comma separated (.csv) or tab separated (.txt)
Import
To import text files, execute the following steps.
1. On the File tab, click Open.
2. Click Browse.
3. Select Text Files from the drop-down list.
4a.
To import a .csv file, select the Microsoft Excel Comma Separated Values File and click Open.
That's all.
4b.
To import a .txt file, select the Text Document and click Open.
Excel launches the Text Import Wizard.
5. Choose Delimited and click Next.
6. Clear all the check boxes under Delimiters except for the Tab check box and click Next.
7. Click Finish.
Result:
Export
To export text files, execute the following steps.
1. Open an Excel file.
2. On the File tab, click Save As.
3. Click Browse.
4. Select Text (Tab delimited) or CSV (Comma delimited) from the drop-down list.
5. Click Save.
Result.
A .csv file (comma separated) or a .txt file (tab separated).
XML
Convert your XML file to an Excel file, or vice versa.
This enables you to exchange data between different applications.
From XML to Excel is really easy.
Simply execute the following steps.
1. Open a blank workbook.
2. Turn on the Developer tab.
3. On the Developer tab, in the XML group, click Import.
4. Select the XML file and click Import.
5. Click OK.
Result:
To convert an Excel file to an XML file, simply execute the following steps.
First, we will create a schema based on XML source data.
The schema defines the structure of the XML file.
We have to do this outside Excel.
1. For example, open Notepad and add the following lines.
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<data-set xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<record>
<LastName>Smith</LastName>
<Sales>16753</Sales>
<Country>UK</Country>
<Quarter>Qtr 3</Quarter>
</record>
<record>
<LastName>Johnson</LastName>
<Sales>14808</Sales>
<Country>USA</Country>
<Quarter>Qtr 4</Quarter>
</record>
</data-set>
Note: the tags refer to the column names, but you can give them any name you want! For example, instead of LastName use Name.
2. Save the file as schema.xml.
3. Open data-set.xlsx.
4. On the Developer tab, in the XML group, click Source to open the XML Source task pane.
5. To add an XML map, click XML Maps.
The XML Maps dialog box appears.
6. Click Add.
7. Select schema.xml and click OK twice.
8. Now simply drag (map) the 4 elements from the tree onto the worksheet (row 1).
9. On the Developer tab, in the XML group, click Export.
10. Save your file as data-set.xml and press Enter.
Result:
That saves quite a lot of time!
Protect Workbook
This example teaches you how to protect the workbook structure in Excel.
If you protect the workbook structure, users cannot insert, delete, rename, move, copy, hide or unhide worksheets anymore.
1. Open a workbook.
2. On the Review tab, in the Protect group, click Protect Workbook.
3. Check Structure, enter a password and click OK.
Note: The Windows option is not available in Excel 2013 and later versions.
4. Reenter the password and click on OK.
Users cannot insert, delete, rename, move, copy, hide or unhide worksheets anymore.
Note: to unprotect the workbook, click Protect Workbook and enter the password.
The password for the downloadable Excel file is "easy".
Protect Sheet
When you share an Excel file with other users, you may want to protect a worksheet to help prevent it from being changed.
1. Right click a worksheet tab.
2. Click Protect Sheet.
3. Enter a password.
4. Check the actions you allow the users of your worksheet to perform.
5. Click OK.
Note: if you don't check any action, users can only view the Excel file!
6. Confirm the password and click OK.
Your worksheet is protected now.
To unprotect a worksheet, right click on the worksheet tab and click Unprotect Sheet.
The password for the downloadable Excel file is "easy".
Lock Cells
Lock All Cells | Lock Specific Cells | Lock Formula Cells
You can lock cells in Excel if you want to protect cells from being edited.
Lock All Cells
By default, all cells are locked.
However, locking cells has no effect until you protect the worksheet.
1. Select all cells.
2. Right click, and then click Format Cells (or press CTRL + 1).
3. On the Protection tab, you can verify that all cells are locked by default.
4. Click OK or Cancel.
5. Protect the sheet.
All cells are locked now.
To unprotect a worksheet, right click on the worksheet tab and click Unprotect Sheet.
The password for the downloadable Excel file is "easy".
Lock Specific Cells
To lock specific cells in Excel, first unlock all cells.
Next, lock specific cells.
Finally, protect the sheet.
1. Select all cells.
2. Right click, and then click Format Cells (or press CTRL + 1).
3. On the Protection tab, uncheck the Locked check box and click OK.
4. For example, select cell A1 and cell A2.
5. Right click, and then click Format Cells (or press CTRL + 1).
6. On the Protection tab, check the Locked check box and click OK.
Again, locking cells has no effect until you protect the worksheet.
7. Protect the sheet.
Cell A1 and cell A2 are locked now.
To edit these cells, you have to unprotect the sheet.
The password for the downloadable Excel file is "easy".
You can still edit all other cells.
Lock Formula Cells
To lock all cells that contain formulas, first unlock all cells.
Next, lock all formula cells.
Finally, protect the sheet.
1. Select all cells.
2. Right click, and then click Format Cells (or press CTRL + 1).
3. On the Protection tab, uncheck the Locked check box and click OK.
4. On the Home tab, in the Editing group, click Find & Select.
5. Click Go To Special.
6. Select Formulas and click OK.
Excel selects all formula cells.
7. Press CTRL + 1.
8. On the Protection tab, check the Locked check box and click OK.
Note: if you also check the Hidden check box, users cannot see the formula in the formula bar when they select cell A2, B2, C2 or D2.
Again, locking cells has no effect until you protect the worksheet.
9. Protect the sheet.
All formula cells are locked now.
To edit these cells, you have to unprotect the sheet.
The password for the downloadable Excel file is "easy".
You can still edit all other cells.
Read-only Workbook
This example shows you how to make your Excel workbook read-only.
Users without a password can still save changes by creating a new copy of the workbook.
1. Open a workbook.
2. On the File tab, click Save As.
3. Click Browse.
4. Click on the Tools button and click General Options.
5. In the Password to modify box, enter a password and click OK.
Note: if you only want to recommend users to open the Excel file as read-only, without protecting it, don't enter a password and check Read-only recommended.
6. Reenter the password and click on OK.
Note: this feature does not encrypt your Excel file.
Malicious users can edit the file and remove the password.
7. Enter a file name and click Save.
Your workbook is read-only now.
The password for the downloadable Excel file is "easy".
8. Excel displays the following message box when you open a read-only Excel file.
Enter the password or open read only.
Remember, users without a password can still save changes by creating a new copy of the workbook.
For a better protection, protect a sheet.Mark as Final
Mark a workbook as final in Excel to indicate that this is the final version of your workbook.
Only use this feature to discourage editing.
Users can still edit the workbook.
1. Open a workbook.
2. On the File tab, click Info.
3. Click Protect Workbook, Mark as Final.
4. Click OK.
Result.
Note: users can still edit the workbook by clicking on Edit Anyway.
Also notice the Marked as Final icon in the status bar.
COUNTIF
Numeric Criteria | Text Tricks | Count Booleans | Count Errors | And Criteria | Or Criteria | More about Countif | Count Magic
The powerful COUNTIF function in Excel counts cells based on one criteria.
This page contains many easy to follow COUNTIF examples.
Numeric Criteria
Use the COUNTIF function in Excel to count cells that are equal to a value, count cells that are greater than or equal to a value, etc.
1. The COUNTIF function below counts the number of cells that are equal to 20.
2. The following COUNTIF function gives the exact same result.
3. The COUNTIF function below counts the number of cells that are greater than or equal to 10.
4. The following COUNTIF function gives the exact same result.
Explanation: the & operator joins the 'greater than or equal to' symbol and the value in cell C1.
5. The COUNTIF function below counts the number of cells that are not equal to 7.
6. The COUNTIF functions below count the number of cells that are equal to 3 or 7.
Text Tricks
Use the COUNTIF function in Excel and a few tricks to count cells that contain specific text.
Always enclose text in double quotation marks.
1. The COUNTIF function below counts the number of cells that contain exactly star.
2. The COUNTIF function below counts the number of cells that contain exactly star + 1 character.
A question mark (?) matches exactly one character.
3. The COUNTIF function below counts the number of cells that contain exactly star + a series of zero or more characters.
An asterisk (*) matches a series of zero or more characters.
4. The COUNTIF function below counts the number of cells that contain star in any way.
5. The COUNTIF function below counts the number of cells that contain text.
Count Booleans
Use the COUNTIF function in Excel to count Boolean values (TRUE or FALSE).
1. The COUNTIF function below counts the number of cells that contain the Boolean TRUE.
2. The COUNTIF function below counts the number of cells that contain the Boolean FALSE.
Count Errors
Use the COUNTIF function in Excel to count specific errors.
1. The COUNTIF function below counts the number of cells that contain the #NAME? error.
2. The array formula below counts the total number of errors in a range of cells.
Note: finish an array formula by pressing CTRL + SHIFT + ENTER.
Excel adds the curly braces {}.
In Excel 365 or Excel 2021, finish by simply pressing Enter.
You won't see curly braces.
Visit our page about Counting Errors for detailed instructions on how to create this array formula.
And Criteria
Counting with And criteria in Excel is easy.
The COUNTIFS function (with the letter S at the end) in Excel counts cells based on two or more criteria.
1. For example, to count the number of rows that contain Google and Stanford, simply use the COUNTIFS function.
Or Criteria
Counting with Or criteria in Excel can be tricky.
1. The COUNTIF functions below count the number of cells that contain Google or Facebook (one column).
No rocket science so far.
2. However, if you want to count the number of rows that contain Google or Stanford (two columns), you cannot simply use the COUNTIF function twice (see the picture below).
Note: rows that contain Google and Stanford are counted twice, but they should only be counted once.
4 is the answer we are looking for.
3. The array formula below does the trick.
Note: finish an array formula by pressing CTRL + SHIFT + ENTER.
Excel adds the curly braces {}.
In Excel 365 or Excel 2021, finish by simply pressing Enter.
You won't see curly braces.
Visit our page about Counting with Or Criteria for instructions on how to create this array formula.
More about Countif
The COUNTIF function is a great function.
Let's take a look at a few more cool examples.
1. The COUNTIF function below uses a named range.
The named range Ages refers to the range A1:A6.
2. The COUNTIF function below counts the number of cells that are less than the average of the ages (32.2).
3. To count cells between two numbers, use the COUNTIFS function (with the letter S at the end).
4. Use the COUNTIF function to count how many times each value occurs in the named range Ages.
Note: cell B2 contains the formula =COUNTIF(Ages,A2), cell B3 =COUNTIF(Ages,A3), etc.
5. Add the IF function to find the duplicates.
Tip: use COUNTIF and conditional formatting to find and highlight duplicates in Excel.
Count Magic
The COUNTIF function can't count how many times a specific word occurs in a cell or range of cells.
All we need is a little magic!
1. The formula below counts how many times the word "dog" occurs in cell A1.
2. The formula below counts how many times the word "dog" occurs in the range A1:A2.
Note: visit our page about counting words to learn more about these formulas.
Count Blank/Nonblank Cells
This example shows you how to count blank and nonblank cells in Excel.
1. The COUNTBLANK function below counts the number of blank cells in the range A1:A7.
2. The COUNTA function below counts the number of nonblank cells in the range A1:A7. COUNTA stands for count all.
3. The COUNTIFS function below counts the number of blank cells in the range B1:B7 with one additional criteria (blue).
Explanation: the COUNTIFS function (with the letter S at the end) in Excel counts cells based on two or more criteria.
Use an empty string (two double quotes with nothing in between) to find blank cells.
4. The COUNTIFS function below counts the number of nonblank cells in the range B1:B7 with one additional criteria (pink).
Count Characters
Use the LEN function to count characters in Excel.
Use LEN and SUBSTITUTE to count specific characters in Excel.
1. The LEN function in Excel counts the number of characters in a cell.
Explanation: the LEN function counts 2 numbers, 1 space and 6 letters.
2. Use SUM and LEN to count the number of characters in a range of cells.
Note: as you can imagine, this formula can get quite long.
3. The array formula below counts the number of characters in a range of cells.
Note: finish an array formula by pressing CTRL + SHIFT + ENTER.
Excel adds the curly braces {}.
In Excel 365 or Excel 2021, finish by simply pressing Enter.
You won't see curly braces.
The array constant {9;4;6;5} is used as an argument for the SUM function, giving a result of 24.
4. Use LEN and SUBSTITUTE to count how many times a specific character (in this example, the character a) occurs in a cell.
Explanation: the SUBSTITUTE function replaces the character a (second argument) with an empty string (third argument).
LEN(SUBSTITUTE(A1,"a","")) equals 8 (the length of the string without the character a).
If we subtract this number from 9 (total number of characters in cell A1), we get the number of occurrences of the character a in cell A1.
5. The array formula below counts how many times a specific character (in this example, the character a) occurs in a range of cells.
Explanation: the array constant {1;1;2;1} is used as an argument for the SUM function, giving a result of 5. The SUBSTITUTE function is case-sensitive.
The A in Alaska is not counted.
6. The array formula below counts both lower and upper case occurrences of a specific character (in this example, the character a).
Explanation: The LOWER function converts all letters to lowercase first.
Not Equal To
In Excel, <> means not equal to.
The <> operator in Excel checks if two values are not equal to each other.
Let's take a look at a few examples.
1. The formula in cell C1 below returns TRUE because the text value in cell A1 is not equal to the text value in cell B1.
2. The formula in cell C1 below returns FALSE because the value in cell A1 is equal to the value in cell B1.
3. The IF function below calculates the progress between a start and end value if the end value is not equal to an empty string (two double quotes with nothing in between), else it displays an empty string (see row 5).
Note: visit our page about the IF function for more information about this Excel function.
4. The COUNTIF function below counts the number of cells in the range A1:A5 that are not equal to "red".
Note: visit our page about the COUNTIF function for more information about this Excel function.
5. The COUNTIF function below produces the exact same result.
The & operator joins the 'not equal to' operator and the text value in cell C1.
6. The COUNTIFS function below counts the number of cells in the range A1:A5 that are not equal to "red" and not equal to "blue".
Explanation: the COUNTIFS function in Excel counts cells based on two or more criteria.
This COUNTIFS function has 2 range/criteria pairs.
7. The AVERAGEIF function below calculates the average of the values in the range A1:A5 that are not equal to 0.
Note: in other words, the AVERAGEIF function above calculates the average excluding zeros.
You can use the NOT function in Excel to change FALSE to TRUE or TRUE to FALSE.
To illustrate this function, consider the following example.
8. The OR function below returns TRUE if the value in cell A2 equals "USA" or "UK".
Note: to quickly copy this formula to the other cells, double-click the fill handle (see orange arrow).
9. The formula below returns TRUE if the value in cell A2 is not equal to "USA" or "UK".
Explanation: by adding the NOT function, the logical value returned by the OR function is reversed, so that a TRUE value becomes FALSE, and vice versa.
Count Cells with Text
This page illustrates multiple ways to count cells with text in Excel.
Visit our page about the COUNTIF function to count cells that contain specific text.
1a.
Use the COUNTIF function and the asterisk symbol (*) to count cells with text.
1b.
You can also create an array formula to count cells with text.
Note: visit our page about array formulas to learn more about single cell array formulas.
1c.
You can also use the SUMPRODUCT function to count cells with text.
Note: visit our page about the SUMPRODUCT function to learn more about this function.
2a.
Numbers, Booleans (TRUE or FALSE), blanks and errors are not counted as text.
2b.
The formula below counts cells with text and counts cells with Booleans.
3a.
Enter a space into cell A4. The COUNTIF function at step 1a and step 2a also counts cells with a space character.
3b.
The COUNTIFS function below counts cells with text and excludes cells with a space character.
Note: the COUNTIFS function in Excel counts cells based on two or more criteria.
SUM
Sum Range | Sum Entire Column | Sum Non-contiguous Cells | AutoSum | Conditional Sum | Sum Every Nth Row | Sum Largest Numbers | Sum Range with Errors
Use the SUM function in Excel to sum a range of cells, an entire column or non-contiguous cells.
To create awesome SUM formulas, combine the SUM function with other Excel functions.
Sum Range
Most of the time, you'll use the SUM function in Excel to sum a range of cells.
Sum Entire Column
You can also use the SUM function in Excel to sum an entire column.
Note: you can also use the SUM function in Excel to sum an entire row.
For example, =SUM(5:5) sums all values in the 5th row.Sum Non-contiguous Cells
You can also use the SUM function in Excel to sum non-contiguous cells.
Non-contiguous means not next to each other.
Note: =A3+A5+A8 produces the exact same result!
AutoSum
Use AutoSum or press ALT + = to quickly sum a column or row of numbers.
1. First, select the cell below the column of numbers (or next to the row of numbers) you want to sum.
2. On the Home tab, in the Editing group, click AutoSum (or press ATL + =).
3. Press Enter.
You can also use AutoSum to quickly add a total row and a total column.
4. For example, select the range B2:F5 below.
5. Press ATL + =
Excel inserts 8 SUM functions! An easy but impressive trick.
Conditional Sum
The SUMIF function in Excel returns a conditional sum.
1. The SUMIF function below sums values in the range B1:B5 if the corresponding cells in the range A1:A5 contain exactly green.
2. The SUMIF function below sums today's sales.
Note: today is August 3rd, 2018. Visit our page about the SUMIF function for more information and examples.
Sum Every Nth Row
The SUM formula below uses SUM, MOD and ROW to sum every nth row.
Change the 3 to 4 to sum every 4th row, to 5 to sum every 5th row, etc.
Note: the formula bar indicates that this is an array formula by enclosing it in curly braces {}.
Do not type these yourself.
To enter an array formula, finish by pressing CTRL + SHIFT + ENTER.
In Excel 365 or Excel 2021, finish by simply pressing Enter.
You won't see curly braces.
Sum Largest Numbers
The SUM formula below uses SUM and LARGE to sum the largest numbers in a range.
Change {1,2,3,4} to {1,2,3,4,5} to sum the 5 largest numbers.
Note: =LARGE(A1:A11,2) simply returns the second largest number.
Sum Range with Errors
The SUM formula below uses SUM and IFERROR to sum a range with errors.
You can also use the AGGREGATE function in Excel to sum a range with errors.
Note: the SUM function in Excel automatically ignores text values.
Running Total
Use the SUM function | Use a Simple Formula | Use the Quick Analysis Tool
This page teaches you how to create a running total (cumulative sum) in Excel.
A running total changes each time new data is added to a list.
Use the SUM function
First, let's use the SUM function to create a running total in Excel.
1. For example, select cell B9 below and enter a simple SUM function.
2. Next, select cell C2 and enter the SUM function shown below.
Explanation: the first cell ($B$2) in the range reference is an absolute reference.
We fixed the reference to cell B2 by adding a $ symbol in front of the column letter and row number.
The second cell (B2) in the range reference is a normal relative reference.
3. Select cell C2, click on the lower right corner of cell C2 and drag it down to cell C7.
Explanation: when we drag the formula down, the absolute reference ($B$2) stays the same, while the relative reference (B2) changes to B3, B4, B5, etc.
4. For example, take a look at the formula in cell C3.
5. For example, take a look at the formula in cell C4.
6. At step 2, add the IF function as shown below (and drag it down to cell C7) to only display a cumulative sum if data has been entered.
Explanation: if cell B2 is not empty (<> means not equal to), the IF function in cell C2 displays a cumulative sum, else it displays an empty string (two double quotes with nothing in between).
7. Enter the sales in April.
Use a Simple Formula
You can also use a simple formula to quickly calculate a running total in Excel.
1. Start with the first value.
2. Add the new value to the previous running total (and copy this simple formula down).
3. Select cell C3 (not cell C2!), click on the lower right corner of cell C3 and drag it down to cell C7.
Explanation: the simple formula =C2+B3 changes to =C3+B4, =C4+B5, etc.
Each time the new value is added to the previous running total.
4. You can check this.
Use the Quick Analysis Tool
Not a formula hero? No problem.
You can let Excel do all the work for you!
1. Select a range of cells and click the Quick Analysis button.
2. Click Totals and click Running Total (yellow-orange option).
3. The Quick Analysis tool also uses the SUM function to create a running total.
Note: now it's your turn! Download the Excel file and try to create a running total.
SUMIF
Numeric Criteria | Text Criteria | Date Criteria | And Criteria | Or Criteria
The powerful SUMIF function in Excel sums cells based on one criteria.
This page contains many easy to follow SUMIF examples.
Numeric Criteria
Use the SUMIF function in Excel to sum cells based on numbers that meet specific criteria.
1. The SUMIF function below (two arguments) sums values in the range A1:A5 that are less than or equal to 10.
2. The following SUMIF function gives the exact same result.
The & operator joins the 'less than or equal to' symbol and the value in cell C1.
3. The SUMIF function below (three arguments, last argument is the range to sum) sums values in the range B1:B5 if the corresponding cells in the range A1:A5 contain the value 25.
4. The following SUMIF function gives the exact same result (second argument refers to cell D1).
Text Criteria
Use the SUMIF function in Excel to sum cells based on text strings that meet specific criteria.
Always enclose text in double quotation marks.
1. The SUMIF function below sums values in the range B1:B5 if the corresponding cells in the range A1:A5 contain exactly circle.
2. The SUMIF function below sums values in the range B1:B5 if the corresponding cells in the range A1:A5 do not contain exactly triangle.
3. The SUMIF function below sums values in the range B1:B5 if the corresponding cells in the range A1:A5 contain exactly circle + 1 character.
A question mark (?) matches exactly one character.
4. The SUMIF function below sums values in the range B1:B5 if the corresponding cells in the range A1:A5 contain a series of zero or more characters + le.
An asterisk (*) matches a series of zero or more characters.
5. The SUMIF functions below sum values in the range B1:B5 if the corresponding cells in the range A1:A5 contain exactly triangle or circle8.
Date Criteria
Use the SUMIF function in Excel to sum cells based on dates that meet specific criteria.
1. The SUMIF function below sums the sales after January 20th, 2018.
Note: the DATE function in Excel accepts three arguments: year, month and day.
2. The SUMIF function below sums today's sales.
Note: today is August 3rd, 2018.
3. The SUMIFS function (with the letter S at the end) below sums the sales between two dates.
Note: the SUMIFS function in Excel sums cells based on two or more criteria (first argument is the range to sum, followed by two or more range/criteria pairs).
Adjust the dates to sum the sales in a specific month, year, etc.
And Criteria
Summing with And criteria in Excel is easy.
1. For example, to sum the cells that meet the following criteria: Google and Stanford (two criteria ranges), simply use the SUMIFS function (with the letter S at the end).
Note: remember, when using the SUMIFS function, the first argument is the range to sum, followed by two or more range/criteria pairs.
Or Criteria
Summing with Or criteria in Excel can be tricky.
1. The formula below sums the cells that meet the following criteria: Google or Facebook (one criteria range).
No rocket science so far.
2. However, if you want to sum the cells that meet the following criteria: Google or Stanford (two criteria ranges), you cannot simply use the SUMIF function twice (see the picture below).
Note: cells that meet the criteria Google and Stanford are added twice, but they should only be added once.
10 is the answer we are looking for.
3. The array formula below does the trick.
Note: finish an array formula by pressing CTRL + SHIFT + ENTER.
Excel adds the curly braces {}.
In Excel 365 or Excel 2021, finish by simply pressing Enter.
You won't see curly braces.
Visit our page about Summing with Or Criteria for instructions on how to create this array formula.
SUMPRODUCT
Basic Use | Advanced Use
To calculate the sum of the products of corresponding numbers in one or more ranges, use Excel's powerful SUMPRODUCT function.
Basic Use
1. For example, the SUMPRODUCT function below calculates the total amount spent.
Explanation: the SUMPRODUCT function performs this calculation: (2 * 1000) + (4 * 250) + (4 * 100) + (2 * 50) = 3500.
2. The ranges must have the same dimensions or Excel will display the #VALUE! error.
3. The SUMPRODUCT function treats any entries that are not numeric as if they were zeros.
4. If you supply a single range, the SUMPRODUCT function produces the exact same result as the SUM function.
Advanced Use
The SUMPRODUCT function is an extremely versatile function and can produce the same result as many built-in functions in Excel and even array formulas!
1a.
For example, the COUNTIF function below counts the number of cells that contain exactly star.
1b.
The SUMPRODUCT function below produces the exact same result.
Explanation: --(A1:A7="star") reduces to the following array constant:
--{TRUE;FALSE;FALSE;FALSE;FALSE;TRUE;FALSE}
The double negative -- coerces these Booleans to 1's and 0's (TRUE=1, FALSE=0).
Result:
{1;0;0;0;0;1;0}
This array constant is used as an argument for the SUMPRODUCT function, giving a result of 2.
2a.
The COUNTIF function below counts the number of cells that contain exactly star + 1 character.
A question mark (?) matches exactly one character.
2b.
The SUMPRODUCT function is not perfect! You cannot use wildcard characters (? and *) when you use the SUMPRODUCT function.
3a.
The array formula below counts the number of characters in a range of cells.
Note: finish an array formula by pressing CTRL + SHIFT + ENTER.
Excel adds the curly braces {}.
In Excel 365 or Excel 2021, finish by simply pressing Enter.
You won't see curly braces.
3b.
The SUMPRODUCT function below produces the exact same result.
Note: the array constant {9;4;6;5} is used as an argument for the SUMPRODUCT function, giving a result of 24. The SUMPRODUCT function handles arrays natively so you don't have to finish by pressing CTRL + SHIFT + ENTER.
4a.
The array formula below sums the sales in 2018.
4b.
The SUMPRODUCT function below produces the exact same result.
Explanation: (YEAR(A1:A5)=2018)*B1:B5 reduces to:
({2018;2017;2018;2017;2017}=2018)*{10;1;7;20;3} and this reduces to:
{TRUE;FALSE;TRUE;FALSE;FALSE}*{10;1;7;20;3}
We don't need a double negative (see example 1b) because the multiplication operator * automatically coerces the Booleans to 1's and 0's (TRUE=1, FALSE=0).
Result:
{10;0;7;0;0}
This array constant is used as an argument for the SUMPRODUCT function, giving a result of 17.
IF
Simple If Examples | And/Or Criteria | Nested If | More about If
The IF function is one of the most used functions in Excel.
This page contains many easy to follow IF examples.
Simple If Examples
The IF function checks whether a condition is met, and returns one value if true and another value if false.
1a.
For example, take a look at the IF function in cell B2 below.
Explanation: if the price is greater than 500, the IF function returns High, else it returns Low.
1b.
The following IF function produces the exact same result.
Note: you can use the following comparison operators: = (equal to), > (greater than), < (less than), >= (greater than or equal to), <= (less than or equal to) and <> (not equal to).
2. Always enclose text in double quotation marks.
3a.
The formula below calculates the progress between two points in time.
3b.
You can use the IF function to display an empty string if the end value hasn't been entered yet (see row 5).
Explanation: if the end value is not empty (<> means not equal to), the IF function calculates the progress between the start and end value, else it displays an empty string (two double quotes with nothing in between).
And/Or Criteria
Use the IF function in combination with the AND function and the OR function and become an Excel expert.
1. For example, take a look at the IF function in cell D2 below.
Explanation: the AND function returns TRUE if the first score is greater than or equal to 60 and the second score is greater than or equal to 90, else it returns FALSE.
If TRUE, the IF function returns Pass, if FALSE, the IF function returns Fail.
2. For example, take a look at the IF function in cell D2 below.
Explanation: the OR function returns TRUE if at least one score is greater than or equal to 60, else it returns FALSE.
If TRUE, the IF function returns Pass, if FALSE, the IF function returns Fail.
3. For example, take a look at the IF function in cell D2 below.
Explanation: the AND function above has two arguments separated by a comma (Table, Green or Blue).
The AND function returns TRUE if Product equals "Table" and Color equals "Green" or "Blue".
If TRUE, the IF function reduces the price by 50%, if FALSE, the IF function reduces the price by 10%.
Nested If
The IF function in Excel can be nested, when you have multiple conditions to meet.
The FALSE value is being replaced by another IF function to make a further test.
1. For example, take a look at the nested IF formula in cell C2 below.
Explanation: if the score equals 1, the nested IF formula returns Bad, if the score equals 2, the nested IF formula returns Good, if the score equals 3, the nested IF formula returns Excellent, else it returns Not Valid.
If you have Excel 2016 or later, simply use the IFS function.
2. For example, take a look at the nested IF formula in cell C2 below.
Explanation: if the score is less than 60, the nested IF formula returns F, if the score is greater than or equal to 60 and less than 70, the formula returns D, if the score is greater than or equal to 70 and less than 80, the formula returns C, if the score is greater than or equal to 80 and less than 90, the formula returns B, else it returns A.
More about If
The IF function is a great function.
Let's take a look at a few more cool examples.
1. For example, use IF and AND to test if a value is between two numbers.
Explanation: the AND function returns TRUE if the person is older than 12 and younger than 20, else it returns FALSE.
If TRUE, the IF function returns Yes, if FALSE, the IF function returns No.
2. You can combine IF with AVERAGE, SUM and other Excel functions.
The sky is the limit!
Explanation: the AND function returns TRUE if the input value is greater than 100 and the average of the values in the named range Data1 is greater than 100, else it returns FALSE.
If TRUE, the IF function returns the sum of Data2, if FALSE, the IF function returns 0.
Confused? You can always use the Evaluate Formula tool to step through your IF formula.
This Excel tool helps you understand a formula.
3. For example, select cell G3 above.
4. On the Formulas tab, in the Formula Auditing group, click Evaluate Formula.
5. Click Evaluate multiple times.
Note: try it yourself.
Download the Excel file and choose one of the IF formulas explained on this page.
You can use this tool to step through all kinds of formulas.
Learn more about Logical Functions in Excel |
1. Logical Functions |
Learn how to use Excel's logical functions, such as IF, AND, OR and NOT. |
|
2. If |
The IF function is one of the most used functions in Excel.
This page contains many easy to follow IF examples. |
|
3. Comparison Operators |
Use comparison operators in Excel to check if two values are equal to each other, if one value is greater than another value, if one value is less than another value, etc. |
|
4. Or |
The OR function in Excel returns TRUE if any of the conditions are true and returns FALSE if all conditions are false.
Combine the OR function with other functions and become an Excel expert. |
|
5. Roll the Dice |
This page teaches you how to simulate the roll of two dice in Excel.
If you are in a hurry, simply download the Excel file. |
|
6. Ifs |
Use the IFS function in Excel 2016 or later when you have multiple conditions to meet.
The IFS function returns a value corresponding to the first TRUE condition. |
|
7. Contains Specific Text |
To check if a cell contains specific text, use ISNUMBER and SEARCH in Excel.
There's no CONTAINS function in Excel. |
|
8. Switch |
The SWITCH function in Excel looks up a specified value in a list of values and returns the result corresponding to the first match found. |
|
9. If Cell is Blank |
Use the IF function and an empty string in Excel to check if a cell is blank.
Use IF and ISBLANK to produce the exact same result. |
|
10. Absolute Value |
The ABS function in Excel returns the absolute value of a number.
In other words: the ABS function removes the minus sign (-) from a negative number, making it positive. |
|
Comparison Operators
Equal to | Greater than | Less than | Greater than or equal to | Less than or equal to | Not equal to
Use comparison operators in Excel to check if two values are equal to each other, if one value is greater than another value, if one value is less than another value, etc.
Equal to
The equal to operator (=) returns TRUE if two values are equal to each other.
1. For example, take a look at the formula in cell C1 below.
Explanation: the formula returns TRUE because the value in cell A1 is equal to the value in cell B1. Always start a formula with an equal sign (=).
2. The IF function below uses the equal to operator.
Explanation: if the two values (numbers or text strings) are equal to each other, the IF function returns Yes, else it returns No.
Greater than
The greater than operator (>) returns TRUE if the first value is greater than the second value.
1. For example, take a look at the formula in cell C1 below.
Explanation: the formula returns TRUE because the value in cell A1 is greater than the value in cell B1.
2. The OR function below uses the greater than operator.
Explanation: this OR function returns TRUE if at least one value is greater than 50, else it returns FALSE.
Less than
The less than operator (<) returns TRUE if the first value is less than the second value.
1. For example, take a look at the formula in cell C1 below.
Explanation: the formula returns TRUE because the value in cell A1 is less than the value in cell B1.
2. The AND function below uses the less than operator.
Explanation: this AND function returns TRUE if both values are less than 80, else it returns FALSE.
Greater than or equal to
The greater than or equal to operator (>=) returns TRUE if the first value is greater than or equal to the second value.
1. For example, take a look at the formula in cell C1 below.
Explanation: the formula returns TRUE because the value in cell A1 is greater than or equal to the value in cell B1.
2. The COUNTIF function below uses the greater than or equal to operator.
Explanation: this COUNTIF function counts the number of cells that are greater than or equal to 10.
Less than or equal to
The less than or equal to operator (<=) returns TRUE if the first value is less than or equal to the second value.
1. For example, take a look at the formula in cell C1 below.
Explanation: the formula returns TRUE because the value in cell A1 is less than or equal to the value in cell B1.
2. The SUMIF function below uses the less than or equal to operator.
Explanation: this SUMIF function sums values in the range A1:A5 that are less than or equal to 10.
Not Equal to
The not equal to operator (<>) returns TRUE if two values are not equal to each other.
1. For example, take a look at the formula in cell C1 below.
Explanation: the formula returns TRUE because the value in cell A1 is not equal to the value in cell B1.
2. The IF function below uses the not equal to operator.
Explanation: if the two values (numbers or text strings) are not equal to each other, the IF function returns No, else it returns Yes.
Learn more about Logical Functions in Excel |
1. Logical Functions |
Learn how to use Excel's logical functions, such as IF, AND, OR and NOT. |
|
2. If |
The IF function is one of the most used functions in Excel.
This page contains many easy to follow IF examples. |
|
3. Comparison Operators |
Use comparison operators in Excel to check if two values are equal to each other, if one value is greater than another value, if one value is less than another value, etc. |
|
4. Or |
The OR function in Excel returns TRUE if any of the conditions are true and returns FALSE if all conditions are false.
Combine the OR function with other functions and become an Excel expert. |
|
5. Roll the Dice |
This page teaches you how to simulate the roll of two dice in Excel.
If you are in a hurry, simply download the Excel file. |
|
6. Ifs |
Use the IFS function in Excel 2016 or later when you have multiple conditions to meet.
The IFS function returns a value corresponding to the first TRUE condition. |
|
7. Contains Specific Text |
To check if a cell contains specific text, use ISNUMBER and SEARCH in Excel.
There's no CONTAINS function in Excel. |
|
8. Switch |
The SWITCH function in Excel looks up a specified value in a list of values and returns the result corresponding to the first match found. |
|
9. If Cell is Blank |
Use the IF function and an empty string in Excel to check if a cell is blank.
Use IF and ISBLANK to produce the exact same result. |
|
10. Absolute Value |
The ABS function in Excel returns the absolute value of a number.
In other words: the ABS function removes the minus sign (-) from a negative number, making it positive. |
|
OR
The OR function in Excel returns TRUE if any of the conditions are true and returns FALSE if all conditions are false.
Combine the OR function with other functions and become an Excel expert.
1. For example, take a look at the OR function in cell D2 below.
Explanation: the OR function returns TRUE if the first score is greater than 70 or the second score is equal to 100, else it returns FALSE.
2. Combine the OR function with the IF function.
Explanation: the OR function returns TRUE or FALSE (see previous example).
If TRUE, the IF function returns Pass, if FALSE, the IF function returns Fail.
3. For example, take a look at the OR function in cell E2 below.
Explanation: the OR function returns TRUE if at least one score is greater than or equal to 90, else it returns FALSE.
The OR function can test up to 255 conditions.
The only way for the OR function to return FALSE is if all the conditions are FALSE (row 6).
4. The array formula below uses the OR function to return TRUE if any cell in the range A1:E6 is greater than or equal to 90.
Explanation: finish an array formula by pressing CTRL + SHIFT + ENTER.
Excel adds the curly braces {}.
In Excel 365 or Excel 2021, finish by simply pressing Enter.
You won't see curly braces.
The value in cell D4 is greater than or equal to 90. As a result, the array formula returns TRUE.
5. Combine the OR function with the AND function.
Explanation: the AND Function returns TRUE if all conditions are true and returns FALSE if any of the conditions are false.
The AND function above has two arguments separated by a comma (Table, Green or Blue).
The AND function returns TRUE if Product equals "Table" and Color equals "Green" or "Blue".
6. Combine the OR function with the WEEKDAY function.
Explanation: the WEEKDAY function in Excel returns a number from 1 (Sunday) to 7 (Saturday) representing the day of the week of a date.
As a result, the OR function returns TRUE if the date falls on a weekend.
7. Don't confuse the OR function with the XOR (Exclusive OR) function.
Explanation: the XOR function returns TRUE if an odd number of conditions are true, and FALSE otherwise.
With two conditions (see example above) the XOR function returns TRUE if one condition is true (row 2) and returns FALSE if both conditions are false (row 3, 4 and 6) or both conditions are true! (row 5).
Learn more about Logical Functions in Excel |
1. Logical Functions |
Learn how to use Excel's logical functions, such as IF, AND, OR and NOT. |
|
2. If |
The IF function is one of the most used functions in Excel.
This page contains many easy to follow IF examples. |
|
3. Comparison Operators |
Use comparison operators in Excel to check if two values are equal to each other, if one value is greater than another value, if one value is less than another value, etc. |
|
4. Or |
The OR function in Excel returns TRUE if any of the conditions are true and returns FALSE if all conditions are false.
Combine the OR function with other functions and become an Excel expert. |
|
5. Roll the Dice |
This page teaches you how to simulate the roll of two dice in Excel.
If you are in a hurry, simply download the Excel file. |
|
6. Ifs |
Use the IFS function in Excel 2016 or later when you have multiple conditions to meet.
The IFS function returns a value corresponding to the first TRUE condition. |
|
7. Contains Specific Text |
To check if a cell contains specific text, use ISNUMBER and SEARCH in Excel.
There's no CONTAINS function in Excel. |
|
8. Switch |
The SWITCH function in Excel looks up a specified value in a list of values and returns the result corresponding to the first match found. |
|
9. If Cell is Blank |
Use the IF function and an empty string in Excel to check if a cell is blank.
Use IF and ISBLANK to produce the exact same result. |
|
10. Absolute Value |
The ABS function in Excel returns the absolute value of a number.
In other words: the ABS function removes the minus sign (-) from a negative number, making it positive. |
|
Roll the Dice
This page teaches you how to simulate the roll of two dice in Excel.
If you are in a hurry, simply download the Excel file.
Note: the instructions below do not teach you how to format the worksheet.
We assume that you know how to change font sizes, font styles, insert rows and columns, add borders, change background colors, etc.
1. At the moment, each cell contains the letter l (as in lion).
With a Wingdings font style, these l's look like dots.
2. Enter the RANDBETWEEN function in cell C2.
3. Enter the formula shown below into the yellow cells.
If we roll 2, 3, 4, 5 or 6, these cells should contain a dot.
4. Enter the formula shown below into the red cells.
If we roll 4, 5 or 6, these cells should contain a dot.
5. Enter the formula shown below into the blue cells.
If we roll 6, these cells should contain a dot.
6. Enter the formula shown below into the gray cell.
If we roll 1, 3 or 5, this cell should contain a dot.
7. Copy the range C2:E5 and paste it to the range G2:I5.
8. Change the font color of cell C2 and cell G2 to green (so the numbers are not visible).
9. Click the command button on the sheet (or press F9).
Result.
Learn more about Logical Functions in Excel |
1. Logical Functions |
Learn how to use Excel's logical functions, such as IF, AND, OR and NOT. |
|
2. If |
The IF function is one of the most used functions in Excel.
This page contains many easy to follow IF examples. |
|
3. Comparison Operators |
Use comparison operators in Excel to check if two values are equal to each other, if one value is greater than another value, if one value is less than another value, etc. |
|
4. Or |
The OR function in Excel returns TRUE if any of the conditions are true and returns FALSE if all conditions are false.
Combine the OR function with other functions and become an Excel expert. |
|
5. Roll the Dice |
This page teaches you how to simulate the roll of two dice in Excel.
If you are in a hurry, simply download the Excel file. |
|
6. Ifs |
Use the IFS function in Excel 2016 or later when you have multiple conditions to meet.
The IFS function returns a value corresponding to the first TRUE condition. |
|
7. Contains Specific Text |
To check if a cell contains specific text, use ISNUMBER and SEARCH in Excel.
There's no CONTAINS function in Excel. |
|
8. Switch |
The SWITCH function in Excel looks up a specified value in a list of values and returns the result corresponding to the first match found. |
|
9. If Cell is Blank |
Use the IF function and an empty string in Excel to check if a cell is blank.
Use IF and ISBLANK to produce the exact same result. |
|
10. Absolute Value |
The ABS function in Excel returns the absolute value of a number.
In other words: the ABS function removes the minus sign (-) from a negative number, making it positive. |
|
IFS
Use the IFS function in Excel 2016 or later when you have multiple conditions to meet.
The IFS function returns a value corresponding to the first TRUE condition.
Note: if you don't have Excel 2016 or later, you can nest the IF function.
1a.
If the value in cell A1 equals 1, the IFS function returns Bad.
1b.
If the value in cell A1 equals 2, the IFS function returns Good.
1c.
If the value in cell A1 equals 3, the IFS function returns Excellent.
1d.
If the value in cell A1 equals another value, the IFS function returns No Valid Score.
Note: instead of TRUE, you can also use 1=1 or something else that is always TRUE.
Here's another example.
2a.
If the value in cell A1 is less than 60, the IFS function returns F.
2b.
If the value in cell A1 is greater than or equal to 60 and less than 70, the IFS function returns D.
2c.
If the value in cell A1 is greater than or equal to 70 and less than 80, the IFS function returns C.
2d.
If the value in cell A1 is greater than or equal to 80 and less than 90, the IFS function returns B.
2e.
If the value in cell A1 is greater than or equal to 90, the IFS function returns A.
Note: to slightly change the boundaries, you might want to use "<=" instead of "<" in your own function.
Learn more about Logical Functions in Excel |
1. Logical Functions |
Learn how to use Excel's logical functions, such as IF, AND, OR and NOT. |
|
2. If |
The IF function is one of the most used functions in Excel.
This page contains many easy to follow IF examples. |
|
3. Comparison Operators |
Use comparison operators in Excel to check if two values are equal to each other, if one value is greater than another value, if one value is less than another value, etc. |
|
4. Or |
The OR function in Excel returns TRUE if any of the conditions are true and returns FALSE if all conditions are false.
Combine the OR function with other functions and become an Excel expert. |
|
5. Roll the Dice |
This page teaches you how to simulate the roll of two dice in Excel.
If you are in a hurry, simply download the Excel file. |
|
6. Ifs |
Use the IFS function in Excel 2016 or later when you have multiple conditions to meet.
The IFS function returns a value corresponding to the first TRUE condition. |
|
7. Contains Specific Text |
To check if a cell contains specific text, use ISNUMBER and SEARCH in Excel.
There's no CONTAINS function in Excel. |
|
8. Switch |
The SWITCH function in Excel looks up a specified value in a list of values and returns the result corresponding to the first match found. |
|
9. If Cell is Blank |
Use the IF function and an empty string in Excel to check if a cell is blank.
Use IF and ISBLANK to produce the exact same result. |
|
10. Absolute Value |
The ABS function in Excel returns the absolute value of a number.
In other words: the ABS function removes the minus sign (-) from a negative number, making it positive. |
|
Contains Specific Text
To check if a cell contains specific text, use ISNUMBER and SEARCH in Excel.
There's no CONTAINS function in Excel.
1. To find the position of a substring in a text string, use the SEARCH function.
Explanation: "duck" found at position 10, "donkey" found at position 1, cell A4 does not contain the word "horse" and "goat" found at position 12.
2. Add the ISNUMBER function.
The ISNUMBER function returns TRUE if a cell contains a number, and FALSE if not.
Explanation: cell A2 contains the word "duck", cell A3 contains the word "donkey", cell A4 does not contain the word "horse" and cell A5 contains the word "goat".
3. You can also check if a cell contains specific text, without displaying the substring.
Make sure to enclose the substring in double quotation marks.
4. To perform a case-sensitive search, replace the SEARCH function with the FIND function.
Explanation: the formula in cell C3 returns FALSE now.
Cell A3 does not contain the word "donkey" but contains the word "Donkey".
5. Add the IF function.
The formula below (case-insensitive) returns "Found" if a cell contains specific text, and "Not Found" if not.
6. You can also use IF and COUNTIF in Excel to check if a cell contains specific text.
However, the COUNTIF function is always case-insensitive.
Explanation: the formula in cell C2 reduces to =IF(COUNTIF(A2,"*duck*"),"Found","Not Found").
An asterisk (*) matches a series of zero or more characters.
Visit our page about the COUNTIF function to learn all you need to know about this powerful function.
Learn more about Logical Functions in Excel |
1. Logical Functions |
Learn how to use Excel's logical functions, such as IF, AND, OR and NOT. |
|
2. If |
The IF function is one of the most used functions in Excel.
This page contains many easy to follow IF examples. |
|
3. Comparison Operators |
Use comparison operators in Excel to check if two values are equal to each other, if one value is greater than another value, if one value is less than another value, etc. |
|
4. Or |
The OR function in Excel returns TRUE if any of the conditions are true and returns FALSE if all conditions are false.
Combine the OR function with other functions and become an Excel expert. |
|
5. Roll the Dice |
This page teaches you how to simulate the roll of two dice in Excel.
If you are in a hurry, simply download the Excel file. |
|
6. Ifs |
Use the IFS function in Excel 2016 or later when you have multiple conditions to meet.
The IFS function returns a value corresponding to the first TRUE condition. |
|
7. Contains Specific Text |
To check if a cell contains specific text, use ISNUMBER and SEARCH in Excel.
There's no CONTAINS function in Excel. |
|
8. Switch |
The SWITCH function in Excel looks up a specified value in a list of values and returns the result corresponding to the first match found. |
|
9. If Cell is Blank |
Use the IF function and an empty string in Excel to check if a cell is blank.
Use IF and ISBLANK to produce the exact same result. |
|
10. Absolute Value |
The ABS function in Excel returns the absolute value of a number.
In other words: the ABS function removes the minus sign (-) from a negative number, making it positive. |
|
SWITCH
Simple SWITCH | Advanced SWITCH | Combine SWITCH with other Functions | SWITCH or IFS?
The SWITCH function in Excel looks up a specified value in a list of values and returns the result corresponding to the first match found.
Simple SWITCH
Let's start simple.
The SWITCH function below looks up the value in cell B3.
Explanation: if the value is 1, the SWITCH function returns "Bad".
If the value is 2, the SWITCH function returns "Good".
If the value is 3, the SWITCH function returns "Excellent".
The last argument (a dash in this example) is always the default value (if there's no match).
Advanced SWITCH
Let's kick it up a notch! The SWITCH function below reduces the price of green and blue tables by 50% (see orange arrows).
All other products are discounted by 10%.
Explanation: the formula shown above uses the & operator to concatenate (join) the string in cell B3 and cell C3. If the value is "TableGreen", the SWITCH function reduces the price by 50%.
If the value is "TableBlue", the SWITCH function also reduces the price by 50%.
The last argument (10% discount) is always the default value (if there's no match).
Combine SWITCH with other Functions
Let's combine the SWITCH function with other Excel functions.
For example, the SWITCH function below looks up the result of the RIGHT function.
Explanation: the RIGHT function extracts the 2 rightmost characters from the string in cell B3. If UT, the SWITCH function returns "Utah".
If TX, the SWITCH function returns "Texas".
If OH, the SWITCH function returns Ohio.
The last argument (a question mark in this example) is always the default value (if there's no match).
SWITCH or IFS?
The IFS function below produces the exact same result.
Conclusion: the SWITCH function is shorter and easier to read.
However, the SWITCH can only perform an exact match.
When using comparison operators like "=", use IFS instead of SWITCH.
Note: visit our page about the IFS function to learn more about this powerful Excel function.
IFS and SWITCH are only available in Excel 2016 and later versions.
If you don't have Excel 2016 or later, you can nest the IF function.
Learn more about Logical Functions in Excel |
1. Logical Functions |
Learn how to use Excel's logical functions, such as IF, AND, OR and NOT. |
|
2. If |
The IF function is one of the most used functions in Excel.
This page contains many easy to follow IF examples. |
|
3. Comparison Operators |
Use comparison operators in Excel to check if two values are equal to each other, if one value is greater than another value, if one value is less than another value, etc. |
|
4. Or |
The OR function in Excel returns TRUE if any of the conditions are true and returns FALSE if all conditions are false.
Combine the OR function with other functions and become an Excel expert. |
|
5. Roll the Dice |
This page teaches you how to simulate the roll of two dice in Excel.
If you are in a hurry, simply download the Excel file. |
|
6. Ifs |
Use the IFS function in Excel 2016 or later when you have multiple conditions to meet.
The IFS function returns a value corresponding to the first TRUE condition. |
|
7. Contains Specific Text |
To check if a cell contains specific text, use ISNUMBER and SEARCH in Excel.
There's no CONTAINS function in Excel. |
|
8. Switch |
The SWITCH function in Excel looks up a specified value in a list of values and returns the result corresponding to the first match found. |
|
9. If Cell is Blank |
Use the IF function and an empty string in Excel to check if a cell is blank.
Use IF and ISBLANK to produce the exact same result. |
|
10. Absolute Value |
The ABS function in Excel returns the absolute value of a number.
In other words: the ABS function removes the minus sign (-) from a negative number, making it positive. |
|
If Cell is Blank
If Blank | If Not Blank | Highlight Blank Cells
Use the IF function and an empty string in Excel to check if a cell is blank.
Use IF and ISBLANK to produce the exact same result.
If Blank
Remember, the IF function in Excel checks whether a condition is met, and returns one value if true and another value if false.
1. The IF function below returns Yes if the input value is equal to an empty string (two double quotes with nothing in between), else it returns No.
Note: if the input cell contains a space, it looks blank.
However, if this is the case, the input value is not equal to an empty string and the IF function above will return No.
2. Use IF and ISBLANK to produce the exact same result.
Note: the ISBLANK function returns TRUE if a cell is empty and FALSE if not.
If the input cell contains a space or a formula that returns an empty string, it looks blank.
However, if this is the case, the input cell is not empty and the formula above will return No.
If Not Blank
In Excel, <> means not equal to.
1. The IF function below multiplies the input value by 2 if the input value is not equal to an empty string (two double quotes with nothing in between), else it returns an empty string.
2. Use IF, NOT and ISBLANK to produce the exact same result.
Highlight Blank Cells
You can use conditional formatting in Excel to highlight cells that are blank.
1. For example, select the range A1:H8.
2. On the Home tab, in the Styles group, click Conditional Formatting.
3. Click Highlight Cells Rules, More Rules.
4. Select Blanks from the drop-down list, select a formatting style and click OK.
Result.
Note: visit our page about conditional formatting to learn much more about this cool Excel feature.
Learn more about Logical Functions in Excel |
1. Logical Functions |
Learn how to use Excel's logical functions, such as IF, AND, OR and NOT. |
|
2. If |
The IF function is one of the most used functions in Excel.
This page contains many easy to follow IF examples. |
|
3. Comparison Operators |
Use comparison operators in Excel to check if two values are equal to each other, if one value is greater than another value, if one value is less than another value, etc. |
|
4. Or |
The OR function in Excel returns TRUE if any of the conditions are true and returns FALSE if all conditions are false.
Combine the OR function with other functions and become an Excel expert. |
|
5. Roll the Dice |
This page teaches you how to simulate the roll of two dice in Excel.
If you are in a hurry, simply download the Excel file. |
|
6. Ifs |
Use the IFS function in Excel 2016 or later when you have multiple conditions to meet.
The IFS function returns a value corresponding to the first TRUE condition. |
|
7. Contains Specific Text |
To check if a cell contains specific text, use ISNUMBER and SEARCH in Excel.
There's no CONTAINS function in Excel. |
|
8. Switch |
The SWITCH function in Excel looks up a specified value in a list of values and returns the result corresponding to the first match found. |
|
9. If Cell is Blank |
Use the IF function and an empty string in Excel to check if a cell is blank.
Use IF and ISBLANK to produce the exact same result. |
|
10. Absolute Value |
The ABS function in Excel returns the absolute value of a number.
In other words: the ABS function removes the minus sign (-) from a negative number, making it positive. |
|
Absolute Value
The ABS function in Excel returns the absolute value of a number.
In other words: the ABS function removes the minus sign (-) from a negative number, making it positive.
1. For example, the ABS function in cell B1 below returns the absolute value of a negative number.
The ABS function has no effect on 0 (zero) or positive numbers.
2. The absolute value of 0 is 0.
3. The absolute value of a positive number is the same positive number.
When do we need the ABS function in Excel?
4. For example, calculate the forecast error (difference between the actual and the forecast value) for each month.
Note: if we look at the sum of these errors (zero), this forecast model seems perfect, but it's not!
5. Simply use the ABS function to calculate the absolute error for each month.
6. If you don't want to display the forecast errors on the sheet, use SUMPRODUCT and ABS.
Note: visit our page about the SUMPRODUCT function to learn more about this function.
Let's take a look at one more cool example.
7. Use the ABS function to calculate the absolute value of each difference.
8. Add the IF function to test if the values are within tolerance.
Explanation: if the difference is less than or equal to 3, the IF function returns 1, else it returns 0.
9. Add icons.
10. Change the tolerance.
Note: visit our page about icon sets to learn more about this topic.
To view this formatting rule, download the Excel file.
Next, on the Home tab, in the Styles group, click Conditional Formatting, Manage Rules.
Learn more about Logical Functions in Excel |
1. Logical Functions |
Learn how to use Excel's logical functions, such as IF, AND, OR and NOT. |
|
2. If |
The IF function is one of the most used functions in Excel.
This page contains many easy to follow IF examples. |
|
3. Comparison Operators |
Use comparison operators in Excel to check if two values are equal to each other, if one value is greater than another value, if one value is less than another value, etc. |
|
4. Or |
The OR function in Excel returns TRUE if any of the conditions are true and returns FALSE if all conditions are false.
Combine the OR function with other functions and become an Excel expert. |
|
5. Roll the Dice |
This page teaches you how to simulate the roll of two dice in Excel.
If you are in a hurry, simply download the Excel file. |
|
6. Ifs |
Use the IFS function in Excel 2016 or later when you have multiple conditions to meet.
The IFS function returns a value corresponding to the first TRUE condition. |
|
7. Contains Specific Text |
To check if a cell contains specific text, use ISNUMBER and SEARCH in Excel.
There's no CONTAINS function in Excel. |
|
8. Switch |
The SWITCH function in Excel looks up a specified value in a list of values and returns the result corresponding to the first match found. |
|
9. If Cell is Blank |
Use the IF function and an empty string in Excel to check if a cell is blank.
Use IF and ISBLANK to produce the exact same result. |
|
10. Absolute Value |
The ABS function in Excel returns the absolute value of a number.
In other words: the ABS function removes the minus sign (-) from a negative number, making it positive. |
|
Copy a Formula
Copy 101 | Fill Handle | Absolute Reference | Move a Formula | Exact Copy | Copy Magic
When you copy a formula, Excel automatically adjusts the cell references for each new cell the formula is copied to.
Copy 101
Simply use CTRL + c and CTRL + v to copy and paste a formula in Excel.
1. For example, to copy a formula, select cell A3 below and press CTRL + c.
2. To paste this formula, select cell B3 and press CTRL + v.
3. Click in the formula bar to clearly see that the formula references the values in column B.
Fill Handle
Use the fill handle in Excel to quickly copy a formula to other cells.
1. For example, select cell A3 below, click on the lower right corner of cell A3 (the fill handle) and drag it across to cell F3.
Result.
You can also use the fill handle to quickly copy a formula down a column.
2. For example, select cell C1 below, click on the lower right corner of cell C1 (the fill handle) and drag it down to cell C6.
Result.
Tip: instead of dragging the fill handle down, simply select cell C1 and double click the fill handle.
If you have hundreds of rows of data, this can save time!
Absolute Reference
Create an absolute reference to fix the reference to a cell or range of cells.
When you copy a formula, an absolute reference never changes.
1. For example, fix the reference to cell E2 below by placing a $ symbol in front of the column letter and row number.
2. Select cell C2, click on the lower right corner of cell C2 and drag it down to cell C7.
Check:
Explanation: the absolute reference ($E$2) stays the same, while the relative reference (B2) changes to B3, B4, B5, B6 and B7. Visit our page about absolute reference to learn more about this topic.
Move a Formula
To move a formula in Excel, simply use cut (CTRL + x) and paste (CTRL + v).
Excel pros use the following trick to move a formula.
1. Select a cell with a formula.
2. Hover over the border of the selection.
A four-sided arrow appears.
3. Click and hold the left mouse button.
4. Move the formula to the new position.
5. Release the left mouse button.
Exact Copy
To make an exact copy of a formula, without changing the cell references, execute the following easy steps.
1. Click in the formula bar and select the formula.
2. Press CTRL + c and press Enter.
3. Select another cell and press CTRL + v.
Result:
Conclusion: cell A3 and cell B3 contain the exact same formula.
Copy Magic
To make an exact copy of multiple formulas, repeat the previous steps for each formula.
You can also use the following magic trick.
1. Select multiple formulas.
2. Replace all equal signs with xxx.
Result.
3. Use CTRL + c and CTRL + v to copy and paste the text strings.
4. Select the range B6:B10, hold down CTRL, select the range E6:E10 and replace all occurrences of 'xxx' with equal signs (the exact opposite of step 2).
Result.
Conclusion: cell B6 and cell E6 contain the exact same formula, cell B7 and cell E7 contain the exact same formula, etc.
3D-reference
A 3D-reference in Excel refers to the same cell or range on multiple worksheets.
First, we'll look at the alternative.
1. On the Company sheet, select cell B2 and type an equal sign =
2. Go to the North sheet, select cell B2 and type a +
3. Repeat step 2 for the Mid and South sheet.
Result.
4. This is quite a lot of work.
Instead of doing this, use the following 3D-reference: North:South!B2 as the argument for the SUM function.
5. If you add worksheets between North and South, this worksheet is automatically included in the formula in cell B2.
Name Box
You can use the name box in Excel to select a cell, range or named range.
You can also use the name box to quickly create a named range (important).
1. We start simple.
The name box below displays the address of the active cell (B6).
2. You can use the name box to select a cell, range or named range.
For example, click in the name box and type E2:F8.
3. Press Enter.
Note: the name box only displays the upper-left cell of a selected range.
4. Use the name box to quickly create a named range.
For example, select the range A2:A9 below, click in the name box and type Scores.
5. Press Enter.
6. Now let's use this named range in a formula.
Note: use the Name Manager to edit and delete named ranges.
Visit our page about named ranges for more information and formula examples.
7. Finally, click the drop-down arrow in the name box to see a list of all the named ranges in a workbook.
For example, click Ages.
8. Excel selects the named range Ages on Sheet2.
Note: if you're interested, you can download this Excel file.
External References
Create External Reference | Alert | Edit Links
An external reference in Excel is a reference to a cell or range of cells in another workbook.
Below you can find the workbooks of three divisions (North, Mid and South).
Create External Reference
To create an external reference, execute the following steps.
1. Open all workbooks.
2. In the Company workbook, select cell B2 and type the equal sign =
3. On the View tab, in the Window group, click Switch Windows.
4. Click North.
5. In the North workbook, select cell B2.
6. Type a +
7. Repeat steps 3 to 6 for the Mid workbook.
8. Repeat steps 3 to 5 for the South workbook.
9. Remove the $ symbols in the formula of cell B2.
Result:
10. Copy the formula to the other cells.
Alert
Close all workbooks.
Change a number in the workbook of a division.
Close all workbooks again.
Open the Company workbook.
A.
To update all links, click Enable Content.
B.
To not update the links, click the X.
Note: if you see another alert, click Update or Don't Update.
Edit Links
On the Data tab, in the Queries & Connections group, click Edit Links to launch the Edit Links dialog box.
1. If you didn't update the links, you can still update the links here.
Select a workbook and click Update Values to update the links to this workbook.
Note how the Status changes to OK.
2. If you don't want to display the alert and update the links automatically, Click Startup Prompt, select the third option, and click OK.
Hyperlinks
Existing File or Web Page | Place in This Document | Hyperlink Function
Use the 'Insert Hyperlink' dialog box in Excel to create a hyperlink to an existing file, a web page or a place in this document.
You can also use the HYPERLINK function.
Existing File or Web Page
To create a hyperlink to an existing file or web page, execute the following steps.
1. Select cell A1.
2. On the Insert tab, in the Links group, click Link.
The 'Insert Hyperlink' dialog box appears.
3a.
To create a hyperlink to an existing file, select a file (use the Look in drop-down list, if necessary).
3b.
To create a hyperlink to a web page, type the Text to display, the Address, and click OK.
Result:
Note: if you want to change the text that appears when you hover over the link, click ScreenTip.
Place in This Document
To create a hyperlink to a place in this document, execute the following steps.
1. Select cell A2.
2. On the Insert tab, in the Links group, click Link.
The 'Insert Hyperlink' dialog box appears.
3. Click 'Place in This Document' under Link to.
4. Type the Text to display, the cell reference, and click OK.
Result:
Note: if you want to change the text that appears when you hover over the hyperlink, click ScreenTip.
Hyperlink Function
You can also use the HYPERLINK function in Excel to create hyperlinks.
The HYPERLINK function has two arguments.
Note: instead of creating a hyperlink to a web page, create a hyperlink to an existing file.
For example, replace the first argument with "C:\Reports\sales2020.docx" and the second argument with "Open Report".Union and Intersect
This example illustrates how to use the union and intersect operators in Excel (borders below for illustration only).
1. The union operator (comma) adds two ranges.
Explanation: the SUM function reduces to =SUM(C4:D8) + SUM(D7:E11), 20.
2. The intersect operator (single space) returns the intersection of two ranges.
Explanation: the SUM function reduces to =SUM(D7:D8), 2.
Let's look at a few cool examples.
3. Excel automatically adds union operators (commas).
For example, type =SUM( and hold down CTRL to select the ranges below.
Note: press Enter to insert this function.
Excel adds the closing parenthesis for you.
4. You can use the intersect operator (space) to return the intersection of two named ranges.
Note: the named range Feb refers to the range B3:D3 and the named range Chocolate refers to the range B2:B13.
Percent Change
The percent change formula is used very often in Excel.
For example, to calculate the Monthly Change and Total Change.
1a.
Select cell C3 and enter the formula shown below.
1b.
Select cell C3. On the Home tab, in the Number group, apply a Percentage format.
1c.
Select cell C3, click on the lower right corner of cell C3 and drag it down to cell C13.
1d.
Check if everything went alright.
2a.
In a similar way, we can calculate the Total Change.
This time we fix the reference to cell B2. Select cell D3 and enter the formula shown below.
2b.
Select cell D3. On the Home tab, in the Number group, apply a Percentage format.
2c.
Select cell D3, click on the lower right corner of cell D3 and drag it down to cell D13.
2d.
Check if everything went alright.
Explanation: when we drag the formula down, the absolute reference ($B$2) stays the same, while the relative reference (B3) changes to B4, B5, B6, etc.
Add a Column
To add a column in Excel, right-click the column letter and click Insert.
When you insert a column or row, cell references update automatically.
1. First, select cell A10 below and press ALT + = to quickly sum a column of numbers.
2. Select column A.
Note: new columns will be added to the left of the selection.
3. Right click, and then click Insert.
Result:
To add multiple columns, execute the following steps.
4. Select multiple columns by clicking and dragging over the column headers.
For example, select column A and column B.
5. Right click, and then click Insert.
Result:
6. Double click cell D10.
Note: when you insert a column or row, cell references update automatically.
You can also use the Insert option on the Home tab.
7. For example, select column A, B, C and D.
8. On the Home tab, in the Cells group, click Insert, Insert Sheet Columns.
Result:
To quickly add a column, select a column and use the shortcut CTRL SHIFT +.
9. For example, select column F.
10. Press CTRL SHIFT +.
Result:
Note: to quickly add multiple columns, select multiple columns and use the same shortcut.
Absolute Reference
Cell | Range | Named Range | F4
An absolute reference in Excel refers to a fixed location on a worksheet.
When you copy a formula, an absolute reference never changes.
Cell
Let's start with fixing a reference to a cell.
1. Cell C2 below refers to cell B2 and cell E2. Both references are relative.
2. This is what happens when we copy the formula in cell C2 to cell C3.
3. Fix the reference to cell E2 by placing a $ symbol in front of the column letter and row number.
4. To quickly copy the formula in cell C2 to the other cells, select cell C2, click on the lower right corner of cell C2 and drag it down to cell C7.
Check:
Explanation: the absolute reference ($E$2) stays the same, while the relative reference (B2) changes to B3, B4, B5, B6 and B7.
Range
Sometimes you need to fix a reference to a range.
For example, when using the RANK function to rank numbers in a data set.
1. Cell C2 below refers to cell B2 and the range B2:B7. Both references are relative.
2. This is what happens when we copy the formula in cell C2 to cell C3.
3. Fix the reference to the range B2:B7 by placing $ symbols in front of the column letters and row numbers.
4. To quickly copy the formula in cell C2 to the other cells, select cell C2, click on the lower right corner of cell C2 and drag it down to cell C7.
Check:
Explanation: the absolute reference ($B$2:$B$7) stays the same, while the relative reference (B2) changes to B3, B4, B5, B6 and B7.
Named Range
Instead of using absolute range references, create a named range.
This way you can make your formulas easier to understand.
1. Select the range B2:B7, type a name in the Name box and press Enter.
2. Now you can use this named range in your formulas.
Select cell C2, enter the RANK function shown below and copy this formula to the other cells.
Check:
Note: visit our page about named ranges to learn more about this topic.
F4
Use the F4 key to quickly toggle between all 4 types of cell references.
1. For example, select cell C2 below, click in the formula bar and move the insertion point in or to the right of E2.
2. Press F4 to create an absolute reference.
3. Press F4 again to create a mixed reference where the column is relative and the row is absolute.
4. Press F4 again to create a mixed reference where the column is absolute and the row is relative.
Note: visit our page about cell references to learn more about mixed reference in Excel.
ADDRESS
The ADDRESS function in Excel creates a cell reference as text, based on a given row and column number.
1. The ADDRESS function below returns $E$8. The row number is 8 and the column number is 5.
2. The ADDRESS function below returns $G$3. The row number is 3 and the column number is 7.
3. The ADDRESS function returns a text value.
Use the INDIRECT function in Excel to convert this text value into a valid cell reference.
4. By default, the ADDRESS function creates an absolute reference.
To create a relative reference, use 4 for the third argument.
5. For example, use the ADDRESS function in Excel to find the cell address of the maximum value in a column.
Note: visit our page about locating the maximum value in a column for detailed instructions on how to create this formula.
6. Simply use the INDEX function in Excel to return a specific value in a two-dimensional range.
Explanation: 92 found at the intersection of row 3 and column 2 in the range E4:F7. Use INDEX and MACTH in Excel to perform advanced lookups.
DATEDIF
To calculate the number of days, months or years between two dates in Excel, use the DATEDIF function.
The DATEDIF function has three arguments.
1. Fill in "d" for the third argument to get the number of days between two dates.
Note: =A2-A1 produces the exact same result!
2. Fill in "m" for the third argument to get the number of months between two dates.
3. Fill in "y" for the third argument to get the number of years between two dates.
4. Fill in "yd" for the third argument to ignore years and get the number of days between two dates.
5. Fill in "md" for the third argument to ignore months and get the number of days between two dates.
6. Fill in "ym" for the third argument to ignore years and get the number of months between two dates.
Important note: the DATEDIF function returns the number of complete days, months or years.
This may give unexpected results when the day/month number of the second date is lower than the day/month number of the first date.
See the example below.
The difference is 6 years.
Almost 7 years! Use the following formula to return 7 years.
Today's Date
Today and Now | Static Date and Time
To enter today's date in Excel, use the TODAY function.
To enter the current date and time, use the NOW function.
To enter the current date and time as a static value, use keyboard shortcuts.
Today and Now
1. To enter today's date in Excel, use the TODAY function.
Note: the TODAY function takes no arguments.
This date will update automatically when you open the workbook on another date.
2. To enter the current date and time, use the NOW function.
Note: the NOW function takes no arguments.
This time will update automatically whenever the sheet is recalculated.
This happens when you make a change to any cell or when you open the workbook.
Press F9 to manually recalculate the workbook.
3. To enter the current time only, use the formula shown below and apply a time format.
Note: dates are stored as numbers in Excel and count the number of days since January 0, 1900. Times are handled internally as numbers between 0 and 1. Visit our page about date and time formats for more information.
Static Date and Time
1. To enter the current date as a static value, press CTRL + ; (semicolon).
Note: this date will not change when you open the workbook on another date.
2. To enter the current time as a static value, press CTRL + SHIFT + ; (semicolon).
Note: this time will not change when you make a change to a cell or when you open the workbook.
3. To enter the current date and time as a static value, simply press CTRL + ; (semicolon), enter a space and press CTRL + SHIFT + ; (semicolon).
Date and Time Formats
Dates and times in Excel can be displayed in a variety of ways.
To apply a Date or Time format, execute the following steps.
1. Select cell A1.
2. Right click, and then click Format Cells.
3. In the Category list, select Date, and select a Date format.
4. Click OK.
Note: to apply a Time format, in the Category list, select Time.
5. Dates are stored as numbers in Excel and count the number of days since January 0, 1900. Times are handled internally as numbers between 0 and 1. To clearly see this, change the number format of cell A1, B1 and C1 to General.
Note: apparently, 42544 days after January 0, 1900 is the same as June 23, 2016. 6:00 is represented as 0.25 (quarter through the day).
6. You can enter times as 6:00, but Excel displays this time as 6:00:00 AM in the formula bar.
AM is used for times in the night and morning.
PM is used for times in the afternoon and evening.
7. Change the number format of cell C1 to Date only.
Note: cell C1 still contains the number 42544.25. We only changed the appearance of the number, not the number itself.
Calculate Age
To calculate the age of a person in Excel, use DATEDIF and TODAY.
The DATEDIF function has three arguments.
1. Enter the date of birth into cell A2.
2. Enter the TODAY function into cell B2 to return today's date.
3. The DATEDIF function below calculates the age of a person.
Note: fill in "y" for the third argument to get the number of complete years between the date of birth and today's date.
4. Calculate the age of a person without displaying today's date.
5. Calculate the age of a person on a specific date.
Note: the DATE function accepts three arguments: year, month and day.
6. The age formula below calculates the age of a person in years, months and days.
Note: fill in "ym" for the third argument to ignore years and get the number of months between two dates.
Fill in "md" for the third argument to ignore months and get the number of days between two dates.
Use the & operator to join strings.
Time Difference
Simple Formula | Time Difference Formula | Time Difference in Hours as Decimal Value | Time Sheet
Calculating the difference between two times in Excel can be tricky.
Times are handled internally as numbers between 0 and 1.
Simple Formula
Let's start with a simple formula that calculates the difference between two times in the same day.
1. Simply subtract the start time from the end time.
Note: AM is used for times in the night and morning.
PM is used for times in the afternoon and evening.
Change the Time format to display a time with or without AM/PM.
2. Change the number format of the values in cell A2, B2 and C2 to General.
Note: times are handled internally as numbers between 0 and 1. For example, 6:00 AM is represented as 0.25 (quarter through the day).
Time Difference Formula
The simple formula shown above doesn't work if the start time is before midnight and the end time is after midnight.
1. Times that are negative show as ######.
2. To clearly see this, change the number format of the values in cell A2, B2 and C2 to General.
3. The time difference formula below always works.
Explanation: if the end time is greater than or equal to the start time, simply subtract the start time from the end time.
If not, add 1 (full day) to the end time to represent a time on the next day and subtract the start time.
Time Difference in Hours as Decimal Value
To calculate the difference between two times in hours as a decimal value, multiply the previous formula by 24 and change the number format to General.
1. The formula below does the trick.
Time Sheet
Calculate total hours, regular hours and overtime hours with our timesheet calculator.
Weekdays
WEEKDAY | NETWORKDAYS | WORKDAY | NETWORKDAYS.INTL | Fill Weekdays | WORKDAY.INTL | Highlight Weekdays
Use WEEKDAY, NETWORKDAYS and WORKDAY to create cool weekday formulas in Excel.
Are you ready to improve your Excel skills?
WEEKDAY
The WEEKDAY function in Excel returns a number from 1 (Sunday) to 7 (Saturday) representing the day of the week of a date.
1. The WEEKDAY function below returns 2. 12/22/2025 falls on a Monday.
2. You can also use the TEXT function to display the day of the week.
3. Or create a custom date format (dddd) to display the day of the week.
Cell A1 still contains a date.
NETWORKDAYS
The NETWORKDAYS function in Excel returns the number of workdays between two dates.
NETWORKDAYS excludes weekends (Saturday and Sunday).
1. The NETWORKDAYS function below returns 11. There are 11 workdays between 12/17/2025 and 12/31/2025.
Explanation: the NETWORKDAYS function includes the start date and the end date.
The calendar below helps you understand this formula.
Simply count the number of circles.
2. If you supply a list of holidays, the NETWORKDAYS function also excludes holidays.
Explanation: simply count the number of circles in the calendar below.
WORKDAY
The WORKDAY function in Excel returns the date before or after a specified number of workdays.
WORKDAY excludes weekends (Saturday and Sunday).
1. The WORKDAY function below returns the date 1/1/2026.
Explanation: the WORKDAY function does not include the start date.
The calendar below helps you understand this formula.
There are 11 circles.
2. If you supply a list of holidays, the WORKDAY function also excludes holidays.
Explanation: there are 11 circles in the calendar shown below.
NETWORKDAYS.INTL
Use NETWORKDAYS.INTL instead of NETWORKDAYS to specify different weekend days.
Use a string of 0's and 1's (third argument) to specify which days are weekend days.
1. The NETWORKDAYS.INTL function below returns 8.
Explanation: the first 0 tells Excel that Monday is not a weekend day.
The second 0 tells Excel that Tuesday is not a weekend day, etc.
In this example, Friday, Saturday and Sunday are weekend days.
The calendar below helps you understand this formula.
Fill Weekdays
To quickly create a list of dates excluding Saturdays and Sundays, execute the following steps.
1. For example, enter the date 12/17/2025 into cell A1.
2. Select cell A1 and drag the fill handle down.
AutoFill automatically fills in the days.
3. Instead of filling in days, use the AutoFill options to fill in weekdays (ignoring weekend days).
Note: use WORKDAY.INTL to exclude different weekend days and holidays.
Read on.
WORKDAY.INTL
Use WORKDAY.INTL instead of WORKDAY to specify different weekend days.
Let's create a list of dates excluding Mondays, Sundays and holidays.
1. Enter the date 12/17/2025 into cell A1 and specify a list of holidays (E1:E2).
2. Enter the WORKDAY.INTL function shown below.
Explanation: use a string of 0's and 1's (third argument) to specify which days are weekend days.
The first 1 tells Excel that Monday is a weekend day.
The second 0 tells Excel that Tuesday is not a weekend day, etc.
In this example, Monday and Sunday are weekend days.
3. Select cell A2 and drag the fill handle down.
Explanation: the calendar below helps you understand this formula.
Conclusion: this formula automatically skips Mondays, Sundays and holidays.
Pretty cool.
Highlight Weekdays
You can use conditional formatting in Excel to highlight dates that are weekdays (Monday, Tuesday, Wednesday, Thursday or Friday).
1. For example, select the range A1:A8.
2. On the Home tab, in the Styles group, click Conditional Formatting.
3. Click New Rule.
4. Select 'Use a formula to determine which cells to format'.
5. Enter the formula =AND(WEEKDAY(A1)>1,WEEKDAY(A1)<7)
6. Select a formatting style and click OK.
Result.
Excel highlights all weekdays.
Explanation: always write the formula for the upper-left cell in the selected range.
Excel copies the formula to the other cells.
Use the formula =OR(WEEKDAY(A1)=1,WEEKDAY(A1)=7) to highlight weekend dates.
Days until Birthday
To calculate the number of days until your birthday in Excel, execute the following steps.
1. Enter the date of birth into cell B2.
2. Enter the TODAY function into cell C2 to return today's date.
3. The most difficult part in order to get the number of days until your birthday is to find your next birthday.
The formula below does the trick.
Explanation: The DATE function accepts three arguments: year, month and day.
We used the DATEDIF function to find the number of complete years ("y") between Date of Birth and Today.
In this example, DATEDIF(B2,C2,"y") equals 42. If 42 complete years have passed since your date of birth (in other words, you have already celebrated your 42nd birthday), your next birthday will be 42 + 1 = 43 years after your date of birth.
4. Next, we use the DATEDIF function to find the number of days ("d") between Today and Next Birthday.
Conclusion: Sharon's birthday is in 32 days.
If you have a list of names and birthdates, you can use Excel to highlight upcoming birthdays.
This is pretty cool.
5. For example, the formula below calculates how many days are left until Emily's birthday.
Note: this formula isn't new.
To create this formula, take the formula from step 4 and replace D2 with the formula from step 3. Next, replace C2 with $F$1.
6. Double click the lower right corner of cell C2 to quickly copy the formula to the other cells.
Explanation: the absolute reference ($F$1) stays the same, while the relative reference (B2) changes to B3, B4, etc.
Visit our page about absolute reference to learn more about this topic.
7. To highlight upcoming birthdays within a week (green) or within a day (red), you can use conditional formatting in Excel.
8. This is what the spreadsheet will look like tomorrow.
Tip: visit our page about conditional formatting to learn more about this topic.
You can download the Excel file (right side of this page) to see the applied conditional formatting rules.
Last Day of the Month
To get the date of the last day of the month in Excel, use the EOMONTH (End of Month) function.
1. The EOMONTH function below returns the last day of the month.
Note: the EOMONTH function returns the serial number of the date.
Apply a Date format to display the date.
2. The EOMONTH function below returns the same date.
Use the DATE function in Excel to hardcode a date.
Let's kick it up a notch! Use the second argument of the EOMONTH function to specify a number of months in the future or in the past.
3. The EOMONTH function below returns the last day of the next month.
4. The EOMONTH function below returns the last day of the previous month.
5. The EOMONTH function below returns the last day of the month, 8 months in the past!
Explanation: = 6 - 8 = -2 = October (-2 + 12 = 10) in 2015!
6. Use EOMONTH and TODAY to return the last day of the current month.
Note: today is January 15th, 2022.
7. Finally, to find the first day of the month in Excel, simply use DATE, YEAR and MONTH.
Explanation: the DATE function accepts three arguments: year, month and day.
Use YEAR to get the year of a date.
Use MONTH to get the month of a date.
Add or Subtract Time
Add Hours, Minutes and Seconds | Add Up Times | Subtract Minutes | Time Difference
Use the TIME function in Excel to add or subtract hours, minutes and seconds.
To add up times in Excel, simply use the SUM function.
Add Hours, Minutes and Seconds
Remember, to enter a time, use the ":" (colon).
1. Enter a time into cell A1.
2. To add 2 hours and 30 minutes to this time, enter the formula shown below.
Explanation: the TIME function has 3 arguments.
First, use HOUR, MINUTE and SECOND to create the time entered in cell A1. Next, add 2 hours and 30 minutes.
To change the Time format, execute the following steps.
3. Select cell B1.
4. Right click, and then click Format Cells (or press CTRL + 1).
5. In the Category list, select Time, and select a Time format.
6. Click OK.
7. Enter a time into cell A1 (use 2 colons to include seconds).
8. To add 10 seconds to this time, enter the formula shown below.
Note: we changed the Time format to 13:30:55 (see step 5).
Add Up Times
To add up times in Excel, simply use the SUM function.
To display a total of more than 24 hours, change the Time format.
1. For example, task A requires 8 hours to complete, task B requires 4 hours and 30 minutes to complete, etc.
2. To calculate the total duration, simply use the SUM function.
3. Change the duration of task D from 5 hours to 7 hours.
To display a total of more than 24 hours, execute the following steps.
4. Select cell B6.
5. Right click, and then click Format Cells (or press CTRL + 1).
6. Select the Custom category.
7. Type the following number format code: [h]:mm
8. Click OK.
Note: visit our page about Date and Time formats to learn more about this topic.
Subtract Minutes
To subtract hours, minutes or seconds from a time, use the TIME function (and HOUR, MINUTE and SECOND).
1. Enter a time into cell A1.
2. To subtract 33 minutes from this time, enter the formula shown below.
Time Difference
Calculating the difference between two times in Excel can be tricky.
1. To calculate the difference between two times in the same day, simply subtract the start time from the end time.
Note: we changed the Time format to 13:30 (see step 5 under "Add Hours, Minutes and Seconds").
2. This simple formula doesn't work if the start time is before midnight and the end time is after midnight.
The Time Difference formula below always works.
3. The formula below calculates the difference between two times in hours as a decimal value.
Note: visit our page about Time Difference to understand the logic behind these formulas.
Quarter
An easy formula that returns the quarter for a given date.
There's no built-in function in Excel that can do this.
1. Enter the formula shown below.
Explanation: ROUNDUP(x,0) always rounds x up to the nearest integer.
The MONTH function returns the month number of a date.
In this example, the formula reduces to =ROUNDUP(5/3,0), =ROUNDUP(1.666667,0), 2. May is in Quarter 2.
2. Let's see if this formula works for all months.
Explanation: now it's not difficult to see that the first three values (months) in column B are rounded up to 1 (Quarter 1), the next three values (months) in column B are rounded up to 2 (Quarter 2), etc.
3. You can also use MONTH and CHOOSE in Excel to return the quarter for a given date.
Explanation: in this formula, MONTH(A1) returns 5. As a result, the CHOOSE function returns the fifth choice.
May is in Quarter 2.
4. This formula works for all months.
Explanation: in this formula, MONTH(A1) returns 1. As a result, the CHOOSE function returns the first choice.
January is in Quarter 1.
To return the fiscal quarter for a given date, slightly adjust the list of values.
5. For example, if your company's fiscal year starts in April, use the following formula.
Note: green font for illustration only.
6. For example, if your company's fiscal year starts in October, use the following formula.
Tip: to quickly copy the formula in cell B1 to the other cells, select cell B1 and double click on the lower right corner of cell B1 (the fill handle).
Day of the Year
An easy formula that returns the day of the year for a given date.
There's no built-in function in Excel that can do this.
1. To get the year of a date, use the YEAR function.
2. Use the DATE function below to return January 1, 2016. The DATE function accepts three arguments: year, month and day.
3. The formula below returns the day of the year.
Explanation: dates and times are stored as numbers in Excel and count the number of days since January 0, 1900. June 23, 2016 is the same as 42544. January 1, 2016 is the same as 42370. Subtracting these numbers and adding 1 gives the day of the year.
42544 - 42370 + 1 = 174 + 1 = 175.
4. 2016 is a leap year.
A leap year has 366 days.
December 31st is the last day of the year.
We can check this.
5. Bonus.
The formula below calculates the number of days in a year.
Conclusion: 2012, 2016, 2020 and 2024 are leap years.
Days between Dates
To calculate the number of days between two dates in Excel, subtract the start date from the end date, use DAYS or use DATEDIF.
1. Subtract the start date (A1) from the end date (A2).
2. Use the DAYS function in Excel 2013 or later.
The first argument is the end date.
The second argument is the start date.
3. Use the DATEDIF function.
The first argument is the start date.
The second argument is the end date.
Fill in "d" for the third argument to get the number of days between two dates.
Tip: visit our page about the DATEDIF function to find out how to get the number of weeks, months or years between two dates in Excel.
4. The formula below returns the same number of days.
Use the DATE function in Excel to hardcode a date.
Explanation: the DATE function accepts three arguments: year, month and day.
5. Bonus.
Use the NETWORKDAYS function to return the number of workdays between two dates in Excel.
NETWORKDAYS excludes weekends (Saturday and Sunday).
Explanation: the NETWORKDAYS function includes the start date and the end date.
The calendar below helps you understand this formula.
Simply count the number of circles.
Tip: visit our page about weekdays to learn more about the NETWORKDAYS function.
Separate Strings
Formulas | Flash Fill | TextSplit
To separate strings in Excel, use RIGHT, LEN, FIND and LEFT.
If you're not a formula hero, use Flash Fill to split text strings in Excel.
Formulas
The problem we are dealing with is that we need to tell Excel where we want to separate the string (see picture below).
In case of Smith, Mike the comma is at position 6 while in case of Williams, Janet the comma is at position 9.
1. To get the first name, use the formula below.
Explanation: to find the position of the comma, use the FIND function (position 6).
To get the length of a string, use the LEN function (11 characters).
=RIGHT(A2,LEN(A2)-FIND(",",A2)-1) reduces to =RIGHT(A2,11-6-1).
=RIGHT(A2,4) extracts the 4 rightmost characters and gives the desired result (Mike).
2. To get the last name, use the following formula.
Explanation: to find the position of the comma, use the FIND function (position 6).
=LEFT(A2,FIND(",", A2)-1) reduces to =LEFT(A2,6-1).
=LEFT(A2,5) extracts the 5 leftmost characters and gives the desired result (Smith).
3. Select the range B2:C2 and drag it down.
There's an even quicker way to achieve this result.
Read on.
Flash Fill
If you're not a formula hero, use Flash Fill to split text strings in Excel.
1. First, tell Excel what you want to do by entering the first name Mike into cell B2.
2. On the Data tab, in the Data Tools group, click Flash Fill (or press CTRL + E).
Result:
That's pretty cool!
3. Next, enter the last name Smith into cell C2.
4. On the Data tab, in the Data Tools group, click Flash Fill (or press CTRL + E).
Result:
Note: one drawback when using Flash Fill is that the output will not automatically update when the source data changes.
Create formulas (see first paragraph) to overcome this limitation.
TextSplit
If you have Excel 365, use the new TEXTSPLIT function to split text into rows or columns using delimiters.
Note: the TEXTSPLIT function, entered into cell B2, fills multiple cells (B2 and C2).
Wow! This behavior is called spilling.
Count Words
Use TRIM, LEN, SUBSTITUTE and SUMPRODUCT in Excel to count words.
First, let's count the total number of words in a cell or range of cells.
1. The TRIM function below returns a string with only regular spaces.
2. To get the length of this string, add the LEN function.
3. The SUBSTITUTE function below returns a string without spaces.
4. To get the length of this string, add the LEN function.
5. To count the total number of words in cell A1, subtract the length of the string without spaces (formula from step 4) from the length of the string with only regular spaces (formula from step 2) and add 1.
Conclusion: to count the total number of words in a cell, simply count the number of spaces and add 1 to this result.
1 space means 2 words, 2 spaces means 3 words, etc.
6. To count the total number of words in the range A1:A2, add the SUMPRODUCT function and replace A1 with A1:A2.
Note: visit our page about the SUMPRODUCT function to learn more about this Excel function.
Finally, let's count how many times a specific word occurs in a cell or range of cells.
This trick is pretty cool.
7. The LEN function below returns the length of the original text in cell A1.
8. The SUBSTITUTE function below returns the string without the word "dog".
9. The LEN function below returns the length of this string.
10. Subtract the length of the string without the word "dog" (formula from step 9) from the length of the original text in cell A1 (formula from step 7).
Conclusion: after removing the word "dog" from the original text, 12 characters are missing.
11. We know the length of the word "dog" (3), so the word "dog" occurs 12 / 3 = 4 times in cell A1.
12. To count how many times the word "dog" occurs in the range A1:A2, add the SUMPRODUCT function and replace A1 with A1:A2.
13. Use the COUNTIF function in Excel to count the number of cells that contain a specific word.
Note: an asterisk (*) matches a series of zero or more characters.
Visit our page about the COUNTIF function to learn more about this great Excel function.
Text to Columns
To separate the contents of one Excel cell into separate columns, you can use the 'Convert Text to Columns Wizard'.
For example, when you want to separate a list of full names into last and first names.
1. Select the range with full names.
2. On the Data tab, in the Data Tools group, click Text to Columns.
The following dialog box appears.
3. Choose Delimited and click Next.
4. Clear all the check boxes under Delimiters except for the Comma and Space check box.
5. Click Finish.
Note: This example has commas and spaces as delimiters.
You may have other delimiters in your data.
Experiment by checking and unchecking the different check boxes.
You get a live preview of how your data will be separated.
Result:
FIND
Use the FIND function in Excel to find the position of a substring in a string.
The FIND function is case-sensitive.
1. The FIND function below finds the string "ro" at position 4.
2. The FIND function below finds the string "Excel" at position 11.
3. The FIND function is case-sensitive.
The FIND function below returns the #VALUE! error because it cannot find the string "excel".
The FIND function has a 3rd optional argument.
You can use this argument to indicate the position, counting from the left, at which you want to start searching.
4. The FIND function below finds the string "o" at position 5.
5. The FIND function below starts searching at position 6 and finds the string "o" at position 7.
Note: the SEARCH function in Excel is case-insensitive and supports wildcards.
SEARCH
Use the SEARCH function in Excel to find the position of a substring in a string.
The SEARCH function is case-insensitive and supports wildcards.
1. The SEARCH function below finds the string "ro" at position 4.
2. The SEARCH function is case-insensitive.
The SEARCH function below finds the string "excel", "Excel", "EXCEL", "EXcel", etc.
The SEARCH function supports wildcard characters.
A question mark (?) matches exactly one character.
An asterisk (*) matches a series of zero or more characters.
3. The SEARCH function below finds the string "2019", "2018", "2017", etc.
4. The SEARCH function below finds the string "Microsoft Excel 2019", "Microsoft Word 2019", "Microsoft Access 2019", etc.
The SEARCH function has a 3rd optional argument.
You can use this argument to indicate the position, counting from the left, at which you want to start searching.
5. The SEARCH function below finds the string "o" at position 5.
6. The SEARCH function below starts searching at position 6 and finds the string "o" at position 7.
Change Case
To change the case of text in Excel, use LOWER, UPPER or PROPER.
If you're not a formula hero, use Flash Fill to change case in Excel.
1. Use the LOWER function in Excel to change the case of text to lowercase.
Note: double click the lower right corner of cell B1 to quickly copy this formula to the other cells.
2. Use the UPPER function in Excel to change the case of text to uppercase.
3. Use the PROPER function in Excel to change the first letter of each word to uppercase and all other letters to lowercase.
If you're not a formula hero, use Flash Fill to change the case of text in Excel.
In the example below, we are looking for a mix of proper case and uppercase.
4. First, tell Excel what you want to do by entering the correct city (proper case) and state abbreviation (uppercase) into cell B1.
5. On the Data tab, in the Data Tools group, click Flash Fill (or press CTRL + E).
Result:
Note: Flash Fill is not perfect and sometimes needs a little help.
Visit our page about Flash Fill to learn more about this great Excel tool.
Remove Spaces
The TRIM function in Excel removes leading spaces, extra spaces and trailing spaces.
Use the SUBSTITUTE function to remove all spaces or non-breaking spaces.
1. The TRIM function below removes 2 leading spaces, 3 extra spaces and 2 trailing spaces.
Note: the TRIM function does not remove single spaces between words.
2. To get the length of a string, use the LEN function.
Explanation: the LEN function counts 2 spaces, 2 characters, 4 spaces, 3 characters and 2 spaces.
3. You can use the SUBSTITUTE function to remove all spaces.
Note: the SUBSTITUTE function substitutes spaces (second argument) with empty strings (third argument).
Text imported from other applications may contain ASCII characters.
The CLEAN function removes the first 32 non-printable ASCII characters (codes 0 through 31).
4. The CLEAN function below removes a non-printable character, CHAR(7).
5. Simply combine CLEAN and TRIM to remove non-printable characters and spaces.
6. The CLEAN function removes line breaks.
To enter a line break, press ALT + ENTER.
7. You can also use the SUBSTITUTE function to remove a line break, CHAR(10), and replace it with something else.
For example, a comma and a space.
The CLEAN function doesn't remove all ASCII characters.
Simply use the SUBSTITUTE function to remove other ASCII characters.
8. First, find out the code number of the character.
9. Next, use SUBSTITUTE and CHAR to return the text string without this character.
10. If your text contains non-breaking spaces, CHAR(160), the TRIM function doesn't work.
11. You can use the SUBSTITUTE function to substitute non-breaking spaces, CHAR(160) with normal spaces, CHAR(32).
Don't forget to add a TRIM function to remove the extra spaces.
Compare Text
This example shows two ways to compare text strings in Excel.
One is case-sensitive and one is case-insensitive.
1. Use the EXACT function (case-sensitive).
Explanation: the string "Frog" in cell A1 and the string "frog" in cell B1 are not exactly equal to each other (first letter in uppercase and first letter in lowercase).
2. Use the formula =A1=B1 (case-insensitive).
Explanation: this formula ignores lowercase and uppercase differences.
As a result, the first six formulas return TRUE.
3. Add the IF function to replace TRUE and FALSE with a word or message.
The formula below uses the EXACT function (see step 1).
4. Do you want to compare two or more columns by highlighting the differences in each row? Visit our page about Row Differences.
Substitute vs Replace
If you know the text to be replaced, use the SUBSTITUTE function in Excel.
If you know the position of the text to be replaced, use the REPLACE function.
1. The SUBSTITUTE function below replaces 2013 with 2016.
2. The 4th argument (optional) specifies which occurrence you want to replace.
The SUBSTITUTE function below only replaces the second occurrence.
3. The SUBSTITUTE function below substitutes spaces with empty strings.
In other words, this formula removes all spaces.
4. The REPLACE function below starts at position 4 and replaces 2 characters with -P.
5. The REPLACE function below starts at position 1 and replaces 3 characters with an empty string.
In other words, this formula removes the first 3 characters.
You can also use Excel's Find and Replace feature to quickly find specific text and replace it with other text.
6. For example, select the range A1:A10.
7. On the Home tab, in the Editing group, click Find & Select.
8. Click Replace.
9. Type the text you want to find (TX) and replace it with (CA).
10. Click 'Replace All'.
Result.
Excel replaces all occurrences of TX with CA.
TEXT
When joining text and a number, use the TEXT function in Excel to format that number.
This page contains many easy to follow TEXT function examples.
1a.
For example, without using the TEXT function this would be the result.
1b.
With the TEXT function.
Note: #,## is used to add comma's to large numbers.
Always enclose the format code (second argument) in double quotation marks.
2. Here's another example.
Apply a percentage format.
Note: use 0 to display the nearest integer value.
Use 0.0 for one decimal place.
Use 0.00 for two decimal places, etc.
3. And another example.
Format a date.
Note: use less/more m's, d's and y's to change the appearance of the date.
4. For example, use the TEXT function to only display the day of the week.
This time we simply use the TEXT function without adding text.
5. Use the TEXT function to display a number in scientific notation.
6. Use the TEXT function to display a fraction and add the TRIM function to remove the leading space.
Simply use the 'Format Cells' dialog box to find the right format code.
7a.
For example, enter a time into cell A1 and select cell A1.
7b.
Right click, and then click Format Cells (or press CTRL + 1).
7c.
Select the Custom category and click a format code.
Next, click in the Type box, select the format code and press CTRL + c to copy this code.
Note: Excel gives you a live preview of how the time will be formatted (under Sample).
7d.
Click Cancel.
7e.
Paste (CTRL + v) the format code into your TEXT function.
Don't forget to enclose the format code in double quotation marks.
CONCATENATE
Use CONCATENATE, CONCAT, TEXTJOIN or the & operator in Excel to concatenate (join) two or more text strings.
1. The CONCATENATE function below concatenates the string in cell A1 and the string in cell B1.
2. Use the & operator to produce the exact same result.
3. The CONCATENATE function below concatenates the string in cell A1, the string " and " (enclose text in double quotation marks) and the string in cell B1.
4. Use the & operator to produce the exact same result.
5. The CONCATENATE function below concatenates the string in cell A1, a space and the string in cell B1.
6. Use the & operator to produce the exact same result.
The CONCAT function in Excel 2016 or later produces the exact same result as the CONCATENATE function.
Simply replace CONCATENATE with CONCAT in the formulas shown above.
7. The CONCAT function can also join a range of strings.
If you don't need a delimiter (space, comma, dash, etc.) this can be useful.
The TEXTJOIN function in Excel 2016 or later joins a range of strings using a delimiter (first argument).
8. First, take a look at all the extra spaces in column E below when you drag the CONCATENATE function in cell E2 down to cell E11.
9. The beauty of the TEXTJOIN function is that it can ignore empty cells (if the second argument is set to TRUE).
10. When using the CONCATENATE function, use the TEXT function to format numbers.
Note: use 0 to display the nearest integer value.
Use 0.0 for one decimal place.
Use 0.00 for two decimal places, etc.
Visit our page about the TEXT function for many more examples.
11. Use CHAR(10) to insert a line break.
Note: don't forget to enable text wrapping.
On the Home tab, in the Alignment group, click Wrap Text.
12. Let's take a look at one more cool example that uses the TEXTJOIN function.
First, the IF function below finds all members of Team 1.
Explanation: the IF function checks each cell in the named range Teams.
If equal to the value in cell E3, it returns the name from the named range Names, else it returns an empty string (two double quotes with nothing in between).
13. The IF function returns an array constant stored in Excel's memory.
Select the formula in the formula bar and press F9 to see this array constant.
14. Add the powerful TEXTJOIN function to concatenate these names.
Use a comma and space as the delimiter (first argument) and set the second argument to TRUE to ignore the empty strings.
Finish an array formula by pressing CTRL + SHIFT + ENTER.
Note: Excel adds the curly braces {}.
In Excel 365 or Excel 2021, finish by simply pressing Enter.
You won't see curly braces.
Mia, James and Sophia are in Team 1. Double click the lower right corner of cell F3 to quickly copy this formula to the other cells.
Substring
Mid | Left | Right | Substring between parentheses | Substring containing specific text | Flash Fill | Excel 365
There's no SUBSTRING function in Excel.
Use MID, LEFT, RIGHT, FIND, LEN, SUBSTITUTE, REPT, TRIM and MAX in Excel to extract substrings.
Mid
To extract a substring, starting in the middle of a string, use the MID function in Excel.
Explanation: the MID function starts at position 7 (O) and extracts 6 characters.
Left
To extract the leftmost characters from a string, use the LEFT function in Excel.
To extract a substring (of any length) before the dash, add the FIND function.
Explanation: the FIND function finds the position of the dash.
Subtract 1 from this result to extract the correct number of leftmost characters.
The formula shown above reduces to LEFT(A1,4-1).
Right
To extract the rightmost characters from a string, use the RIGHT function in Excel.
To extract a substring (of any length) after the dash, add LEN and FIND.
Explanation: the LEN function returns the length of the string.
The FIND function finds the position of the dash.
Subtract these values to extract the correct number of rightmost characters.
The formula shown above reduces to RIGHT(A1,6-4).
Substring between parentheses
To extract a substring between parentheses (or braces, brackets, slashes, etc.), use MID and FIND in Excel.
1. The formula below is almost perfect.
Explanation: the FIND function finds the position of the opening parenthesis.
Add 1 to find the start position of the substring.
The formula shown above reduces to MID(A1,6+1,2).
This MID function always extracts 2 characters.
2. Replace the 2 (third argument) with a formula that returns the length of the substring.
Explanation: subtract the position of the opening parenthesis and the value 1 from the position of the closing parenthesis to find the correct length of the substring.
Substring containing specific text
To extract a substring containing specific text (for example, the @ symbol), use SUBSTITUTE, REPT, MID, FIND, TRIM and MAX in Excel.
1. First, use SUBSTITUTE and REPT to substitute a single space with 100 spaces (or any other large number).
2. The MID function below starts 50 (1/2 * large number) positions before the position of the @ symbol and extracts 100 (large number) characters.
3. Use the TRIM function to remove the leading and the trailing spaces.
4. Put it all together.
Note: at step 2, the MID function starts 50 positions before the position of the @ symbol.
If the email address is the first word in the sentence (cell A3), this results in a negative start position.
In this case, the MAX function (see formula above) returns 1.
Flash Fill
If you're not a formula hero, use Flash Fill in Excel to automatically extract substrings.
Note: Excel does not insert formulas, if you change the text strings in column A, Excel will not update the numbers in Column B.
Excel 365
If you have Excel 365, use TEXTBEFORE or TEXTAFTER to extract substrings in Excel.
These functions are simple and powerful.
1. We used the formula below to extract a substring (of any length) before the dash.
2. The TEXTBEFORE function below produces the exact same result.
3. We used the formula below to extract a substring (of any length) after the dash.
4. The TEXTAFTER function below produces the exact same result.
5. We used the formula below to extract a substring between parentheses.
Combine TEXTBEFORE and TEXTAFTER to produce the exact same result.
6. First, use the TEXTAFTER function to extract the substring after the opening parenthesis.
7. Next, add the TEXTBEFORE function to extract the substring before the closing parenthesis.
VLOOKUP
Exact Match | Approximate Match | Vlookup Looks Right | First Match | Partial Match | Vlookup is Case-insensitive | Multiple Criteria | #N/A error | Multiple Lookup Tables | Index and Match | Table Magic | Xlookup
The VLOOKUP function is one of the most popular functions in Excel.
This page contains many easy to follow VLOOKUP examples.
Exact Match
Most of the time you are looking for an exact match when you use the VLOOKUP function in Excel.
Let's take a look at the arguments of the VLOOKUP function.
1. The VLOOKUP function below looks up the value 53 (first argument) in the leftmost column of the red table (second argument).
2. The value 4 (third argument) tells the VLOOKUP function to return the value in the same row from the fourth column of the red table.
Note: the Boolean FALSE (fourth argument) tells the VLOOKUP function to return an exact match.
If the VLOOKUP function cannot find the value 53 in the first column, it will return a #N/A error.
3. Here's another example.
Instead of returning the salary, the VLOOKUP function below returns the last name (third argument is set to 3) of ID 79.
Approximate Match
Let's take a look at an example of the VLOOKUP function in approximate match mode (fourth argument set to TRUE).
1. The VLOOKUP function below looks up the value 85 (first argument) in the leftmost column of the red table (second argument).
There's just one problem.
There's no value 85 in the first column.
2. Fortunately, the Boolean TRUE (fourth argument) tells the VLOOKUP function to return an approximate match.
If the VLOOKUP function cannot find the value 85 in the first column, it will return the largest value smaller than 85. In this example, this will be the value 80.
3. The value 2 (third argument) tells the VLOOKUP function to return the value in the same row from the second column of the red table.
Note: always sort the leftmost column of the red table in ascending order if you use the VLOOKUP function in approximate match mode (fourth argument set to TRUE).
Vlookup Looks Right
The VLOOKUP function always looks up a value in the leftmost column of a table and returns the corresponding value from a column to the right.
1. For example, the VLOOKUP function below looks up the first name and returns the last name.
2. If you change the column index number (third argument) to 3, the VLOOKUP function looks up the first name and returns the salary.
Note: in this example, the VLOOKUP function cannot lookup the first name and return the ID.
The VLOOKUP function only looks to the right.
No worries, you can use INDEX and MATCH in Excel to perform a left lookup.
First Match
If the leftmost column of the table contains duplicates, the VLOOKUP function matches the first instance.
For example, take a look at the VLOOKUP function below.
Explanation: the VLOOKUP function returns the salary of Mia Clark, not Mia Reed.
Partial Match
The VLOOKUP function supports wildcards for partial matches.
For example, take a look at the VLOOKUP function below.
Explanation: an asterisk (*) matches zero or more characters.
The VLOOKUP function matches the first instance that begins with "Jess".
Use "*"&G2 for an "ends with" match.
Use "*"&G2&"*" for a "contains" match.
Vlookup is Case-insensitive
The VLOOKUP function in Excel performs a case-insensitive lookup.
For example, the VLOOKUP function below looks up MIA (cell G2) in the leftmost column of the table.
Explanation: the VLOOKUP function is case-insensitive so it looks up MIA or Mia or mia or miA, etc.
As a result, the VLOOKUP function returns the salary of Mia Clark (first instance).
Use INDEX, MATCH and EXACT in Excel to perform a case-sensitive lookup.
Multiple Criteria
Do you want to look up a value based on multiple criteria? Use INDEX and MATCH in Excel to perform a two-column lookup.
Note: the array formula above looks up the salary of James Clark, not James Smith, not James Anderson.
#N/A error
If the VLOOKUP function cannot find a match, it returns a #N/A error.
1. For example, the VLOOKUP function below cannot find the value 28 in the leftmost column.
2. If you like, you can use the IFNA function to replace the #N/A error with a friendly message.
Note: the IFNA function was introduced in Excel 2013. If you're using Excel 2010 or Excel 2007, combine IF and ISNA or use IFERROR.
Multiple Lookup Tables
When using the VLOOKUP function in Excel, you can have multiple lookup tables.
You can use the IF function to check whether a condition is met, and return one lookup table if TRUE and another lookup table if FALSE.
1. Create two named ranges: Table1 and Table2.
2. Select cell E4 and enter the VLOOKUP function shown below.
Explanation: the bonus depends on the market (UK or USA) and the sales amount.
The second argument of the VLOOKUP function does the trick.
If UK, the VLOOKUP function uses Table1, if USA, the VLOOKUP function uses Table2. Set the fourth argument of the VLOOKUP function to TRUE to return an approximate match.
3. Press Enter.
4. Select cell E4, click on the lower right corner of cell E4 and drag it down to cell E10.
Note: for example, Walker receives a bonus of $1,500. Because we're using named ranges, we can easily copy this VLOOKUP function to the other cells without worrying about cell references.
Index and Match
Instead of using VLOOKUP, use INDEX and MATCH.
To perform advanced lookups, you'll need INDEX and MATCH.
Maybe this is one step too far for you at this stage, but it shows you one of the many other powerful formulas Excel has to offer.
Table Magic
Tables can make VLOOKUP formulas a lot easier.
In the example below, a single VLOOKUP function automatically looks up all country codes.
Note: visit our page about merging tables to learn how to create this VLOOKUP function and bring your Excel game to a new level.
Xlookup
If you have Excel 365 or Excel 2021, use XLOOKUP instead of VLOOKUP.
The XLOOKUP function is easier to use and has some additional advantages.
Tax Rates
This example teaches you how to calculate the tax on an income using the VLOOKUP function in Excel.
The following tax rates apply to individuals who are residents of Australia.
Taxable income |
Tax on this income |
0 - $18,200 |
Nil |
$18,201 - $37,000 |
19c for each $1 over $18,200 |
$37,001 - $87,000 |
$3,572 plus 32.5c for each $1 over $37,000 |
$87,001 - $180,000 |
$19,822 plus 37c for each $1 over $87,000 |
$180,001 and over |
$54,232 plus 45c for each $1 over $180,000 |
Example: if income is 39000, tax equals 3572 + 0.325 * (39000 - 37000) = 3572 + 650 = $4222
To automatically calculate the tax on an income, execute the following steps.
1. On the second sheet, create the named range Rates.
2. When you set the fourth argument of the VLOOKUP function to TRUE, the VLOOKUP function returns an exact match or if not found, it returns the largest value smaller than lookup_value (A2).
That's exactly what we want!
Explanation: Excel cannot find 39000 in the first column of Rates.
However, it can find 37000 (the largest value smaller than 39000).
As a result, it returns 3572 (col_index_num, the third argument, is set to 2).
3. Now, what's left is the remainder of the equation, + 0.325 * (39000 - 37000).
This is easy.
We can return 0.325 by setting col_index_num to 3 and return 37000 by setting col_index_num to 1. The complete formula below does the trick.
Note: when you set the fourth argument of the VLOOKUP function to TRUE, the first column of the table must be sorted in ascending order.
INDEX and MATCH
Match | Index | Index and Match | Two-way Lookup | Case-sensitive Lookup | Left Lookup | Two-column Lookup | Closest Match | Xlookup
Use INDEX and MATCH in Excel and impress your boss.
Instead of using VLOOKUP, use INDEX and MATCH.
To perform advanced lookups, you'll need INDEX and MATCH.
Match
The MATCH function returns the position of a value in a given range.
For example, the MATCH function below looks up the value 53 in the range B3:B9.
Explanation: 53 (first argument) found at position 5 in the range B3:B9 (second argument).
In this example, we use MATCH to return an exact match so we set the third argument to 0.
Index
The INDEX function below returns a specific value in a one-dimensional range.
Explanation: the INDEX function returns the 5th value (second argument) in the range E3:E9 (first argument).
Index and Match
Replace the value 5 in the INDEX function (see previous example) with the MATCH function (see first example) to lookup the salary of ID 53.
Explanation: the MATCH function returns position 5. The INDEX function needs position 5. It's a perfect combination.
If you like, you can also use the VLOOKUP function.
It's up to you.
However, you'll need INDEX and MATCH to perform advanced lookups, as we will see next.
Two-way Lookup
The INDEX function can also return a specific value in a two-dimensional range.
For example, use INDEX and MATCH in Excel to perform a two-way-lookup.
Case-sensitive Lookup
By default, the VLOOKUP function performs a case-insensitive lookup.
However, you can use INDEX, MATCH and EXACT in Excel to perform a case-sensitive lookup.
Note: the formula correctly looks up the salary of MIA Reed, not Mia Clark.
Left Lookup
The VLOOKUP function only looks to the right.
No worries, you can use INDEX and MATCH in Excel to perform a left lookup.
Note: when we drag this formula down, the absolute references ($E$4:$E$7 and $G$4:$G$7) stay the same, while the relative reference (A2) changes to A3, A4, A5, etc.
Two-column Lookup
Do you want to look up a value based on multiple criteria? Use INDEX and MATCH in Excel to perform a two-column lookup.
Note: the array formula above looks up the salary of James Clark, not James Smith, not James Anderson.
Closest Match
To find the closest match to a target value in a data column, use INDEX, MATCH, ABS and MIN in Excel.
Xlookup
If you have Excel 365 or Excel 2021, use XLOOKUP instead of INDEX and MATCH.
The XLOOKUP function is easier to use and has some additional advantages.
Two-way Lookup
To lookup a value in a two-dimensional range, use INDEX and MATCH in Excel.
Below you can find the sales of different ice cream flavors in each month.
1. To find the position of Feb in the range A2:A13, use the MATCH function.
The result is 2.
2. To find the position of Chocolate in the range B1:D1, use the MATCH function.
The result is 1.
3. Use these results and the INDEX function to find the sales of Chocolate in February.
Explanation: 217 found at the intersection of row 2 and column 1 in the range B2:D13.
4. Put it all together.
You can also lookup a value in a two-dimensional range without using INDEX and MATCH.
The following trick is pretty awesome.
5. Select the range A1:D13.
6. On the Formulas tab, in the Defined Names group, click Create from Selection.
7. Check Top row and Left column and click OK.
8. Excel created 12 + 3 = 15 named ranges! Simply select a range and look at the Name box.
9. Use the intersect operator (space) to return the intersection of two named ranges.
10. Create a dynamic two-way lookup.
Explanation: the INDIRECT functions convert the text strings ("Feb" in cell G2 and "Chocolate" in cell G3) into valid named ranges.
OFFSET
Return a Cell | Return a Range | Negative Offset
The OFFSET function in Excel returns a cell or range of cells that is a specified number of rows and columns from a cell or range of cells.
Return a Cell
First, let's use the OFFSET function in Excel to return a cell.
Here we go.
1. The OFFSET function below returns the cell that is 3 rows below and 2 columns to the right of cell A2. The OFFSET function returns a cell because the height and width are both set to 1.
Result:
The last 2 arguments of the OFFSET function are optional.
When height and width are omitted, the new reference has the same height and width as the starting reference (first argument).
2. For example, the OFFSET function below returns the cell that is 12 rows below and 0 columns to the right of cell A2.
Result:
Return a Range
Alright.
Let's now use the OFFSET function in Excel to return a range (two or more cells).
1. The OFFSET function below returns the 1 x 2 range that is 8 rows below and 1 column to the right of cell A2. The SUM function calculates the sum of this range.
Result:
The last 2 arguments of the OFFSET function are optional (as previously mentioned).
When height and width are omitted, the new reference has the same height and width as the starting reference (first argument).
2. For example, the OFFSET function below returns the range that is 4 rows below and 0 columns to the right of the range B2:C2. The SUM function calculates the sum of this range.
Result:
3. The OFFSET function below returns the range that is 4 rows below and 0 columns to the right of the range B2:C2. This time without a SUM function.
Result:
Note: before inserting this formula, select the range E8:F8 (or another range of the same size).
Finish by pressing CTRL + SHIFT + ENTER.
The formula bar indicates that this is an array formula by enclosing it in curly braces {}.
To delete this array formula, select the range E8:F8 and press Delete.
4. If you have Excel 365 or Excel 2021, simply select cell E8, enter the OFFSET function and press Enter.
Bye bye curly braces.
Note: the OFFSET function, entered into cell E8, fills multiple cells.
Wow! This behavior in Excel 365/2021 is called spilling.
Negative Offset
If you want to return a cell or range of cells that is a specified number of rows above or columns to the left, use negative numbers.
The OFFSET function below returns the cell that is 12 rows above and 1 column to the left of cell C14.
Result:
Case-sensitive Lookup
By default, the VLOOKUP function performs a case-insensitive lookup.
However, you can use INDEX, MATCH and EXACT in Excel to perform a case-sensitive lookup.
1. For example, the simple VLOOKUP function below returns the salary of Mia Clark.
However, we want to lookup the salary of MIA Reed (see cell G2).
2. The EXACT function in Excel returns TRUE if two strings are exactly the same.
The EXACT function below returns FALSE.
3. The EXACT function below returns TRUE.
4. Replace B8 with B3:B9.
Explanation: the range (array constant) created by the EXACT function is stored in Excel's memory, not in a range.
The array constant looks as follows:
{FALSE;FALSE;FALSE;FALSE;FALSE;TRUE;FALSE}
5. All we need is a function that finds the position of TRUE in this array constant.
MATCH function to the rescue! Finish by pressing CTRL + SHIFT + ENTER.
Explanation: TRUE (first argument) found at position 6 in the array constant (second argument).
In this example, we use the MATCH function to return an exact match so we set the third argument to 0. The formula bar indicates that this is an array formula by enclosing it in curly braces {}.
Do not type these yourself.
6. Use the INDEX function (two arguments) to return a specific value in a one-dimensional range.
In this example, the salary at position 6 (second argument) in the range D3:D9 (first argument).
7. Finish by pressing CTRL + SHIFT + ENTER.
Note: the formula correctly looks up the salary of MIA Reed, not Mia Clark.
8. If you have Excel 365 or Excel 2021, simply use the XLOOKUP function to perform a case-sensitive lookup.
Note: visit our page about the XLOOKUP function to learn more about this great new Excel function.
Left Lookup
The VLOOKUP function only looks to the right.
To look up a value in any column and return the corresponding value to the left, simply use INDEX and MATCH.
1. The MATCH function returns the position of a value in a given range.
Explanation: 104 found at position 4 in the range $G$4:$G$7.
2. Use this result and the INDEX function to return the 4th value in the range $E$4:$E$7.
3. Drag the formula in cell B2 down to cell B11.
Note: when we drag this formula down, the absolute references ($E$4:$E$7 and $G$4:$G$7) stay the same, while the relative reference (A2) changes to A3, A4, A5, etc.
4. If you have Excel 365 or Excel 2021, simply use the XLOOKUP function to perform a left lookup.
Note: the XLOOKUP function, entered into cell B2, fills multiple cells.
Wow! This behavior in Excel 365/2021 is called spilling.
Visit our page about the XLOOKUP function to learn more about this great new Excel function.
Locate Maximum Value
To find the maximum value in Excel, use the MAX function.
To find the cell address of the maximum value in a column, use MAX, MATCH and ADDRESS.
1. First, we use the MAX function to find the maximum value in column A.
2. Second, we use the MATCH function to find the row number of the maximum value.
Explanation: the MATCH function reduces to =MATCH(12,A:A,0), 7. The MATCH function returns the position of the maximum value in column A.
Set the third argument to 0 to return an exact match.
3. Finally, we use the ADDRESS function to return the cell address.
Explanation: the ADDRESS function in Excel creates a cell reference as text, based on a given row and column number.
The ADDRESS function reduces to =ADDRESS(7,1), $A$7.
INDIRECT
Cell Reference | Range Reference | Named Range | Worksheet Reference
Use the INDIRECT function in Excel to convert a text string into a valid reference.
You can use the & operator to create text strings.
Cell Reference
Use the INDIRECT function in Excel to convert a text string into a valid cell reference.
1. For example, take a look at the INDIRECT function below.
Explanation: =INDIRECT(A1) reduces to =INDIRECT("D1").
The INDIRECT function converts the text string "D1" into a valid cell reference.
In other words, =INDIRECT("D1") reduces to =D1.
2. The simple INDIRECT function below produces the exact same result.
3. Do we really need the INDIRECT function? Yes.
Without using the INDIRECT function, this would be the result.
4. Use the & operator to join the string "D" with the value in cell A1.
Explanation: the formula above reduces to =INDIRECT("D1").
Again, =INDIRECT("D1") reduces to =D1.
Range Reference
Use the INDIRECT function in Excel to convert a text string into a valid range reference.
For example, use SUM and INDIRECT.
Explanation: the formula above reduces to =SUM(INDIRECT("D3:D6")).
The INDIRECT function converts the text string "D3:D6" into a valid range reference.
In other words, =SUM(INDIRECT("D3:D6")) reduces to =SUM(D3:D6).
Named Range
Use the INDIRECT function in Excel to convert a text string into a valid named range.
1. For example, the AVERAGE function below uses the named range Scores.
Explanation: the named range Scores refers to the range D1:D3.
2. However, the AVERAGE function below returns an error.
Explanation: =AVERAGE("Scores") returns an error because Excel cannot calculate the average of a text string!
3. The INDIRECT function below does the trick.
Explanation: =AVERAGE(INDIRECT("Scores")) reduces to =AVERAGE(Scores).
Worksheet Reference
Use the INDIRECT function in Excel to create a dynamic worksheet reference.
1. This is what a simple worksheet reference looks like.
Note: cell A1 on Sheet1 contains the value 10. Cell A1 on Sheet2 contains the value 20. Cell A1 on Sheet3 contains the value 30.
2. On the Summary sheet, enter the INDIRECT function shown below.
Use the & operator to join the sheet name in cell A1 with "!A1".
Explanation: the formula above reduces to =INDIRECT("Sheet1!A1").
The INDIRECT function converts the text string "Sheet1!A1" into a valid worksheet reference.
In other words, =INDIRECT("Sheet1!A1") reduces to =Sheet1!A1.
3. If your sheet names contain spaces or other special characters, enclose the sheet name in single quotation marks.
Modify the INDIRECT function as shown below.
Two-column Lookup
This example teaches you how to perform a two-column lookup in Excel.
See the example below.
We want to look up the salary of James Clark, not James Smith, not James Anderson.
1. To join strings, use the & operator.
2. The MATCH function returns the position of a value in a given range.
Insert the MATCH function shown below.
3. Finish by pressing CTRL + SHIFT + ENTER.
Note: the formula bar indicates that this is an array formula by enclosing it in curly braces {}.
Do not type these yourself.
They will disappear when you edit the formula.
Explanation: the range (array constant) A2:A8&B2:B8 is stored in Excel's memory, not in a range.
The array constant looks as follows:
{"JamesSmith";"JamesAnderson";"JamesClark";"JohnLewis";"JohnWalker";"MarkReed";"RichardLopez"}
This array constant is used as an argument for the MATCH function, giving a result of 3 (JamesClark found at position 3).
4. Use this result and the INDEX function to return the 3rd value in the range C2:C8.
5. If you have Excel 365 or Excel 2021, simply use the XLOOKUP function to perform a two-column lookup.
Note: visit our page about the XLOOKUP function to learn more about this great new Excel function.
Closest Match
To find the closest match to a target value in a data column, use INDEX, MATCH, ABS and MIN in Excel.
Use the VLOOKUP function in Excel to find an approximate match.
1. The ABS function in Excel returns the absolute value of a number.
Explanation: C3-F2 equals -39. The ABS function removes the minus sign (-) from a negative number, making it positive.
The ABS function has no effect on 0 (zero) or positive numbers.
2. To calculate the differences between the target value and the values in the data column, replace C3 with C3:C9.
Explanation: the range (array constant) created by the ABS function is stored in Excel's memory, not in a range.
The array constant looks as follows:
{39;14;37;16;22;16;17}
3. To find the closest match, add the MIN function and finish by pressing CTRL + SHIFT + ENTER.
Note: the formula bar indicates that this is an array formula by enclosing it in curly braces {}.
Do not type these yourself.
The array constant is used as an argument for the MIN function, giving a result of 14.
4. All we need is a function that finds the position of the value 14 in the array constant.
MATCH function to the rescue! Finish by pressing CTRL + SHIFT + ENTER.
Explanation: 14 (first argument) found at position 2 in the array constant (second argument).
In this example, we use the MATCH function to return an exact match so we set the third argument to 0.
5. Use the INDEX function (two arguments) to return a specific value in a one-dimensional range.
In this example, the name at position 2 (second argument) in the range B3:B9 (first argument).
6. Finish by pressing CTRL + SHIFT + ENTER.
Note: in Excel 365 or Excel 2021, finish by simply pressing Enter.
You won't see curly braces.
Compare Two Columns
Display Duplicates | Unique Values in Each Column | Row by Row Comparison
To compare two columns, use IF, ISERROR and MATCH in Excel.
You can display the duplicates or the unique values.
Before we start: do you want to compare two columns by highlighting the unique values in each column? Visit our page about comparing two lists.
Display Duplicates
Let's start by comparing two columns and displaying the duplicates.
1. Display the duplicates in the first column (these values also occur in the second column).
Explanation: the MATCH function in cell C1 returns the number 5 (letter A found at position 5 in the range B1:B7).
As a result, the ISERROR function returns FALSE and the IF function returns the value in cell A1. The MATCH function in cell C4 returns a #N/A error (no letter D in the range B1:B7).
As a result, the ISERROR function returns TRUE and the IF function returns an empty string.
2. You can also display the duplicates in the second column.
Note: at step 1, we matched each value in the first column with the range in the second column.
At step 2, we match each value in the second column with the range in the first column.
Unique Values in Each Column
Do you want to compare two columns by displaying the unique values in each column? Simply swap the last 2 arguments of the IF function.
1. Display the unique values in the first column (these values do not occur in the second column).
Note: take a look at the second picture on this page to see that we swapped the last 2 arguments of the IF function.
2. You can also display the unique values in the second column.
Note: take a look at the third picture on this page to see that we swapped the last 2 arguments of the IF function.
Row by Row Comparison
For a quick row by row comparison, simply use the IF function in Excel.
1. The IF function in cell C1 below returns Match because the value in cell A1 is equal to the value in cell B1.
2. To perform a case-sensitive comparison, add the EXACT function.
3. Do you want to compare two columns by highlighting the differences in each row? Visit our page about Row Differences.
XLOOKUP
Exact Match | Not Found | Approximate Match | Left Lookup | Multiple Values | Horizontal Lookup | Last Match
If you have Excel 365 or Excel 2021, use XLOOKUP instead of VLOOKUP.
The XLOOKUP function is easier to use and has some additional advantages.
Exact Match
By default, the XLOOKUP function in Excel 365/2021 performs an exact match.
1. The XLOOKUP function below looks up the value 53 (first argument) in the range B3:B9 (second argument).
2. Next, it simply returns the value in the same row from the range E3:E9 (third argument).
3. Here's another example.
Instead of returning the salary, the XLOOKUP function below returns the last name (replace E3:E9 with D3:D9) of ID 79.
Not Found
If the XLOOKUP function cannot find a match, it returns a #N/A error.
1. For example, the XLOOKUP function below cannot find the value 28 in the range B3:B9.
2. Use the fourth argument of the XLOOKUP function to replace the #N/A error with a friendly message.
Approximate Match
Let's take a look at an example of the XLOOKUP function in approximate match mode.
1. The XLOOKUP function below looks up the value 85 (first argument) in the range B3:B7 (second argument).
There's just one problem.
There's no value 85 in this range.
2. Fortunately, the value -1 (fifth argument) tells the XLOOKUP function to find the next smaller value.
In this example, the value 80.
3. Next, it simply returns the value in the same row from the range C3:C7 (third argument).
Note: use 1 instead of -1 for the fifth argument to find the next larger value.
In this example, the value 90. The XLOOKUP function also works with unsorted data.
In this example, there's no need to sort the scores in ascending order.
Left Lookup
Instead of using INDEX and MATCH in Excel to perform a left lookup, simply use the XLOOKUP function.
For example, take a look at the XLOOKUP function below.
Explanation: the XLOOKUP function looks up the last name and returns the ID.
Multiple Values
The XLOOKUP function in Excel 365/2021 can return multiple values.
1. First, the XLOOKUP function below looks up the ID and returns the first name (nothing new).
2. Replace C6:C12 with C6:E12 to return the first name, last name and salary.
Note: the XLOOKUP function, entered into cell C3, fills multiple cells.
Wow! This behavior in Excel 365/2021 is called spilling.
Horizontal Lookup
Instead of using the HLOOKUP function in Excel to perform a horizontal lookup, simply use the XLOOKUP function.
Note: the XLOOKUP function, entered into cell B2, fills multiple cells.
Wow! This behavior in Excel 365/2021 is called spilling.
Last Match
By default, the XLOOKUP function performs a first to last search (nothing new).
To perform a last to first search, set the sixth argument to -1 (see example below).
Explanation: this XLOOKUP function returns the salary of Mia Reed, not Mia Clark.
PMT
PMT examples | PPMT and IPMT
The PMT function in Excel calculates the payment for a loan based on constant payments and a constant interest rate.
This page contains many easy to follow PMT examples.
PMT examples
Consider a loan with an annual interest rate of 6%, a 20-year duration, a present value of $150,000 (amount borrowed) and a future value of 0 (that's what you hope to achieve when you pay off a loan).
1. The PMT function below calculates the annual payment.
Note: if the fifth argument is omitted, it is assumed that payments are due at the end of the period.
We pay off a loan of $150,000 (positive, we received that amount) and we make annual payments of $13,077.68 (negative, we pay).
2. The PMT function below calculates the quarterly payment.
Note: we make quarterly payments, so we use 6%/4 = 1.5% for Rate and 20*4 = 80 for Nper (total number of periods).
3. The PMT function below calculates the monthly payment.
Note: we make monthly payments, so we use 6%/12 = 0.5% for Rate and 20*12 = 240 for Nper (total number of periods).
Consider an investment with an annual interest rate of 8% and a present value of 0. How much money should you deposit at the end of each year to have $1,448.66 in the account in 10 years?
4. The PMT function below calculates the annual deposit.
Explanation: in 10 years time, you pay 10 * $100 (negative) = $1000, and you'll receive $1,448.66 (positive) after 10 years.
The higher the interest, the faster your money grows.
Consider an annuity with an annual interest rate of 6% and a present value of $83,748.46 (purchase value).
How much money can you withdraw at the end of each month for the next 20 years?
5. The PMT function below calculates the monthly withdrawal.
Explanation: you need a one-time payment of $83,748.46 (negative) to pay this annuity.
You'll receive 240 * $600 (positive) = $144,000 in the future.
This is another example that money grows over time.
PPMT and IPMT
Consider a loan with an annual interest rate of 5%, a 2-year duration and a present value (amount borrowed) of $20,000.
1. The PMT function below calculates the monthly payment.
Note: we make monthly payments, so we use 5%/12 for Rate and 2*12 for Nper (total number of periods).
2. The PPMT function in Excel calculates the principal part of the payment.
The second argument specifies the payment number.
Explanation: the PPMT function above calculates the principal part of the 5th payment.
3. The IPMT function in Excel calculates the interest part of the payment.
The second argument specifies the payment number.
Explanation: the IPMT function above calculates the interest part of the 5th payment.
4. It takes 24 months to pay off this loan.
Create a loan amortization schedule (see picture below) to clearly see how the principal part increases and the interest part decreases with each payment.
Note: the principal part and the interest part always add up to the payment amount.
Loans with Different Durations
This example teaches you how to compare loans with different durations in Excel.
1. First, we calculate the monthly payment on a loan with an annual interest rate of 6%, a 20-year duration and a present value (amount borrowed) of $150,000.
Note: we make monthly payments, so we use 6%/12 = 0.5% for Rate and 20*12 = 240 for Nper (total number of periods).
2. Next, select the range A2:D2 and drag it down two rows.
3. Change the duration of the other two loans to 25 and 30 years.
Result:
The monthly payment over 30 years ($899,33) looks good in contrast to the $966,45 and $1,074.65. Right?
4. But now we calculate the Total Paid for each loan.
The monthly payment over 30 years ($899,33) suddenly does not look so attractive anymore.
Conclusion: the longer the duration of the loan, the more interest you pay.
Investment or Annuity
Investment | Annuity
This example teaches you how to calculate the future value of an investment or the present value of an annuity.
Tip: when working with financial functions in Excel, always ask yourself the question, am I making a payment (negative) or am I receiving money (positive)?
Investment
Assume that at the end of every year, you deposit $100 into a savings account.
At an annual interest rate of 8%, how much will your investment be worth after 10 years?
1. Insert the FV (Future Value) function.
2. Enter the arguments.
In 10 years time, you pay 10 * $100 (negative) = $1000, and you'll receive $1,448.66 (positive) after 10 years.
The higher the interest, the faster your money grows.
Note: the last two arguments are optional.
If omitted, Pv = 0 (no present value).
If Type is omitted, it is assumed that payments are due at the end of the period.
Annuity
Assume you want to purchase an annuity that will pay $600 a month, for the next 20 years.
At an annual interest rate of 6%, how much does the annuity cost?
1. Insert the PV (Present Value) function.
2. Enter the arguments.
You need a one-time payment of $83,748.46 (negative) to pay this annuity.
You'll receive 240 * $600 (positive) = $144,000 in the future.
This is another example that money grows over time.
Note: we receive monthly payments, so we use 6%/12 = 0.5% for Rate and 20*12 = 240 for Nper.
The last two arguments are optional.
If omitted, Fv = 0 (no future value).
If Type is omitted, it is assumed that payments are due at the end of the period.
This annuity does not take into account life expectancy, inflation etc.
Compound Interest
What's compound interest and what's the formula for compound interest in Excel? This example gives you the answers to these questions.
1. Assume you put $100 into a bank.
How much will your investment be worth after 1 year at an annual interest rate of 8%? The answer is $108.
2. Now this interest ($8) will also earn interest (compound interest) next year.
How much will your investment be worth after 2 years at an annual interest rate of 8%? The answer is $116.64.
3. How much will your investment be worth after 5 years? Simply drag the formula down to cell A6.
The answer is $146.93.
4. All we did was multiplying 100 by 1.08, 5 times.
So we can also directly calculate the value of the investment after 5 years.
which is the same as:
Note: there is no special function for compound interest in Excel.
However, you can easily create a compound interest calculator to compare different rates and different durations.
5. Assume you put $100 into a bank.
How much will your investment be worth after 5 years at an annual interest rate of 8%? You already know the answer.
Note: the compound interest formula reduces to =100*(1+0.08/1)^(1*5), =100*(1.08)^5
6. Assume you put $10,000 into a bank.
How much will your investment be worth after 15 years at an annual interest rate of 4% compounded quarterly? The answer is $18,167.
Note: the compound interest formula reduces to =10000*(1+0.04/4)^(4*15), =10000*(1.01)^60
7. Assume you put $10,000 into a bank.
How much will your investment be worth after 10 years at an annual interest rate of 5% compounded monthly? The answer is $16,470.
Note: the compound interest formula always works.
If you're interested, download the Excel file and try it yourself!
CAGR
There's no CAGR function in Excel.
However, simply use the RRI function in Excel to calculate the compound annual growth rate (CAGR) of an investment over a period of years.
1. The RRI function below calculates the CAGR of an investment.
The answer is 8%.
Note: the RRI function has three arguments (number of years = 5, start = 100, end = 147).
2. The CAGR measures the growth of an investment as if it had grown at a steady rate on an annually compounded basis.
We can check this.
which is the same as:
Note: again, number of years or n = 5, start = 100, end = 147, CAGR = 8%.
3. Knowing this, we can easily create a CAGR formula that calculates the compound annual growth rate of an investment in Excel.
A2 = A1 * (1 + CAGR)n
end = start * (1 + CAGR)n
end/start = (1 + CAGR)n
(end/start)1/n = (1 + CAGR)
CAGR = (end/start)1/n - 1
4. The CAGR formula below does the trick.
Note: in other words, to calculate the CAGR of an investment in Excel, divide the value of the investment at the end by the value of the investment at the start.
Next, raise this result to the power of 1 divided by the number of years.
Finally, subtract 1 from this result.
Loan Amortization Schedule
This example teaches you how to create a loan amortization schedule in Excel.
1. We use the PMT function to calculate the monthly payment on a loan with an annual interest rate of 5%, a 2-year duration and a present value (amount borrowed) of $20,000. We use named ranges for the input cells.
2. Use the PPMT function to calculate the principal part of the payment.
The second argument specifies the payment number.
3. Use the IPMT function to calculate the interest part of the payment.
The second argument specifies the payment number.
4. Update the balance.
5. Select the range A7:E7 (first payment) and drag it down one row.
Change the balance formula.
6. Select the range A8:E8 (second payment) and drag it down to row 30.
It takes 24 months to pay off this loan.
See how the principal part increases and the interest part decreases with each payment.
NPV
Net Present Value | Understanding the NPV function
The correct NPV formula in Excel uses the NPV function to calculate the present value of a series of future cash flows and subtracts the initial investment.
Net Present Value
For example, project X requires an initial investment of $100 (cell B5).
1. We expect a profit of $0 at the end of the first period, a profit of $50 at the end of the second period and a profit of $150 at the end of the third period.
2. The discount rate equals 15%.
Explanation: this is the rate of return of the best alternative investment.
For example, you could also put your money in a high-yield savings account at an interest rate of 15%.
3. The NPV formula below calculates the net present value of project X.
Explanation: a positive net present value indicates that the project’s rate of return exceeds the discount rate.
In other words, it's better to invest your money in project X than to put your money in a high-yield savings account at an interest rate of 15%.
4. The NPV formula below calculates the net present value of project Y.
Explanation: the net present value of project Y is higher than the net present value of project X.
Therefore, project Y is a better investment.
Understanding the NPV function
The NPV function simply calculates the present value of a series of future cash flows.
This is not rocket science.
1. For example, project A requires an initial investment of $100 (cell B5).
We expect a profit of $0 at the end of the first period, a profit of $0 at the end of the second period and a profit of $152.09 at the end of the third period.
Explanation: a net present value of 0 indicates that the project generates a rate of return equal to the discount rate.
In other words, both options, investing your money in project A or putting your money in a high-yield savings account at an interest rate of 15%, yield an equal return.
2. We can check this.
Assume you put $100 into a bank.
How much will your investment be worth after 3 years at an annual interest rate of 15%? The answer is $152.09.
Note: the internal rate of return of project A equals 15%.
The internal rate of return is the discount rate that makes the net present value equal to zero.
Visit our page about the IRR function to learn more about this topic.
3. The NPV function simply calculates the present value of a series of future cash flows.
4. We can check this.
First, we calculate the present value (pv) of each cash flow.
Next, we sum these values.
Explanation: $152.09 in 3 years is worth $100 right now.
$50 in 2 years is worth 37.81 right now.
$25 in 1 year is worth $21.74 right now.
Would you trade $159.55 for $100 right now? Of course, so project B is a good investment.
5. The NPV formula below calculates the net present value of project B.
Explanation: project B is a good investment because the net present value ($159.55 - $100) is greater than 0.
IRR
Simple IRR example | Present Values | IRR rule
Use the IRR function in Excel to calculate a project's internal rate of return.
The internal rate of return is the discount rate that makes the net present value equal to zero.
Simple IRR example
For example, project A requires an initial investment of $100 (cell B5).
1. We expect a profit of $0 at the end of the first period, a profit of $0 at the end of the second period and a profit of $152.09 at the end of the third period.
Note: the discount rate equals 10%.
This is the rate of return of the best alternative investment.
For example, you could also put your money in a savings account at an interest rate of 10%.
2. The correct NPV formula in Excel uses the NPV function to calculate the present value of a series of future cash flows and subtracts the initial investment.
Explanation: a positive net present value indicates that the project’s rate of return exceeds the discount rate.
In other words, it's better to invest your money in project A than to put your money in a savings account at an interest rate of 10%.
3. The IRR function below calculates the internal rate of return of project A.
4. The internal rate of return is the discount rate that makes the net present value equal to zero.
To clearly see this, replace the discount rate of 10% in cell B2 with 15%.
Explanation: a net present value of 0 indicates that the project generates a rate of return equal to the discount rate.
In other words, both options, investing your money in project A or putting your money in a high-yield savings account at an interest rate of 15%, yield an equal return.
5. We can check this.
Assume you put $100 into a bank.
How much will your investment be worth after 3 years at an annual interest rate of 15%? The answer is $152.09.
Conclusion: you can compare the performance of a project to a savings account with an interest rate equal to the IRR.
Present Values
For example, project B requires an initial investment of $100 (cell B5).We expect a profit of $25 at the end of the first period, a profit of $50 at the end of the second period and a profit of $152.09 at the end of the third period.
1. The IRR function below calculates the internal rate of return of project B.
2. Again, the internal rate of return is the discount rate that makes the net present value equal to zero.
To clearly see this, replace the discount rate of 15% in cell B2 with 39%.
Explanation: a net present value of 0 indicates that the project generates a rate of return equal to the discount rate.
In other words, both options, investing your money in project B or putting your money in a high-yield savings account at an interest rate of 39%, yield an equal return.
3. We can check this.
First, we calculate the present value (pv) of each cash flow.
Next, we sum these values.
Explanation: instead of investing $100 in project B, you could also put $17.95 in a savings account for 1 year, $25.77 in a savings account for 2 years and $56.28 in a savings account for three years, at an annual interest rate equal to the IRR (39%).
IRR rule
The IRR rule states that if the IRR is greater than the required rate of return, you should accept the project.
IRR values are frequently used to compare investments.
1. The IRR function below calculates the internal rate of return of project X.
Conclusion: if the required rate of return equals 15%, you should accept this project because the IRR of this project equals 29%.
2. The IRR function below calculates the internal rate of return of project Y.
Conclusion: in general, a higher IRR indicates a better investment.
Therefore, project Y is a better investment than project X.
3. The IRR function below calculates the internal rate of return of project Z.
Conclusion: a higher IRR isn't always better.
Project Z has a higher IRR than project Y but the cash flows are much lower.
Depreciation
SLN | SYD | DB | DDB | VDB
Excel offers five different depreciation functions.
We consider an asset with an initial cost of $10,000, a salvage value (residual value) of $1000 and a useful life of 10 periods (years).
Below you can find the results of all five functions.
Each function will be explained separately in the next 5 paragraphs.
Most assets lose more value in the beginning of their useful life.
The SYD, DB, DDB and VDB functions have this property.
SLN
The SLN (Straight Line) function is easy.
Each year the depreciation value is the same.
The SLN function performs the following calculation.
Deprecation Value = (10,000 - 1,000) / 10 = 900.00. If we subtract this value 10 times, the asset depreciates from 10,000 to 1000 in 10 years (see first picture, bottom half).
SYD
The SYD (Sum of Years' Digits) function is also easy.
As you can see below, this function also requires the period number.
The SYD function performs the following calculations.
A useful life of 10 years results in a sum of years of 10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 = 55. The asset loses 9000 in value.
Depreciation value period 1 = 10/55 * 9000 = 1,636.36. Deprecation value period 2 = 9/55 * 9000 = 1,472,73, etc.
If we subtract these values, the asset depreciates from 10,000 to 1000 in 10 years (see first picture, bottom half).
DB
The DB (Declining Balance) function is a bit more complicated.
It uses a fixed rate to calculate the depreciation values.
The DB function performs the following calculations.
Fixed rate = 1 - ((salvage / cost) ^ (1 / life)) = 1 - (1000/10,000)^(1/10) = 1 - 0.7943282347 = 0.206 (rounded to 3 decimal places).
Depreciation value period 1 = 10,000 * 0.206 = 2,060.00. Deprecation value period 2 = (10,000 - 2,060.00) * 0.206 = 1635.64, etc.
If we subtract these values, the asset depreciates from 10,000 to 995.88 in 10 years (see first picture, bottom half).
Note: the DB function has a fifth optional argument.
You can use this argument to indicate the number of months to go in the first year (If omitted, it is assumed to be 12).
For example, set this argument to 9 if you purchase your asset at the beginning of the second quarter in year 1 (9 months to go in the first year).Excel uses a slightly different formula to calculate the deprecation value for the first and last period (the last period represents an 11th year with only 3 months).
DDB
The DDB (Double Declining Balance) function is easy again.
However, sometimes you don't reach the salvage value when you use this function.
The DDB function performs the following calculations.
A useful life of 10 years results in a rate of 1/10 = 0.1. Because this function is called Double Declining Balance we double this rate (factor = 2).
Depreciation value period 1 = 10,000 * 0.2 = 2,000.00. Deprecation value period 2 = (10,000 - 2,000.00) * 0.2 = 1600.00, etc.
As said earlier, sometimes you don't reach the salvage value when you use this function.
In this example, if we subtract the depreciation values, the asset depreciates from 10,000 to 1073.74 in 10 years (see first picture, bottom half).
However, read on to fix this.
Note: the DDB function has a fifth optional argument.
You can use this argument to use a different factor.
VDB
The VDB (Variable Declining Balance) function uses the DDB (Double Declining Balance) method by default.
The 4th argument indicates the starting period, the 5th argument indicates the ending period.
The VDB function performs the same calculations as the DDB function.
However, it switches to Straight Line calculation (yellow values) to make sure you reach the salvage value (see first picture, bottom half).
It only switches to Straight Line calculation when Depreciation Value, Straight Line is higher than Depreciation Value, DDB.
In period 8, Depreciation Value, DDB = 419.43. We still have 2097.15 - 1000 (see first picture, bottom half) to depreciate.
If we use the Straight Line method this results in 3 remaining depreciation values of 1097.15 / 3 = 365.72. Depreciation Value, Straight Line is not higher so we do not switch.
In period 9, Depreciation Value, DDB = 335.54. We still have 1677.72 - 1000 (see first picture, bottom half) to depreciate.
If we use Straight line method this results in 2 remaining depreciation values of 677.72 / 2 = 338.86. Depreciation Value, Straight Line is higher so we switch to Straight Line calculation.
Note: the VDB function is much more versatile than the DDB function.
It can calculate the depreciation value of multiple periods.
In this example, =VDB(Cost,Salvage,Life,0,3) reduces to 2000 + 1600 + 1280 = 4880. It contains a 6th and 7th optional argument.
You can use the 6th argument to use a different factor.
If you set the 7th argument to TRUE it does not switch to Straight Line calculation (the same as DDB).
Profit Margin
Gross Profit Margin | Operating Profit Margin | Net Profit Margin
Calculating gross profit margin, operating profit margin and net profit margin in Excel is easy.
Simply use the formulas explained on this page.
Gross Profit Margin
Assume your business had a total revenue of $10,000 in July and the cost of goods sold (COGS) equaled $4,000.
To calculate the gross profit margin (GPM), use the following formula:
Gross Profit MarginGPM
|
= |
Total Revenue - COGS |
Total Revenue |
1. The formula below calculates the number above the fraction line.
This is called the gross profit.
2. Divide this result by the total revenue to calculate the gross profit margin in Excel.
3. On the Home tab, in the Number group, click the percentage symbol to apply a Percentage format.
Result:
Operating Profit Margin
The operating profit margin also includes operating expenses (OPEX) such as rent, equipment, inventory costs, marketing, etc.
To calculate the operating profit margin (OPM), use the following formula:
Operating Profit MarginOPM
|
= |
Total Revenue - COGS - OPEX |
Total Revenue |
1. The formula below calculates the number above the fraction line.
This is called the operating profit.
2. Divide this result by the total revenue to calculate the operating profit margin in Excel.
3. On the Home tab, in the Number group, click the percentage symbol to apply a Percentage format.
Result:
Net Profit Margin
The net profit margin also includes non-operating expenses such as interest (on debt) and taxes.
To calculate the net profit margin (NPM), use the following formula:
Net Profit MarginNPM
|
= |
Total Revenue - COGS - OPEX - I - T |
Total Revenue |
where:
COGS = Cost of Goods Sold
OPEX = Operating expenses
I = Interest
T = Taxes
1. The formula below calculates the number above the fraction line.
This is called the net income.
2. Divide this result by the total revenue to calculate the net profit margin in Excel.
3. On the Home tab, in the Number group, click the percentage symbol to apply a Percentage format.
Result:
Conclusion: a 35% net profit margin means your business has a net income of $0.35 for each dollar of sales.
AVERAGE
Average | AverageA | Average Top 3 | AverageIf | Weighted Average | Moving Average
The AVERAGE function in Excel calculates the average (arithmetic mean) of a group of numbers.
The AVERAGE function ignores logical values, empty cells and cells that contain text.
Average
Instead of using the AVERAGE function, use SUM and COUNT.
1. For example, the AVERAGE function below calculates the average of the numbers in cells A1 through A3.
2. The formula below produces the exact same result.
3. The following AVERAGE function calculates the average of the numbers in cells A1 through A3 and the number 8.
4. The AVERAGE function ignores logical values (TRUE or FALSE), empty cells and cells that contain text.
AverageA
The AVERAGEA function also returns the average (arithmetic mean) of a group of numbers.
However, the logical value FALSE and cells that contain text evaluate to 0 and the logical value TRUE evaluates to 1. The AVERAGEA function also ignores empty cells.
1. For example, take a look at the AVERAGEA function below.
2. You can use the normal AVERAGE function to check this result.
Average Top 3
Use AVERAGE and LARGE in Excel to calculate the average of the top 3 numbers in a data set.
1. First, the AVERAGE function below calculates the average of the numbers in cells A1 through A6.
2. For example, to find the third largest number, use the following LARGE function.
3. The formula below calculates the average of the top 3 numbers.
Explanation: the LARGE function returns the array constant {20,15,10}.
This array constant is used as an argument for the AVERAGE function, giving a result of 15.
AverageIf
To calculate the average of cells that meet one criteria, use the AVERAGEIF function in Excel.
Weighted Average
To calculate a weighted average in Excel, use SUMPRODUCT and SUM.
Moving Average
Use the Analysis Toolpak to calculate the moving average of a time series in Excel.
Note: a moving average is used to smooth out irregularities (peaks and valleys) to easily recognize trends.
Negative Numbers to Zero
A clever Excel trick to change negative numbers to zero but leave positive numbers unchanged.
Below you can find two columns with numbers.
To subtract the numbers in column B from the numbers in column A, execute the following steps.
1. Select cell C1.
2. Enter the formula =A1-B1
3. Click the lower right corner of cell C1 and drag the formula down.
Result:
4. To change the negative numbers to zero but leave the positive numbers unchanged, instead of =A1-B1, use =MAX(0,A1-B1) and drag the function down.
Result:
Explanation: the MAX function returns the maximum of two values.
If the result of the formula is negative, the function returns 0.
Random Numbers
Rand | RandBetween | RandArray
Excel has two very useful functions when it comes to generating random numbers.
RAND and RANDBETWEEN.
Rand
The RAND function generates a random decimal number between 0 and 1.
1. Select cell A1.
2. Type =RAND() and press Enter.
The RAND function takes no arguments.
3. To generate a list of random numbers, select cell A1, click on the lower right corner of cell A1 and drag it down.
Note that cell A1 has changed.
That is because random numbers change every time a cell on the sheet is calculated.
4. If you don't want this, simply copy the random numbers and paste them as values.
5. Select cell C1 and look at the formula bar.
This cell holds a value now and not the RAND function.
RandBetween
The RANDBETWEEN function generates a random whole number between two boundaries.
1. Select cell A1.
2. Type RANDBETWEEN(50,75) and press Enter.
3. If you want to generate random decimal numbers between 50 and 75, modify the RAND function as follows:
RandArray
If you have Excel 365 or Excel 2021, you can use the magic RANDARRAY function.
1. By default, the RANDARRAY function generates random decimal numbers between 0 and 1. The array below consists of 5 rows and 2 columns.
Note: this dynamic array function, entered into cell A1, fills multiple cells.
Wow! This behavior in Excel 365/2021 is called spilling.
2. The RANDARRAY function below generates an array of integers, 10 rows by 1 column, between 20 and 80.
Note: the Boolean TRUE (fifth argument) tells the RANDARRAY function to return an array of integers.
Use FALSE to return an array of decimal numbers between 20 and 80.
RANK
The RANK function in Excel returns the rank of a number in a list of numbers.
Use RANK.AVG to return the average rank if more than one number has the same rank.
1. If the third argument is omitted (or 0), Excel ranks the largest number first, second largest number second, etc.
Note: when we drag this formula down, the absolute reference ($A$1:$A$9) stays the same, while the relative reference (A1) changes to A2, A3, A4, etc.
2. If the third argument is 1, Excel ranks the smallest number first, second smallest number second, etc.
Note: the RANK function is an old function.
Microsoft Excel recommends using the new RANK.EQ function in Excel 2010 or later.
There's no difference at all between these two functions.
3. The RANK.AVG function in Excel 2010 or later returns the average rank if more than one number has the same rank.
4. To create a clean RANK function, use a named range instead of an absolute range reference.
Explanation: the named range Data refers to the range A1:A9.
If you're using Excel 365 or Excel 2021, create the following RANK formula.
This formula will amaze and impress your co-workers.
5. We want to show the top 3 results.
Enter the value 3 into cell D2.
6. To find the third largest score, use the LARGE function below.
The named range Scores refers to the range B2:B8.
7. The FILTER function below shows all students with a score greater than or equal to the third largest score.
Note: the FILTER function, entered into cell F2, fills multiple cells.
Wow!
8. Finally, add the SORT function to sort by the second column (second argument), in descending order (third argument).
Note: use 1 to sort in ascending order, use -1 to sort in descending order.
9. This RANK formula works for every N.
For example, enter the value 5 into cell D2 to show the top 5 results.
Note: this dynamic array formula, entered into cell F2, fills multiple cells.
This behavior in Excel 365/2021 is called spilling.
Tip: download the Excel file (right side of this page) and give it a try.
Percentiles and Quartiles
This example teaches you how to use PERCENTILE and QUARTILE in Excel.
Below you can find a list of scores (green fill for illustration only).
1. Use the PERCENTILE function shown below to calculate the 30th percentile.
Excel returns the value 12.7. This means that 30% (6 out of 20) of the scores are lower or equal to 12.7
Note: The second argument of the PERCENTILE function must be a decimal number between 0 and 1. Excel uses a slightly different algorithm to calculate percentiles and quartiles than you find in most statistics books.
If you're interested, download the Excel file.
2. Use the PERCENTILE function shown below to calculate the 90th percentile.
Excel returns the value 61.7. This means that 90% (18 out of 20) of the scores are lower or equal to 61.7
3. Use the QUARTILE function shown below to calculate the 1st quartile.
Excel returns the value 11.25. This means that 25% (5 out of 20) of the scores are lower or equal to 11.25
Note: The second argument of the QUARTILE function must be a number between 0 and 4. PERCENTILE(A1:A20,0.25) gives the exact same result.
It's up to you which function you would like to use for quartiles.
Below you can find an overview.
Minimum Value |
PERCENTILE(A1:A20,0) |
QUARTILE(A1:A20,0) |
MIN(A1:A20) |
1st Quarter |
PERCENTILE(A1:A20,0.25) |
QUARTILE(A1:A20,1) |
|
Median |
PERCENTILE(A1:A20,0.50) |
QUARTILE(A1:A20,2) |
MEDIAN(A1:A20) |
3rd Quarter |
PERCENTILE(A1:A20,0.75) |
QUARTILE(A1:A20,3) |
|
Maximum Value |
PERCENTILE(A1:A20,1) |
QUARTILE(A1:A20,4) |
MAX(A1:A20) |
Box and Whisker Plot
Simple Box and Whisker Plot | Outliers | Box Plot Calculations
This example teaches you how to create a box and whisker plot in Excel.
A box and whisker plot shows the minimum value, first quartile, median, third quartile and maximum value of a data set.
Simple Box and Whisker Plot
1. For example, select the range A1:A7.
Note: you don't have to sort the data points from smallest to largest, but it will help you understand the box and whisker plot.
2. On the Insert tab, in the Charts group, click the Statistic Chart symbol.
3. Click Box and Whisker.
Result:
Explanation: the middle line of the box represents the median or middle number (8).
The x in the box represents the mean (also 8 in this example).
The median divides the data set into a bottom half {2, 4, 5} and a top half {10, 12, 15}.
The bottom line of the box represents the median of the bottom half or 1st quartile (4).
The top line of the box represents the median of the top half or 3rd quartile (12).
The whiskers (vertical lines) extend from the ends of the box to the minimum value (2) and maximum value (15).
Outliers
1. For example, select the range A1:A11.
Note: the median or middle number (8) divides the data set into two halves: {1, 2, 2, 4, 5} and {10, 12, 15, 18, 35}.
The 1st quartile (Q1) is the median of the first half.
Q1 = 2. The 3rd quartile (Q3) is the median of the second half.
Q3 = 15.
2. On the Insert tab, in the Charts group, click the Statistic Chart symbol.
3. Click Box and Whisker.
Result:
Explanation: the interquartile range (IQR) is defined as the distance between the 1st quartile and the 3rd quartile.
In this example, IQR = Q3 - Q1 = 15 - 2 = 13. A data point is considered an outlier if it exceeds a distance of 1.5 times the IQR below the 1st quartile (Q1 - 1.5 * IQR = 2 - 1.5 * 13 = -17.5) or 1.5 times the IQR above the 3rd quartile (Q3 + 1.5 * IQR = 15 + 1.5 * 13 = 34.5).
Therefore, in this example, 35 is considered an outlier.
As a result, the top whisker extends to the largest value (18) within this range.
4. Change the last data point to 34.
Result:
Explanation: all data points are between -17.5 and 34.5. As a result, the whiskers extend to the minimum value (2) and maximum value (34).
Box Plot Calculations
Most of the time, you can cannot easily determine the 1st quartile and 3rd quartile without performing calculations.
1. For example, select the even number of data points below.
2. On the Insert tab, in the Charts group, click the Statistic Chart symbol.
3. Click Box and Whisker.
Result:
Explanation: Excel uses the QUARTILE.EXC function to calculate the 1st quartile (Q1), 2nd quartile (Q2 or median) and 3rd quartile (Q3).
This function interpolates between two values to calculate a quartile.
In this example, n = 8 (number of data points).
4. Q1 = 1/4*(n+1)th value = 1/4*(8+1)th value = 2 1/4th value = 4 + 1/4 * (5-4) = 4 1/4. You can verify this number by using the QUARTILE.EXC function or looking at the box and whisker plot.
5. Q2 = 1/2*(n+1)th value = 1/2*(8+1)th value = 4 1/2th value = 8 + 1/2 * (10-8) = 9. This makes sense, the median is the average of the middle two numbers.
6. Q3 = 3/4*(n+1)th value = 3/4*(8+1)th value = 6 3/4th value = 12 + 3/4 * (15-12) = 14 1/4. Again, you can verify this number by using the QUARTILE.EXC function or looking at the box and whisker plot.
AVERAGEIF
The AVERAGEIF function in Excel calculates the average of cells that meet one criteria.
AVERAGEIFS calculates the average of cells that meet multiple criteria.
1. For example, the AVERAGEIF function below (two arguments) calculates the average of all values in the range A1:A7 that are greater than 0.
2. The AVERAGEIF function below (three arguments, last argument is the range to average) calculates the average of all values in the range B1:B7 if the corresponding cells in the range A1:A7 contain exactly Apple.
3. The AVERAGEIF function below calculates the average of all values in the range B1:B7 if the corresponding cells in the range A1:A7 do not contain exactly Banana.
4. The AVERAGEIF function below calculates the average of all values in the range B1:B7 if the corresponding cells in the range A1:A7 contain a series of zero or more characters + berry.
An asterisk (*) matches a series of zero or more characters.
5. The AVERAGEIF function below calculates the average of all values in the range B1:B7 if the corresponding cells in the range A1:A7 contain exactly 4 characters.
A question mark (?) matches exactly one character.
The AVERAGEIFS function (with the letter S at the end) in Excel calculates the average of cells that meet multiple criteria.
6. The AVERAGEIFS function below calculates the average of all values in the range A1:A7 that are greater than or equal to 500 and less than or equal to 1000.
Note: first argument is the range to average, followed by two or more range/criteria pairs.
7. The AVERAGEIFS function below calculates the average of all values in the range C1:C7 if the corresponding cells in the range A1:A7 contain exactly Apple and the corresponding cells in the range B1:B7 contain exactly Red.
Note: again, the first argument is the range to average, followed by two or more range/criteria pairs.
FORECAST
FORECAST.LINEAR | FORECAST.ETS | Forecast Sheet
The FORECAST (or FORECAST.LINEAR) function in Excel predicts a future value along a linear trend.
The FORECAST.ETS function in Excel predicts a future value using Exponential Triple Smoothing, which takes into account seasonality.
Note: the FORECAST function is an old function.
Microsoft Excel recommends using the new FORECAST.LINEAR function which produces the exact same result.
FORECAST.LINEAR
1. The FORECAST.LINEAR function below predicts a future value along a linear trend.
Explanation: when we drag the FORECAST.LINEAR function down, the absolute references ($B$2:$B$11 and $A$2:$A$11) stay the same, while the relative reference (A12) changes to A13 and A14.
2. Enter the value 89 into cell C11, select the range A1:C14 and insert a scatter plot with straight lines and markers.
Note: when you add a trendline to an Excel chart, Excel can display the equation in a chart.
This equation predicts the same future values.
FORECAST.ETS
The FORECAST.ETS function in Excel 2016 or later is a great function which can detect a seasonal pattern.
1. The FORECAST.ETS function below predicts a future value using Exponential Triple Smoothing.
Note: the last 3 arguments are optional.
The fourth argument indicates the length of the seasonal pattern.
The default value of 1 indicates seasonality is detected automatically.
2. Enter the value 49 into cell C13, select the range A1:C17 and insert a scatter plot with straight lines and markers.
3. You can use the FORECAST.ETS.SEASONALITY function to find the length of the seasonal pattern.
After seeing the chart, you probably already know the answer.
Conclusion: in this example, when using the FORECAST.ETS function, you can also use the value 4 for the fourth argument.
Forecast Sheet
Use the Forecast Sheet tool in Excel 2016 or later to automatically create a visual forecast worksheet.
1. Select the range A1:B13 shown above.
2. On the Data tab, in the Forecast group, click Forecast Sheet.
Excel launches the dialog box shown below.
3. Specify when the forecast ends, set a confidence interval (95% by default), detect seasonality automatically or manually set the length of the seasonal pattern, etc.
4. Click Create.
This tool uses the FORECAST.ETS function and calculates the same future values.
The lower and upper confidence bounds are a nice bonus.
Explanation: in period 13, we can be 95% confident that the number of visitors will be between 86 and 94.
MAXIFS and MINIFS
Use MAXIFS and MINIFS in Excel 2016 or later to find the maximum and minimum value based on one criteria or multiple criteria.
1. For example, the MAXIFS function below finds the highest female score.
Note: the first argument (D2:D12 in this example) is always the range in which the maximum or minimum will be determined.
This MAXIFS function has 1 range/criteria pair (B2:B12/Female).
2. The MINIFS function below finds the lowest female score.
3. For example, the MAXIFS function below finds the highest female score in Canada.
Note: this MAXIFS function has 2 range/criteria pairs (B2:B12/Female and C2:C12/Canada).
MAXIFS and MINIFS functions can handle up to 126 range/criteria pairs.
4. The MAXIFS function below finds the highest score below 60.
Note: this MAXIFS function only uses the range D2:D12.
Weighted Average
To calculate a weighted average in Excel, simply use SUMPRODUCT and SUM.
1. First, the AVERAGE function below calculates the normal average of three scores.
Suppose your teacher says, "The test counts twice as much as the quiz and the final exam counts three times as much as the quiz".
2. Below you can find the corresponding weights of the scores.
The formula below calculates the weighted average of these scores.
Weighted AverageWA
|
= |
20 + 40 + 40 + 90 + 90 + 90 |
6 |
3. We can use the SUMPRODUCT function in Excel to calculate the number above the fraction line (370).
Note: the SUMPRODUCT function performs this calculation: (20 * 1) + (40 * 2) + (90 * 3) = 370.
4. We can use the SUM function in Excel to calculate the number below the fraction line (6).
5. Use the functions at step 3 and step 4 to calculate the weighted average of these scores in Excel.
MODE
Use the MODE function in Excel to find the most frequently occurring number in a list of numbers.
Use MODE.MULT to find multiple modes.
1. The MODE function below returns the most frequently occurring number (8).
2. The new MODE.SNGL function (SNGL stands for single) produces the exact same result.
3. Change the value in cell A2 to 5. In this example, there are multiple modes (5 and 8).
MODE and MODE.SNGL always return a single mode.
4. If you have Excel 365 or Excel 2021, simply use the MODE.MULT function to find multiple modes.
Note: the MODE.MULT function, entered into cell A8, fills multiple cells.
Wow! This behavior in Excel 365/2021 is called spilling.
If you don't have Excel 365 or Excel 2021, execute the following steps to find multiple modes.
5. Select multiple cells.
6. Enter the MODE.MULT function.
7. Finish by pressing CTRL + SHIFT + ENTER.
Note: the formula bar indicates that this is an array formula by enclosing it in curly braces {}.
To delete this array formula, select the range A8:A10 and press Delete.
In this example, there are only two modes (5 and 8) so we could have selected two cells at step 5.
8. Change the value in cell A6 to 3.
9. The MODE function only works with numbers.
Use INDEX, MODE and MATCH to find the most frequently occurring word in Excel.
Standard Deviation
What is Standard Deviation? | STDEV.P | STDEV.S | Variance
This page explains how to calculate the standard deviation based on the entire population using the STDEV.P function in Excel and how to estimate the standard deviation based on a sample using the STDEV.S function in Excel.
What is Standard Deviation?
Standard deviation is a number that tells you how far numbers are from their mean.
1. For example, the numbers below have a mean (average) of 10.
Explanation: the numbers are all the same which means there's no variation.
As a result, the numbers have a standard deviation of zero.
The STDEV function is an old function.
Microsoft Excel recommends using the new STEDV.S function which produces the exact same result.
2. The numbers below also have a mean (average) of 10.
Explanation: the numbers are close to the mean.
As a result, the numbers have a low standard deviation.
3. The numbers below also have a mean (average) of 10.
Explanation: the numbers are spread out.
As a result, the numbers have a high standard deviation.
STDEV.P
The STDEV.P function (the P stands for Population) in Excel calculates the standard deviation based on the entire population.
For example, you're teaching a group of 5 students.You have the test scores of all students.
The entire population consists of 5 data points.
The STDEV.P function uses the following formula:
In this example, x1 = 5, x2 = 1, x3 = 4, x4 = 6, x5 = 9, μ = 5 (mean), N = 5 (number of data points).
1. Calculate the mean (μ).
2. For each number, calculate the distance to the mean.
3. For each number, square this distance.
4. Sum (∑) these values.
5. Divide by the number of data points (N = 5).
6. Take the square root.
7. Fortunately, the STDEV.P function in Excel can execute all these steps for you.
STDEV.S
The STDEV.S function (the S stands for Sample) in Excel estimates the standard deviation based on a sample.
For example, you're teaching a large group of students.You only have the test scores of 5 students.
The sample size equals 5. The STDEV.S function uses the following formula:
In this example, x1=5, x2=1, x3=4, x4=6, x5=9 (same numbers as above), x=5 (sample mean), n=5 (sample size).
1. Repeat steps 1-5 above but at step 5 divide by n-1 instead of N.
2. Take the square root.
3. Fortunately, the STDEV.S function in Excel can execute all these steps for you.
Note: why do we divide by n - 1 instead of by n when we estimate the standard deviation based on a sample? Bessel's correction states that dividing by n-1 instead of by n gives a better estimation of the standard deviation.
Variance
Variance is the square of the standard deviation.
It's that simple.
Sometimes it's easier to use the variance when solving statistical problems.
1. The VAR.P function below calculates the variance based on the entire population.
Note: you already knew this answer (see step 5 under STDEV.P).
Take the square root of this result to find the standard deviation based on the entire population.
2. The VAR.S function below estimates the variance based on a sample.
Note: you already knew this answer (see step 1 under STDEV.S).
Take the square root of this result to find the standard deviation based on a sample.
3. VAR and VAR.S produce the exact same result.
Note: Microsoft Excel recommends using the new VAR.S function.
FREQUENCY
The FREQUENCY function in Excel calculates how often values occur within the ranges you specify in a bin table.
You can also use the COUNTIFS function to create a frequency distribution.
1. First, enter the bin numbers (upper levels) in the range C4:C8.
2. Select the range D4:D9 (extra cell), enter the FREQUENCY function shown below (without the curly braces) and finish by pressing CTRL + SHIFT + ENTER.
Note: the formula bar indicates that this is an array formula by enclosing it in curly braces {}.
To delete this array formula, select the range D4:D9 and press Delete.
3. If you have Excel 365 or Excel 2021, simply select cell D4, enter the FREQUENCY function and press Enter.
Bye bye curly braces.
Note: the FREQUENCY function, entered into cell D4, fills multiple cells.
Wow! This behavior in Excel 365/2021 is called spilling.
4. Hide the column with the bin numbers (upper levels) and insert a column with proper bin labels.
Explanation: 1 value is less than or equal to 20, 8 values are greater than or equal to 21 and less than or equal to 25, etc.
At step 2, we selected the range D4:D9 (instead of the range D4:D8).
As a result, the FREQUENCY function also counts the number of values that are greater than 40.
5. You can also use the Analysis Toolpak to create a histogram.
6. Change the bin numbers.
Select the range D4:D9 (no extra cell), enter the FREQUENCY function shown below (without the curly braces) and finish by pressing CTRL + SHIFT + ENTER.
Explanation: the last bin number is greater than or equal to the maximum value (52).
As a result, we don't need an extra cell to count the number of values that are greater than 60.
7. You can also use the COUNTIFS function to create a frequency distribution.
Explanation: the COUNTIFS function in Excel counts cells based on two or more criteria.
The COUNTIFS function shown above has 2 range/criteria pairs.
The & operator joins ">=" with the value in cell C4 and "<=" with the value in cell D4. You can easily copy this formula to the other cells.
Chop off Decimals
Int | Trunc | Decimal Part
This example illustrates two functions to chop off decimals in Excel.
INT and TRUNC.
Int
The INT (Integer) function rounds a number down to the nearest integer (negative numbers become more negative).
Conclusion: the INT function only chops off decimals from positive numbers.
Trunc
The TRUNC (Truncate) function always chops off decimals.
The TRUNC function can keep any number of decimals.
Simply use the second argument to specify how many decimals you want to keep.
Decimal Part
To return just the decimal part of a number, use the following formula.
Note: if the second argument of the TRUNC function is omitted, a value of 0 is assumed.
Nearest Multiple
Mround | Ceiling | Floor
This example illustrates three functions to round numbers to a multiple of x in Excel.
MROUND, CEILING and FLOOR.
Mround
1. For example, round a number to the nearest multiple of 10.
2. For example, round a number to the nearest multiple of 5.
Ceiling
The same as MROUND but always rounds up.
Floor
The same as MROUND but always rounds down.
EVEN and ODD
Even | Odd | IsEven | IsOdd
Use EVEN and ODD in Excel to round numbers.
Use ISEVEN or ISODD in Excel to determine if a number is even or odd.
Even
1. The EVEN function rounds a positive number up to the nearest even integer.
2. The EVEN function rounds a negative number down to the nearest even integer.
Odd
1. The ODD function rounds a positive number up to the nearest odd integer.
2. The ODD function rounds a negative number down to the nearest odd integer.
IsEven
The ISEVEN function returns TRUE if a number is even and FALSE if a number is odd.
1. The ISEVEN function below returns TRUE.
2. The ISEVEN function below returns FALSE.
Add the IF function to return Even or Odd.
3. The formula below returns Even.
4. The formula below returns Odd.
IsOdd
The ISODD function returns TRUE if a number is odd and FALSE if a number is even.
1. The ISODD function below returns TRUE.
2. The ISODD function below returns FALSE.
3. Here's a cool example.
Use conditional formatting and the ISODD function to highlight all odd numbers.
Note: instead of using ISEVEN or ISODD to determine if a number is even or odd, use the MOD function in Excel.
MOD
MOD examples | Combine MOD with other Functions | Extract Fractional Part
The MOD function in Excel gives the remainder of a division.
You can use the MOD (Modulus) function to determine whether a number is divisible by another number or to check if a number is even or odd.
MOD examples
Let's start with a few simple examples of the MOD function.
1. The MOD function below returns 9.
Explanation: 59 divided by 10 equals 5 with a remainder of 9.
2. The MOD function below returns 1.
Explanation: 7 divided by 2 equals 3 with a remainder of 1.
3. The MOD function below returns 0.
Explanation: 36 divided by 6 equals 6 with a remainder of 0.
Combine MOD with other Functions
Let's explore the power of the MOD function by combining it with other Excel functions!
1. Use IF and MOD to determine if a number is divisible by another number.
For example, check if the number in cell A1 is divisible by 8.
Explanation: 85 divided by 8 equals 10 with a remainder of 5. The MOD function returns 5. As a result, the IF function returns No.
2. Change the value in cell A1 to 88.
Explanation: 88 divided by 8 equals 11 with a remainder of 0. The MOD function returns 0. As a result, the IF function returns Yes (88 is divisible by 8).
You can also use IF and MOD to check if a number is even or odd.
3. Even numbers divided by 2 always give a remainder of 0. For example, 28 divided by 2 equals 14 with a remainder of 0. As a result, the formula below returns Even.
4. Odd numbers divided by 2 always give a remainder of 1. For example, 29 divided by 2 equals 14 with a remainder of 1. As a result, the formula below returns Odd.
Let's check out another cool example.
5. The formula below returns 0 (see orange arrows) for every 3rd row.
Explanation: the ROW function returns the row number of a cell.
For the first row, MOD(1,3) = 1 because 1 divided by 3 equals 0 with a remainder 1. For the third row, MOD(3,3) = 0 because 3 divided by 3 equals 1 with a remainder of 0.
6. Use this formula to sum every 3rd row in Excel.
Note: finish an array formula by pressing CTRL + SHIFT + ENTER.
Excel adds the curly braces {}.
In Excel 365 or Excel 2021, finish by simply pressing Enter.
You won't see curly braces.
Visit our page about Summing Every nth Row for more information about this array formula.
Extract Fractional Part
To extract the fractional part of a number, use the MOD function with a divisor (second argument) of 1.
1. The MOD function below returns the fractional part of the value in cell A1.
Explanation: 3 divided by 1 equals 3 with a remainder of 0.45.
2. Knowing this, we can use the MOD function in Excel to extract the time from a datetime value.
Explanation: dates are stored as numbers in Excel and count the number of days since January 0, 1900. The fractional part represents the time as a fraction of a day.
3. To clearly see this, select the range A1:B1 and change the number format to General.
The result is a simple modulo operation.
Tip: visit our page about Date and Time formats to learn more about this topic.
Rounding Times
Use MROUND in Excel to round a time to the nearest 15 minutes, the nearest 30 minutes, the nearest hour, etc.
1. The formula below rounds a time to the nearest 15 minutes.
Note: if your formula returns a decimal number, don't panic.
Times are handled internally as numbers between 0 and 1. Simply apply a Time Format to display a time.
2. The formula below rounds a time to the nearest 30 minutes.
3. The formula below rounds a time to the nearest hour.
4. FLOOR always rounds down.
The formula below rounds a time down to the nearest hour.
5. CEILING always rounds up.
The formula below rounds a time up to the nearest hour.
Note: change the Time Format to display a time without AM/PM (24 Hour Time Format).
6. Use the ":" (colon) twice to enter a time with seconds in Excel.
For example, 2 hours, 43 minutes and 15 seconds.
7. The CEILING function below rounds this time up to the next minute.
Tip: use the Format Painter to quickly copy the format of cell A1 to cell B1.
IFERROR
Use the IFERROR function in Excel to return an alternative result, such as text, when a formula evaluates to an error.
1. For example, Excel returns the #DIV/0! error when a formula tries to divide a number by 0.
2. If the formula evaluates to an error, the IFERROR function below returns a friendly message.
3. If the formula does not evaluate to an error, the IFERROR function simply returns the result of the formula.
4. For example, Excel returns the #N/A error when the VLOOKUP function cannot find a match.
5. If the VLOOKUP function evaluates to an error, the IFERROR function below returns a friendly message.
6. If the VLOOKUP function does not evaluate to an error, the IFERROR function simply returns the result of the VLOOKUP function.
Note: the IFERROR function catches the following errors: #DIV/0!, #N/A, #VALUE!, #REF!, #NUM!, #NAME? and #NULL!.
For example, the IFERROR function shown above also catches the #NAME? error if you accidentally misspell the word VLOOKUP.Use the IFNA function in Excel 2013 or later to only catch #N/A errors.
ISERROR
This example illustrates the ISERROR function in Excel.
1. For example, Excel displays the #DIV/0! error when a formula tries to divide a number by 0.
2. The ISERROR function in Excel checks whether a value is an error and returns TRUE or FALSE.
3. Add the IF function.
If a cell contains an error, the value 5 is returned.
If not, the value 100 is returned.
4. Use the IFERROR function to return the result of a formula (if there's no error) or an alternative result, such as text (if there's an error).
5. Use COUNT, IF and ISERROR to count the total number of errors in a range of cells.
Note: finish an array formula by pressing CTRL + SHIFT + ENTER.
Excel adds the curly braces {}.
In Excel 365 or Excel 2021, finish by simply pressing Enter.
You won't see curly braces.
Visit our page about Counting Errors for detailed instructions on how to create this array formula.
AGGREGATE
Excel functions such as SUM, COUNT, LARGE and MAX don't work if a range includes errors.
However, you can easily use the AGGREGATE function to fix this.
1. For example, Excel returns an error if you use the SUM function to sum a range with errors.
2. Use the AGGREGATE function to sum a range with errors.
Explanation: the first argument (9) tells Excel that you want to use the SUM function.
The second argument (6) tells Excel that you want to ignore error values.
3. It's not easy to remember which argument belongs to which function.
Fortunately, the AutoComplete feature in Excel helps you with this.
4. The AGGREGATE function below finds the second largest number in a range with errors.
Explanation: the first argument (14) tells Excel that you want to use the LARGE function.
The second argument (6) tells Excel that you want to ignore error values.
The fourth argument (2) tells Excel that you want to find the second largest number.
5. The AGGREGATE function below finds the maximum value ignoring error values and hidden rows.
Explanation: the first argument (4) tells Excel that you want to use the MAX function.
The second argument (7) tells Excel that you want to ignore error values and hidden rows.
In this example, row 2 is hidden.
Circular Reference
Direct Circular Reference | Indirect Circular Reference | Find Circular References
A circular reference in Excel occurs when a formula directly or indirectly refers to its own cell.
This is not possible.
Direct Circular Reference
Let's start simple.
A direct circular reference in Excel occurs when a formula directly refers to its own cell.
1. For example, the formula in cell A3 below directly refers to its own cell (A3).
This is not possible.
2. Press Enter.
The circular reference error message appears.
3. Click OK.
Excel returns a 0.
Indirect Circular Reference
An indirect circular reference in Excel occurs when a formula indirectly refers to its own cell.
Let's look at a simple example.
1. For example, cell D2 below contains the value 25.
2. Cell F4 refers to cell D2.
3. Cell C5 refers to cell F4.
4. So far, everything's OK.
Now replace the value 25 in cell D2 with the formula shown below.
5. Press Enter.
The circular reference error message appears.
6. Click OK.
Excel returns a 0.
7. On the Formulas tab, in the Formula Auditing group, click Show Formulas.
8. Cell D2 refers to cell C5. Cell C5 refers to cell F4. Cell F4 refers back to cell D2.
Conclusion: the formula in cell D2 indirectly refers to its own cell (D2).
This is not possible.
The formulas in cell C5 and cell F4 also refer back to their own cell (it's a circle).
Find Circular References
To find circular references in Excel, in the Formula Auditing group, click the down arrow next to Error Checking and click Cell References.
1. Our sheet contains 2 circular references.
1 direct circular reference (A3) and 1 indirect circular reference (D2, C5 and F4).
2. On the Formulas tab, in the Formula Auditing group, click the down arrow next to Error Checking.
3. Click Circular References.
Excel shows the cell address of one circular reference.
4. You can also look at the status bar.
This is much easier.
5. Fix this circular reference.
To find more circular references, repeat these steps.
6. On the Formulas tab, in the Formula Auditing group, click the down arrow next to Error Checking.
7. Click Circular References.
Excel shows the cell addresses of the indirect circular reference.
8. The status bar only displays a single cell address.
Note: fix this circular reference by replacing one of the formulas with a value.
As a result, the warning in the status bar will disappear.
Formula Auditing
Trace Precedents | Remove Arrows | Trace Dependents | Show Formulas | Error Checking | Evaluate Formula
Formula auditing in Excel allows you to display the relationship between formulas and cells.
The example below helps you master Formula Auditing quickly and easily.
Trace Precedents
You have to pay $96.00. To show arrows that indicate which cells are used to calculate this value, execute the following steps.
1. Select cell C13.
2. On the Formulas tab, in the Formula Auditing group, click Trace Precedents.
Result:
As expected, Total cost and Group size are used to calculate the Cost per person.
3. Click Trace Precedents again.
As expected, the different costs are used to calculate the Total cost.
Remove Arrows
To remove the arrows, execute the following steps.
1. On the Formulas tab, in the Formula Auditing group, click Remove Arrows.
Trace Dependents
To show arrows that indicate which cells depend on a selected cell, execute the following steps.
1. Select cell C12.
2. On the Formulas tab, in the Formula Auditing group, click Trace Dependents.
Result:
As expected, the Cost per person depends on the Group size.
Show Formulas
By default, Excel shows the results of formulas.
To show the formulas instead of their results, execute the following steps.
1. On the Formulas tab, in the Formula Auditing group, click Show Formulas.
Result:
Note: instead of clicking Show Formulas, press CTRL + ` (you can find this key above the tab key).
Error Checking
To check for common errors that occur in formulas, execute the following steps.
1. Enter the value 0 into cell C12.
2. On the Formulas tab, in the Formula Auditing group, click Error Checking.
Result.
Excel finds an error in cell C13. The formula tries to divide a number by 0.
Evaluate Formula
To debug a formula by evaluating each part of the formula individually, execute the following steps.
1. Select cell C13.
2. On the Formulas tab, in the Formula Auditing group, click Evaluate Formula.
3. Click Evaluate four times.
Excel shows the formula result.
Floating Point Errors
Excel stores and calculates floating point numbers.
Sometimes, the result of a formula is a very close approximation.
1. For example, take a look at the formulas below.
At first glance, everything looks alright.
2. However, if we show 16 decimal places, we can see that one result is a very close approximation.
You don't have to worry about floating point errors.
They are rare.
3. Even if your worksheet contains a floating point error, in most cases, this causes no problems.
However, if you compare the value in cell C8 with another value, the following problem can occur.
4. Use the ROUND function to fix this.
IFNA
Use the IFNA function in Excel to replace a #N/A error with a friendly message.
The IFNA function only catches #N/A errors.
1. For example, Excel returns the #N/A error when the VLOOKUP function cannot find a match.
2. Use the IFNA function to replace the #N/A error with a friendly message.
3. If the VLOOKUP function does not evaluate to a #N/A error, the IFNA function simply returns the result of the VLOOKUP function.
The IFNA function was introduced in Excel 2013. If you're using Excel 2010 or Excel 2007, combine IF and ISNA (step 5) or use IFERROR (step 6).
4. First, the ISNA function checks whether a value is #N/A, and returns TRUE or FALSE.
5. Combine IF and ISNA.
6. The previous formula is quite long.
You can also use the IFERROR function in Excel.
Note: the IFERROR function catches other errors as well.
For example, the #NAME? error if you accidentally misspell the word VLOOKUP.Count Errors
This example shows you how to create an array formula that counts the number of errors in a range.
1. We use IF and ISERROR to check for an error.
Explanation: the IF function returns 1, if an error is found.
If not, it returns an empty string.
2. To count the errors (don't be overwhelmed), we add the COUNT function and replace A1 with A1:C3.
3. Finish by pressing CTRL + SHIFT + ENTER.
Note: the formula bar indicates that this is an array formula by enclosing it in curly braces {}.
Do not type these yourself.
They will disappear when you edit the formula.
In Excel 365 or Excel 2021, finish by simply pressing Enter.
You won't see curly braces.
Explanation: the range (array constant) created by the IF function is stored in Excel's memory, not in a range.
The array constant looks as follows:
{1,"",1;"","","";"","",1}
This array constant is used as an argument for the COUNT function, giving a result of 3.
4. To count specific errors, use the COUNTIF function.
For example, count the number of cells that contain the #DIV/0! error.
Count Unique Values
This example shows you how to create an array formula that counts unique values.
1. We use the COUNTIF function.
For example, to count the number of 5's, use the following function.
2. To count the unique values (don't be overwhelmed), we add the SUM function, 1/, and replace 5 with A1:A6.
3. Finish by pressing CTRL + SHIFT + ENTER.
Note: The formula bar indicates that this is an array formula by enclosing it in curly braces {}.
Do not type these yourself.
They will disappear when you edit the formula.
Explanation: The range (array constant) created by the COUNTIF function is stored in Excel's memory, not in a range.
The array constant looks as follows:
{3;1;1;1;3;3} - (three 7's, one sun, one moon, one 5, three 7's, three 7's)
This reduces to:
{1/3;1/1;1/1;1/1;1/3;1/3}
This array constant is used as an argument for the SUM function, giving a result of 1/3+1+1+1+1/3+1/3 = 4.
4. The array formula below counts the number of values that occur exactly once.
Explanation: the IF function converts the array constant {3;1;1;1;3;3} to {0;1;1;1;0;0}.
This array constant is used as an argument for the SUM function, giving a result of 3.
5. If you have Excel 365 or Excel 2021, simply use the magic UNIQUE function to extract unique values.
Note: this dynamic array function, entered into cell C3, fills multiple cells.
Wow! This behavior in Excel 365/2021 is called spilling.
6. Next, add the COUNTA function to count unique values in Excel 365/2021.
7. The formula below counts the number of values that occur exactly once.
Note: the UNIQUE function has 2 optional arguments.
The default value of 0 (second argument) tells the UNIQUE function to extract values from a vertical array.
The value 1 (third argument) tells the UNIQUE function to extract values that occur exactly once.
Count with Or Criteria
Counting with Or criteria in Excel can be tricky.
This article shows several easy to follow examples.
1. We start simple.
For example, we want to count the number of cells that contain Google or Facebook (one column).
2a.
However, if we want to count the number of rows that contain Google or Stanford (two columns), we cannot simply use the COUNTIF function twice (see the picture below).
Rows that contain Google and Stanford are counted twice, but they should only be counted once.
4 is the answer we are looking for.
2b.
What we need is an array formula.
We use the IF function to check if Google or Stanford occurs.
Explanation: TRUE = 1, FALSE = 0. For row 1, the IF function evaluates to IF(TRUE+TRUE,1,0), IF(2,1,0), 1. So the first row will be counted.
For row 2, the IF function evaluates to IF(FALSE+FALSE,1,0), IF(0,1,0), 0. So the second row will not be counted.For row 3, the IF function evaluates to IF(FALSE+TRUE,1,0), IF(1,1,0), 1. So the third row will be counted, etc.
2c.
All we need is a SUM function that counts these 1's.
To achieve this (don't be overwhelmed), we add the SUM function and replace A1 with A1:A8 and B1 with B1:B8.
2d.
Finish by pressing CTRL + SHIFT + ENTER.
Note: the formula bar indicates that this is an array formula by enclosing it in curly braces {}.
Do not type these yourself.
They will disappear when you edit the formula.
In Excel 365 or Excel 2021, finish by simply pressing Enter.
You won't see curly braces.
Explanation: the range (array constant) created by the IF function is stored in Excel's memory, not in a range.
The array constant looks as follows:
{1;0;1;0;1;0;1;0}
This array constant is used as an argument for the SUM function, giving a result of 4.
3. We can go one step further.
For example, we want to count the number of rows that contain (Google and Stanford) or Columbia.
Sum Every nth Row
This example shows you how to create an array formula that sums every nth row in Excel.
We will show it for n = 3, but you can do this for any number.
1. The ROW function returns the row number of a cell.
2. The MOD function gives the remainder of a division.
For example, for the first row, MOD(1,3) = 1 because 1 divided by 3 equals 0 with a remainder 1. For the third row, MOD(3,3) = 0 because 3 divided by 3 equals 1 with a remainder of 0. As a result, the formula returns 0 for every 3rd row.
Note: change the 3 to 4 to sum every 4th row, to 5 to sum every 5th row, etc.
3. Slightly change the formula as shown below.
4. To get the sum of the product of these two ranges (FALSE=0, TRUE=1), use the SUM function and finish by pressing CTRL + SHIFT + ENTER.
Note: the formula bar indicates that this is an array formula by enclosing it in curly braces {}.
Do not type these yourself.
They will disappear when you edit the formula.
In Excel 365 or Excel 2021, finish by simply pressing Enter.
You won't see curly braces.
Explanation: the product of these two ranges (array constant) is stored in Excel's memory, not in a range.
The array constant looks as follows.
{0;0;5;0;0;66;0;0;21}
This array constant is used as an argument for the SUM function, giving a result of 92.
Sum Largest Numbers
This example shows you how to create an array formula that sums the largest numbers in a range.
1. We use the LARGE function.
For example, to find the second largest number, use the following function.
2. To sum the 4 largest numbers (don't be overwhelmed), add the SUM function and replace 2 with {1,2,3,4}.
3. Finish by pressing CTRL + SHIFT + ENTER.
Note: the formula bar indicates that this is an array formula by enclosing it in curly braces {}.
Do not type these yourself.
They will disappear when you edit the formula.
In Excel 365 or Excel 2021, finish by simply pressing Enter.
You won't see curly braces.
Explanation: the range (array constant) created by the LARGE function is stored in Excel's memory, not in a range.
The array constant looks as follows.
{22,10,8,6}
This array constant is used as an argument for the SUM function, giving a result of 46.
Sum Range with Errors
This example shows you how to create an array formula that sums a range with errors.
You can also use the AGGREGATE function to sum a range with errors.
1. We use the IFERROR function to check for an error.
Explanation: the IFERROR function returns 0, if an error is found.
If not, it returns the value of the cell.
2. To sum the range with errors (don't be overwhelmed), we add the SUM function and replace A1 with A1:A7.
3. Finish by pressing CTRL + SHIFT + ENTER.
Note: the formula bar indicates that this is an array formula by enclosing it in curly braces {}.
Do not type these yourself.
They will disappear when you edit the formula.
In Excel 365 or Excel 2021, finish by simply pressing Enter.
You won't see curly braces.
Explanation: the range (array constant) created by the IFERROR function is stored in Excel's memory, not in a range.
The array constant looks as follows:
{0;5;4;0;0;1;3}
This array constant is used as an argument for the SUM function, giving a result of 13.
Sum with Or Criteria
Summing with Or criteria in Excel can be tricky.
This article shows several easy to follow examples.
1. We start simple.
For example, we want to sum the cells that meet the following criteria: Google or Facebook (one criteria range).
2a.
However, if we want to sum the cells that meet the following criteria: Google or Stanford (two criteria ranges), we cannot simply use the SUMIF function twice (see the picture below).
Cells that meet the criteria Google and Stanford are added twice, but they should only be added once.
10 is the answer we are looking for.
2b.
We need an array formula.
We use the IF function to check if Google or Stanford occurs.
Explanation: TRUE = 1, FALSE = 0. For row 1, the IF function evaluates to IF(TRUE+TRUE,1,0)*3, IF(2,1,0)*3, 3. So the value 3 will be added.
For row 2, the IF function evaluates to IF(FALSE+FALSE,1,0)*5, IF(0,1,0)*5, 0. So the value 5 will not be added.For row 3, the IF function evaluates to IF(FALSE+TRUE,1,0)*2, IF(1,1,0)*2, 2. So the value 2 will be added, etc.
2c.
All we need is a SUM function that sums these values.
To achieve this (don't be overwhelmed), we add the SUM function and replace A1 with A1:A8, B1 with B1:B8 and C1 with C1:C8.
2d.
Finish by pressing CTRL + SHIFT + ENTER.
Note: the formula bar indicates that this is an array formula by enclosing it in curly braces {}.
Do not type these yourself.
They will disappear when you edit the formula.
In Excel 365 or Excel 2021, finish by simply pressing Enter.
You won't see curly braces.
Explanation: the range (array constant) created by the IF function is stored in Excel's memory, not in a range.
The array constant looks as follows:
{1;0;1;0;1;0;1;0}
multiplied by C1:C8 this yields:
{3;0;2;0;4;0;1;0}
This latter array constant is used as an argument for the SUM function, giving a result of 10.
3. We can go one step further.
For example, we want to sum the cells that meet the following criteria: (Google and Stanford) or Columbia.
Most Frequently Occurring Word
This example teaches you how to find the most frequently occurring word in Excel.
You can use the MODE function to find the most frequently occurring number.
However, the MODE function only works with numbers.
You can use the COUNTIF function to count the number of occurrences of each word.
However, we are looking for a single formula that returns the most frequently occurring word (circle in our example).
To find the most frequently occurring word, execute the following steps.
1. The MATCH function returns the position of a value in a given range.
Explanation: circle (A7) found at position 2 in the range A1:A7. Set the third argument to 0 to return an exact match.
2. To find the position of the most frequently occurring word (don't be overwhelmed), we add the MODE function and replace A7 with A1:A7.
3. Finish by pressing CTRL + SHIFT + ENTER.
Note: the formula bar indicates that this is an array formula by enclosing it in curly braces {}.
Do not type these yourself.
They will disappear when you edit the formula.
In Excel 365 or Excel 2021, finish by simply pressing Enter.
You won't see curly braces.
Explanation: the range (array constant) created by the MATCH function is stored in Excel's memory, not in a range.
The array constant looks as follows:
{1;2;2;2;5;5;2} - (triangle found at position 1, circle found at position 2, circle found at position 2, etc.)
This array constant is used as an argument for the MODE function, giving a result of 2 (the position of the most frequently occurring word).
4. Use this result and the INDEX function to return the 2nd word in the range A1:A7, the most frequently occurring word.
Dynamic Arrays
Formula Example | Dynamic Array Functions | Old Array Formulas | Spill Range
Dynamic array formulas, entered into a single cell, fill multiple cells.
This behavior in Excel 365/2021 is called spilling.
Formula Example
Let's start with an easy example.
1. Fix the reference to cell E2 by placing a $ symbol in front of the column letter and row number.
2. To quickly copy the formula in cell C2 to the other cells, select cell C2, click on the lower right corner of cell C2 and drag it down to cell C7.
Check:
Explanation: the absolute reference ($E$2) stays the same, while the relative reference (B2) changes to B3, B4, B5, B6 and B7.
3. If you have Excel 365 or Excel 2021, simply enter the dynamic array formula shown below into cell C2.
4. Press Enter.
Explanation: this dynamic array (DA) formula, entered into cell C2, fills multiple cells.
This behavior in Excel 365/2021 is called spilling.
If you select a cell in the range C2:C7, a blue border appears.
5. If you select a cell in the range C3:C7, the formula in the formula bar will be greyed out.
Dynamic Array Functions
Excel 365 and Excel 2021 offer many new dynamic array functions.
Follow the links below to learn more about these functions.
1. The SORT function below sorts by the second column, in ascending order.
Note: this dynamic array function, entered into cell F2, fills multiple cells.
Wow!
2. The FILTER function below extracts all USA records.
3. The RANDARRAY function below generates random decimal numbers between 0 and 1. The array below consists of 5 rows and 2 columns.
4. The SEQUENCE function below generates a two-dimensional array.
Rows = 7, Columns = 4, Start = 0, Step = 5.
5. The UNIQUE function below (with no extra arguments) extracts unique values.
6. The XLOOKUP function below looks up the ID and returns the first name, last name and salary.
Note: if you have Excel 365 or Excel 2021, use XLOOKUP instead of VLOOKUP.
The XLOOKUP function is easier to use and has some additional advantages.
7. The SORTBY function sorts a range based on the values in a corresponding range.
Note: use 1 to sort in ascending order, use -1 to sort in descending order.
Old Array Formulas
Old array formulas still work.
The good news is, if you have Excel 365 or Excel 2021, you don't have to press CTRL + SHIFT + ENTER anymore.
Below you can find a few examples.
1. A traditional array formula finished by pressing CTRL + SHIFT + ENTER.
Explanation: this formula sums the 4 largest numbers.
2. The same formula in Excel 365/2021 finished by simply pressing Enter.
Bye bye curly braces.
3. A traditional TRANSPOSE function entered by preselecting the range E2:E4 and finished by pressing CTRL + SHIFT + ENTER.
Explanation: the TRANSPOSE function converts a horizontal range to a vertical range, or vice versa.
4. The same function in Excel 365/2021, entered into a single cell, spills to neighboring cells.
Spill Range
To refer to the values inside the blue rectangle, also called the spill range, always use the first cell and a hash character.
1. For example, the UNIQUE function below, entered into cell C1, extracts unique values.
2. The COUNTA function below uses the spill range (C1#) to count unique values.
3. If something is blocking the spill range, Excel displays the #SPILL! error.
Note: in this example, simply empty cell C6 to fix the #SPILL error.
LET function
Simple LET function | Advanced LET function
Use the LET function in Excel 365/2021 to declare variables and assign values (or calculation results) to variables.
Next, use these variables in a calculation.
Simple LET function
Let's start with an easy example.
1. The simple LET function below declares variable x (and assigns the value 2) and declares variable y (and assigns the value 5).
Note: the LET function can handle up to 126 variable/value pairs.
2. The final argument of the LET function is always a calculation.
In this example, x+y reduces to 2+5=7.
Advanced LET function
Why using the LET function in Excel? The LET function can make your formulas easier to read.
Let's take a look at a cool example.
1. The VLOOKUP function below returns the sales of ID 14.
Note: visit our page about the VLOOKUP function to learn more about this Excel function.
2. The formula below calculates a bonus (10 percent of every dollar above $5,000).
3. To write a single formula, simply replace H3 with the VLOOKUP function.
This IF formula is quite difficult to read.
Simply use the LET function to make it easier to read.
4. The LET function below declares the variable Sales and assigns a calculation result!
5. Next, use the variable Sales in a final calculation.
Note: the IF formula is now easier to understand.
This LET function has only 1 variable/value pair.
Array Manipulation
VSTACK | HSTACK | TOROW | TOCOL | WRAPROWS | WRAPCOLS | TAKE | CHOOSEROWS
Use the new array manipulation functions in Excel 365 to quickly combine, shape and resize arrays.
VSTACK
The VSTACK function in Excel 365 vertically stacks multiple arrays into a single array.
Note: the VSTACK function, entered into cell B5, fills multiple cells.
This behavior is called spilling.
HSTACK
The HSTACK function in Excel 365 horizontally stacks multiple arrays into a single array.
TOROW
The TOROW function in Excel 365 converts a 2D array into a single row.
TOCOL
The TOCOL function in Excel 365 converts a 2D array into a single column.
WRAPROWS
The WRAPROWS function converts a 1D array into a 2D array.
WRAPROWS starts a new row after a specified number of elements (second argument).
WRAPCOLS
The WRAPCOLS function converts a 1D array into a 2D array.
WRAPCOLS starts a new column after a specified number of elements (second argument).
TAKE
The TAKE function extracts a subset of an array.
You can start in each corner by using positive and negative arguments.
1. The TAKE function below extracts a 4 by 2 array (starting in the upper-left corner).
2. The TAKE function below extracts a 3 by 1 array (starting in the bottom-right corner).
CHOOSEROWS
The CHOOSEROWS function in Excel 365 returns specific rows from an array.
The CHOOSEROWS function below returns the 3rd and the 5th row from an array.
Note: use CHOOSECOLS to return specific columns from an array.
For example, download the Excel file and try to return the 2nd column from this array.Practice makes perfect!
LAMBDA
Use LAMBDA and the Name Manager in Excel to create your own Excel function.
You can use this custom function like any other Excel function!
Suppose we want to create a custom function called MYFUNCTION that multiplies two values, and then adds 1 to the result.
To create this function, execute the following steps.
1. On the Formulas tab, in the Defined Names group, click Define Name.
2. Give your function a name.
3. Use LAMBDA to create your function.
Explanation: first specify the input arguments (x and y).
Finish with a calculation to define the output of the function (x*y+1).
4. A LAMBDA function works like any other Excel function.
For example, double click the lower right corner of cell C1 to quickly copy this function to the other cells.
Note: if you like, you can use different argument names.
In this example, =LAMBDA(a,b,a*b+1) produces the exact same result! The LAMBDA function is only available in Excel 365 or Excel 2021.
Custom Sort Order
You can use Excel to sort data in a custom order.
In the example below, we would like to sort by Priority (High, Normal, Low).
1. Click any cell inside the data set.
2. On the Data tab, in the Sort & Filter group, click Sort.
The Sort dialog box appears.
3. Select Priority from the 'Sort by' drop-down list.
4. Select Custom List from the 'Order' drop-down list.
The Custom Lists dialog box appears.
5. Type the list entries.
6. Click OK.
7. Click OK again.
Result.
Records are sorted by Priority (High, Normal, Low).
Sort by Color
This example teaches you how to sort data by color in Excel.
1. Click any single cell inside a data set.
2. On the Data tab, in the Sort & Filter group, click Sort.
The Sort dialog box appears.
3. Sort by Last Name (or any other column), sort on Cell Color (you can also sort on Font Color and Cell Icon), and select the green color for the first level.
4. Click 'Copy Level' two times and select the other colors.
5. Click OK.
Result.
Reverse List
This article teaches you how to reverse the order of a list in Excel.
For example, we want to reverse the list in column A below.
1. Enter the value 1 into cell B1 and the value 2 into cell B2.
2. Select the range B1:B2, click the lower right corner of this range, and drag it down to cell B8.
3. Click any number in the list in column B.
4. To sort in descending order, on the Data tab, in the Sort & Filter group, click ZA.
Result.
Not only the list in column B, but also the list in column A has been reversed.
If you have Excel 365 or Excel 2021, use SEQUENCE, SORTBY and ROWS to sort a list in reverse order.
The following formula is pretty awesome.
5. First, use the SEQUENCE function to generate a list of numbers.
The SEQUENCE function below has 4 arguments.
Rows = 8, Columns = 1, Start = 1, Step = 1.
Note: the SEQUENCE function, entered into cell B1, fills multiple cells.
Wow! This behavior in Excel 365/2021 is called spilling.
6. The SORTBY function sorts a range based on the values in a corresponding range.
Use -1 (third argument) to sort in descending order.
7. Nest the SEQUENCE function inside the SORTBY function.
8. If you have a longer list of say 20 names, change the value 8 to 20 in the formula shown above, or even better, use the ROWS function.
Note: the ROWS function simply counts the number of rows in a range.
Randomize List
This article teaches you how to randomize (shuffle) a list in Excel.
For example, we want to randomize the list in column A below.
1. Select cell B1 and insert the RAND() function.
2. Click on the lower right corner of cell B1 and drag it down to cell B8.
3. Click any number in the list in column B.
4. To sort in descending order, on the Data tab, in the Sort & Filter group, click ZA.
Result.
A random list in column A (sorted on the random numbers above).
Note: random numbers change every time a cell on the sheet is calculated.
If you don't want this, simply copy the random numbers and paste them as values.
If you have Excel 365 or Excel 2021, use RANDARRAY, SORTBY and ROWS to randomize a list in Excel.
The following formula is pretty awesome.
5. First, use the RANDARRAY function to generate a list of random decimal numbers between 0 and 1. The array below consists of 8 rows and 1 column.
Note: the RANDARRAY function, entered into cell B1, fills multiple cells.
Wow! This behavior in Excel 365/2021 is called spilling.
6. The SORTBY function sorts a range based on the values in a corresponding range.
By default, the SORTBY function sorts in ascending order.
7. Nest the RANDARRAY function inside the SORTBY function.
8. If you have a longer list of say 20 names, change the value 8 to 20 in the formula shown above, or even better, use the ROWS function.
Note: the ROWS function simply counts the number of rows in a range.
SORT function
Use the magic SORT function in Excel 365/2021 to sort your Excel data on one column or multiple columns.
Let's give it a try.
1. The simple SORT function below has only 1 argument (A2:D15).
By default, the SORT function sorts by the first column, in ascending order.
Note: this dynamic array function, entered into cell F2, fills multiple cells.
Wow! This behavior in Excel 365/2021 is called spilling.
2. Use the second argument of the SORT function to sort by a different column.
The SORT function below sorts by the second column.
Note: only edit the formula in cell F2. Excel will do the rest.
3. Use the third argument of the SORT function to sort in a different order.
The SORT function below sorts by the first column, in descending order.
Note: use 1 to sort in ascending order, use -1 to sort in descending order.
4. To sort on multiple columns, simply supply an array constant.
For example, sort by Last Name first and Sales second.
5. The advanced SORT function below sorts by Last Name first (in ascending order) and by Sales second (in descending order).
Pretty cool, huh?
6. Finally, use the SORTBY function in Excel to sort a range based on the values in a corresponding range.
Note: use 1 to sort in ascending order, use -1 to sort in descending order.
Number and Text Filters
Number Filter | Text Filter
This example teaches you how to apply a number filter and a text filter to only display records that meet certain criteria.
1. Click any single cell inside a data set.
2. On the Data tab, in the Sort & Filter group, click Filter.
Arrows in the column headers appear.
Number Filter
To apply a number filter, execute the following steps.
3. Click the arrow next to Sales.
4. Click Number Filters (this option is available because the Sales column contains numeric data) and select Greater Than from the list.
5. Enter 10,000 and click OK.
Result.
Excel only displays the records where Sales is greater than $10,000.
Note: you can also display records equal to a value, less than a value, between two values, the top x records, records that are above average, etc.
The sky is the limit!
Text Filter
To apply a text filter, execute the following steps.
3. Click the arrow next to Last Name.
4. Click Text Filters (this option is available because the Last Name column contains text data) and select Equals from the list.
5. Enter ?m* and click OK.
Note: A question mark (?) matches exactly one character.
An asterisk (*) matches a series of zero or more characters.
Result.
Excel only displays the records where the second character of Last Name equals m.
Note: you can also display records that begin with a specific character, end with a specific character, contain or do not contain a specific character, etc.
The sky is the limit!
Date Filters
This example teaches you how to apply a date filter to only display records that meet certain criteria.
1. Click any single cell inside a data set.
2. On the Data tab, in the Sort & Filter group, click Filter.
Arrows in the column headers appear.
3. Click the arrow next to Date.
4. Click on Select All to clear all the check boxes, click the + sign next to 2015, and click the check box next to January.
5. Click OK.
Result.
Excel only displays the sales in 2015, in January.
6. Click the arrow next to Date.
7. Click on Select All to select all the check boxes.
8. Click Date Filters (this option is available because the Date column contains dates) and select Last Month from the list.
Result.
Excel only displays the sales of last month.
Note: this date filter and many other date filters depend on today's date.
Advanced Filter
And Criteria | Or Criteria | Formula as Criteria
This example teaches you how to apply an advanced filter in Excel to only display records that meet complex criteria.
When you use the Advanced Filter, you need to enter the criteria on the worksheet.
Create a Criteria range (blue border below for illustration only) above your data set.
Use the same column headers.
Be sure there's at least one blank row between your Criteria range and data set.
And Criteria
To display the sales in the USA and in Qtr 4, execute the following steps.
1. Enter the criteria shown below on the worksheet.
2. Click any single cell inside the data set.
3. On the Data tab, in the Sort & Filter group, click Advanced.
4. Click in the Criteria range box and select the range A1:D2 (blue).
5. Click OK.
Notice the options to copy your filtered data set to another location and display unique records only (if your data set contains duplicates).
Result.
No rocket science so far.
We can achieve the same result with the normal filter.
We need the Advanced Filter for Or criteria.
Or Criteria
To display the sales in the USA in Qtr 4 or in the UK in Qtr 1, execute the following steps.
6. Enter the criteria shown below on the worksheet.
7. On the Data tab, in the Sort & Filter group, click Advanced, and adjust the Criteria range to range A1:D3 (blue).
8. Click OK.
Result.
Formula as Criteria
To display the sales in the USA in Qtr 4 greater than $10.000 or in the UK in Qtr 1, execute the following steps.
9. Enter the criteria (+formula) shown below on the worksheet.
10. On the Data tab, in the Sort & Filter group, click Advanced, and adjust the Criteria range to range A1:E3 (blue).
11. Click OK.
Result.
Note: always place a formula in a new column.
Do not use a column label or use a column label that is not in your data set.
Create a relative reference to the first cell in the column (B6).
The formula must evaluate to TRUE or FALSE.
Data Form
The data form in Excel allows you to add, edit and delete records (rows) and display only those records that meet certain criteria.
Especially when you have wide rows and you want to avoid repeated scrolling to the right and left, the data form can be useful.
1. Open the downloadable Excel file.
2. Add the Form command to the Quick Access Toolbar.
3. Click the Form command.
4. Use the Find Prev and Find Next buttons to easily switch from one record (row) to another.
Note: use the New or Delete button to add or delete records.
Once you start editing a record, you can use the Restore button to undo any changes you make.
5. To display only those records that meet certain criteria, click the Criteria button.
6. Enter the criteria and click the Form button.
7. Now, when you use the Find Prev and Find Next buttons, you will only see those records that meet these criteria.
In our example, only record 13.
Note: to edit the criteria, click the Criteria button again.
To close the data form, click the Close button.
Tip: use VBA to create awesome Userforms in Excel.
Remove Duplicates
This example teaches you how to remove duplicates in Excel.
1. Click any single cell inside the data set.
2. On the Data tab, in the Data Tools group, click Remove Duplicates.
The following dialog box appears.
3. Leave all check boxes checked and click OK.
Result.
Excel removes all identical rows (blue) except for the first identical row found (yellow).
To remove rows with the same values in certain columns, execute the following steps.
4. For example, remove rows with the same Last Name and Country.
5. Check Last Name and Country and click OK.
Result.
Excel removes all rows with the same Last Name and Country (blue) except for the first instances found (yellow).
Let's take a look at one more cool Excel feature that removes duplicates.
You can use the Advanced Filter to extract unique rows (or unique values in a column).
6. On the Data tab, in the Sort & Filter group, click Advanced.
The Advanced Filter dialog box appears.
7. Click Copy to another location.
8. Click in the List range box and select the range A1:A17 (see images below).
9. Click in the Copy to box and select cell F1 (see images below).
10. Check Unique records only.
11. Click OK.
Result.
Excel removes all duplicate last names and sends the result to column F.
Note: at step 8, instead of selecting the range A1:A17, select the range A1:D17 to extract unique rows.
12. Finally, you can use conditional formatting in Excel to highlight duplicate values.
13. Or use conditional formatting in Excel to highlight duplicate rows.
Tip: visit our page about finding duplicates to learn more about these tricks.
Outlining Data
Outlining data makes your data easier to view.
In this example, we will total rows of related data and collapse a group of columns.
1. First, sort the data on the Company column.
2. On the Data tab, in the Outline group, click Subtotal.
3. Select the Company column, the column we use to outline our worksheet.
4. Use the Count function.
5. Check the Company check box.
6. Click OK.
Result:
7. To collapse a group of cells, click a minus sign.
You can use the numbers to collapse or expand groups by level.
For example, click the 2 to only show the subtotals.
Note: click the 1 to only show the Grand Count, click the 3 to show everything.
To collapse a group of columns, execute the following steps.
8. For example, select column A and B.
9. On the Data tab, in the Outline group, click Group.
10. Click the minus sign above column C (it will change to a plus sign).
Result:
11. To remove the outline, click any cell inside the data set and on the Data tab, in the Outline group, click Subtotal, Remove all.
SUBTOTAL
Rows Hidden by a Filter | Manually Hidden Rows | Automatic Subtotals
Use the SUBTOTAL function in Excel (instead of SUM, COUNT, MAX, etc.) to ignore rows hidden by a filter or to ignore manually hidden rows.
Rows Hidden by a Filter
1. For example, the SUM function below calculates the total sales.
2. Apply a filter.
3. The SUM function includes rows hidden by a filter.
4. The SUBTOTAL function ignores rows hidden by a filter and calculates the correct result.
Note: 109 is the argument for Sum if you use the SUBTOTAL function.
5. It's not easy to remember which argument belongs to which function.
Fortunately, the AutoComplete feature in Excel helps you with this.
Note: instead of using 101 (AVERAGE) for the first argument, you could also use 1 (AVERAGE), instead of using 102 (COUNT), you could also use 2 (COUNT), etc.
When filtering data, there's no difference between the numbers 101-111 and the numbers 1-11.
Manually Hidden Rows
1. For example, the SUM function below sums a range of cells.
2. Hide row 2.
3. The SUM function includes manually hidden rows.
4. The SUBTOTAL function ignores manually hidden rows and calculates the correct result.
Caution: the numbers 101-111 ignore manually hidden rows.
However, the numbers 1-11 include manually hidden rows!
Automatic Subtotals
We saved the best for last.
Excel can automatically add SUBTOTAL functions for you.
1. The first option.
Create a table and add a total row to the bottom of the table.
Next, click any cell in the last row to automatically add a SUBTOTAL function.
Explanation: in this example, we also filtered by Country.
Excel uses the SUBTOTAL function to correctly calculate the total sales in the USA.
2. The second option.
On the Data tab, in the Outline group, click Subtotal to outline your data.
Explanation: in this example, Excel automatically added 5 SUBTOTAL functions (B6, B9, B13, B19 and B20).
Follow the link for more information.
Unique Values
Extract Unique Values | Filter for Unique Values | Unique Function | Remove Duplicates
To find unique values in Excel, use the Advanced Filter.
You can extract unique values or filter for unique values.
If you have Excel 365 or Excel 2021, use the magic UNIQUE function.
Extract Unique Values
When using the Advanced Filter in Excel, always enter a text label at the top of each column of data.
1. Click a cell in the list range.
2. On the Data tab, in the Sort & Filter group, click Advanced.
The Advanced Filter dialog box appears.
3. Click Copy to another location (see image below).
4. Click in the Copy to box and select cell C1.
5. Check Unique records only.
6. Click OK.
Result:
Note: Excel removes all duplicate values (Lion in cell A7 and Elephant in cell A9) and sends the unique values to column C.
You can also use this tool to extract unique rows in Excel.
Filter for Unique Values
Filtering for unique values in Excel is a piece of cake.
1. Click a cell in the list range.
2. On the Data tab, in the Sort & Filter group, click Advanced.
3. Click Filter the list, in-place (see image below).
4. Check Unique records only.
5. Click OK.
Result:
Note: rows 7 and 9 are hidden.
To clear this filter, on the Data tab, in the Sort & Filter group, click Clear.
You can also use this tool to filter for unique rows in Excel.
Unique Function
If you have Excel 365 or Excel 2021, simply use the magic UNIQUE function to extract unique values.
1. The UNIQUE function below (with no extra arguments) extracts unique values.
Note: this dynamic array function, entered into cell C1, fills multiple cells.
Wow! This behavior in Excel 365/2021 is called spilling.
2. The UNIQUE function below extracts values that occur exactly once.
Note: the UNIQUE function has 2 optional arguments.
The default value of 0 (second argument) tells the UNIQUE function to extract values from a vertical array.
The value 1 (third argument) tells the UNIQUE function to extract values that occur exactly once.
Remove Duplicates
To find unique values (or unique rows) and delete duplicate values (or duplicate rows) at the same time, use the Remove Duplicates tool in Excel.
On the Data tab, in the Data Tools group, click Remove Duplicates.
In the example below, Excel removes all identical rows (blue) except for the first identical row found (yellow).
Note: visit our page about removing duplicates to learn more about this great Excel tool.
FILTER function
Use the magic FILTER function in Excel 365/2021 to extract records that meet certain criteria.
The FILTER function is quite versatile.
1. The simple FILTER function below has two arguments and extracts all USA records.
Note: this dynamic array function, entered into cell F2, fills multiple cells.
Wow! This behavior in Excel 365/2021 is called spilling.
2. The dynamic FILTER function below extracts all UK records.
3. The FILTER function has an optional third argument.
Use this argument to display a friendly message (instead of the #CALC! error) if no records are found.
4. Let's kick it up a notch! The FILTER function below uses the multiplication operator (*) to extract all records where Sales is greater than $10,000 and Country equals "USA".
5. The FILTER function below uses the addition operator (+) to extract all records where Last Name equals "Smith" or Last Name equals "Brown".
6. Add the SORT function to sort the records by the first column.
Note: by default, the SORT function in Excel 365/2021 sorts by the first column, in ascending order.
Manage Rules
To view all conditional formatting rules in a workbook, use the Conditional Formatting Rules Manager.
You can also use this screen to create, edit and delete rules.
1. Select cell A1.
2. On the Home tab, in the Styles group, click Conditional Formatting.
3. Click Manage Rules.
The Conditional Formatting Rules Manager appears.
Note: because we selected cell A1, Excel shows the rule applied to the range A1:A10.
4. From the drop-down list, change Current Selection to This Worksheet, to view all conditional formatting rules in this worksheet.
Note: click New Rule, Edit Rule and Delete Rule to create, edit and delete rules.
Data Bars
Data bars in Excel make it very easy to visualize values in a range of cells.
A longer bar represents a higher value.
To add data bars, execute the following steps.
1. Select a range.
2. On the Home tab, in the Styles group, click Conditional Formatting.
3. Click Data Bars and click a subtype.
Result:
Explanation: by default, the cell that holds the minimum value (0 if there are no negative values) has no data bar and the cell that holds the maximum value (95) has a data bar that fills the entire cell.
All other cells are filled proportionally.
4. Change the values.
Result.
Excel updates the data bars automatically.
Read on to further customize these data bars.
5. Select the range A1:A10.
6. On the Home tab, in the Styles group, click Conditional Formatting, Manage Rules.
7. Click Edit rule.
Excel launches the Edit Formatting Rule dialog box.
Here you can further customize your data bars (Show Bar Only, Minimum and Maximum, Bar Appearance, Negative Value and Axis, Bar Direction, etc).
Note: to directly launch this dialog box for new rules, at step 3, click More Rules.
8. Select Number from the Minimum drop-down list and enter the value 100. Select Number from the Maximum drop-down list and enter the value 150.
9. Click OK twice.
Result.
Explanation: the cell that holds the value 100 (if any) has no data bar and the cell that holds the value 150 (if any) has a data bar that fills the entire cell.
All other cells are filled proportionally.
Color Scales
Color Scales in Excel make it very easy to visualize values in a range of cells.
The shade of the color represents the value in the cell.
To add a color scale, execute the following steps.
1. Select a range.
2. On the Home tab, in the Styles group, click Conditional Formatting.
3. Click Color Scales and click a subtype.
Result:
Explanation: by default, for 3-Color scales, Excel calculates the 50th percentile (also known as median, middle value or midpoint).
The cell that holds the minimum value (9) is colored red.
The cell that holds the median (36) is colored yellow, and the cell that holds the maximum value (80) is colored green.
All other cells are colored proportionally.
Read on to further customize this color scale.
4. Select the range A1:A7.
5. On the Home tab, in the Styles group, click Conditional Formatting, Manage Rules.
6. Click Edit rule.
Excel launches the Edit Formatting Rule dialog box.
Here you can further customize your color scale (Format Style, Minimum, Midpoint and Maximum, Color, etc).
Note: to directly launch this dialog box for new rules, at step 3, click More Rules.
7. Select 2-Color Scale from the Format Style drop-down list and select white and blue.
8. Click OK twice.
Result.
Icon Sets
Icon Sets in Excel make it very easy to visualize values in a range of cells.
Each icon represents a range of values.
To add an icon set, execute the following steps.
1. Select a range.
2. On the Home tab, in the Styles group, click Conditional Formatting.
3. Click Icon Sets and click a subtype.
Result:
Explanation: by default, for 3 icons, Excel calculates the 67th percent and 33th percent.
67th percent = min + 0.67 * (max-min) = 2 + 0.67 * (95-2) = 64.31. 33th percent = min + 0.33 * (max-min) = 2 + 0.33 * (95-2) = 32.69. A green arrow will show for values equal to or greater than 64.31. A yellow arrow will show for values less than 64.31 and equal to or greater than 32.69. A red arrow will show for values less than 32.69.
4. Change the values.
Result.
Excel updates the icon set automatically.
Read on to further customize this icon set.
5. Select the range A1:A10.
6. On the Home tab, in the Styles group, click Conditional Formatting, Manage Rules.
7. Click Edit rule.
Excel launches the Edit Formatting Rule dialog box.
Here you can further customize your icon set (Icon Style, Reverse Icon Order, Show Icon Only, Icon, Value, Type, etc).
Note: to directly launch this dialog box for new rules, at step 3, click More Rules.
8. Select 3 symbols (Uncircled) from the Icon Style drop-down list.
Select No Cell Icon from the second Icon drop-down list.
Change the Types to Number and change the Values to 100 and 0. Select the greater than symbol (>) next to the value 0.
9. Click OK twice.
Result.
Find Duplicates
Duplicate Values | Triplicates | Duplicate Rows
This example teaches you how to find duplicate values (or triplicates) and how to find duplicate rows in Excel.
Duplicate Values
To find and highlight duplicate values in Excel, execute the following steps.
1. Select the range A1:C10.
2. On the Home tab, in the Styles group, click Conditional Formatting.
3. Click Highlight Cells Rules, Duplicate Values.
4. Select a formatting style and click OK.
Result.
Excel highlights the duplicate names.
Note: select Unique from the first drop-down list to highlight the unique names.
Triplicates
By default, Excel highlights duplicates (Juliet, Delta), triplicates (Sierra), etc.
(see previous image).
Execute the following steps to highlight triplicates only.
1. First, clear the previous conditional formatting rule.
2. Select the range A1:C10.
3. On the Home tab, in the Styles group, click Conditional Formatting.
4. Click New Rule.
5. Select 'Use a formula to determine which cells to format'.
6. Enter the formula =COUNTIF($A$1:$C$10,A1)=3
7. Select a formatting style and click OK.
Result.
Excel highlights the triplicate names.
Explanation: =COUNTIF($A$1:$C$10,A1) counts the number of names in the range A1:C10 that are equal to the name in cell A1. If COUNTIF($A$1:$C$10,A1) = 3, Excel formats cell A1. Always write the formula for the upper-left cell in the selected range (A1:C10).
Excel automatically copies the formula to the other cells.
Thus, cell A2 contains the formula =COUNTIF($A$1:$C$10,A2)=3, cell A3 =COUNTIF($A$1:$C$10,A3)=3, etc.
Notice how we created an absolute reference ($A$1:$C$10) to fix this reference.
Note: you can use any formula you like.
For example, use this formula =COUNTIF($A$1:$C$10,A1)>3 to highlight names that occur more than 3 times.Duplicate Rows
To find and highlight duplicate rows in Excel, use COUNTIFS (with the letter S at the end) instead of COUNTIF.
1. Select the range A1:C10.
2. On the Home tab, in the Styles group, click Conditional Formatting.
3. Click New Rule.
4. Select 'Use a formula to determine which cells to format'.
5. Enter the formula =COUNTIFS(Animals,$A1,Continents,$B1,Countries,$C1)>1
6. Select a formatting style and click OK.
Note: the named range Animals refers to the range A1:A10, the named range Continents refers to the range B1:B10 and the named range Countries refers to the range C1:C10. =COUNTIFS(Animals,$A1,Continents,$B1,Countries,$C1) counts the number of rows based on multiple criteria (Leopard, Africa, Zambia).
Result.
Excel highlights the duplicate rows.
Explanation: if COUNTIFS(Animals,$A1,Continents,$B1,Countries,$C1) > 1, in other words, if there are multiple (Leopard, Africa, Zambia) rows, Excel formats cell A1. Always write the formula for the upper-left cell in the selected range (A1:C10).
Excel automatically copies the formula to the other cells.
We fixed the reference to each column by placing a $ symbol in front of the column letter ($A1, $B1 and $C1).
As a result, cell A1, B1 and C1 contain the same formula, cell A2, B2 and C2 contain the formula =COUNTIFS(Animals,$A2,Continents,$B2,Countries,$C2)>1, etc.
7. Finally, you can use the Remove Duplicates tool in Excel to quickly remove duplicate rows.
On the Data tab, in the Data Tools group, click Remove Duplicates.
In the example below, Excel removes all identical rows (blue) except for the first identical row found (yellow).
Note: visit our page about removing duplicates to learn more about this great Excel tool.
Shade Alternate Rows
Use Conditional Formatting | Apply a Table Style
To shade alternate rows in Excel, use conditional formatting or apply a table style.
Coloring every other row makes it easier to read your data.
Use Conditional Formatting
First, let's use conditional formatting to shade/highlight every other row in Excel.
1. For example, select the range A1:D15 below.
Note: to apply the shading to the entire worksheet, select all cells on a worksheet by clicking the Select All button (see orange arrow).
2. On the Home tab, in the Styles group, click Conditional Formatting.
3. Click New Rule.
4. Select 'Use a formula to determine which cells to format'.
5. Enter the formula =MOD(ROW(),2)=0
6. Select a formatting style and click OK.
Result.
Explanation: the MOD function gives the remainder of a division.
The ROW function returns the row number of a cell.
For example, for the seventh row, MOD(7,2) = 1 because 7 divided by 2 equals 3 with a remainder of 1. For the eight row, MOD(8,2) = 0 because 8 divided by 2 equals 4 with a remainder of 0. As a result, all cells in even rows return 0 and will be shaded.Apply a Table Style
If you're not a formula hero, apply a table style to quickly color alternate rows in Excel.
1. Select any cell within a range.
2. On the Home tab, in the Styles group, click Format as Table.
3. Choose a table style with alternate row shading.
4. Click OK.
Result.
To change the color shading from rows to columns, execute the following steps.
5. First, select a cell inside the table.
Next, on the Table Design tab, in the Table Styles Options group, uncheck Banded Rows and check Banded Columns.
Result.
Note: use the filter arrows to sort and filter this table.
Visit our chapter about tables to learn more about this topic.
To convert this table into a normal range of cells (with banded rows or banded columns), execute the following steps.
6. First, select a cell inside the table.
Next, on the Table Design tab, in the Tools group, click Convert to Range.
Result.
Tip: use Excel VBA to highlight the row and column of the Active Cell (selected cell).
This program will amaze and impress your boss.
Compare Two Lists
This example describes how to compare two lists using conditional formatting.
For example, you may have two lists of NFL teams.
To highlight the teams in the first list that are not in the second list, execute the following steps.
1. First, select the range A1:A18 and name it firstList, select the range B1:B20 and name it secondList.
2. Next, select the range A1:A18.
3. On the Home tab, in the Styles group, click Conditional Formatting.
4. Click New Rule.
5. Select 'Use a formula to determine which cells to format'.
6. Enter the formula =COUNTIF(secondList,A1)=0
7. Select a formatting style and click OK.
Result.
Miami Dolphins and Tennessee Titans are not in the second list.
Explanation: =COUNTIF(secondList,A1) counts the number of teams in secondList that are equal to the team in cell A1. If COUNTIF(secondList,A1) = 0, the team in cell A1 is not in the second list.
As a result, Excel fills the cell with a blue background color.
Always write the formula for the upper-left cell in the selected range (A1:A18).
Excel automatically copies the formula to the other cells.
Thus, cell A2 contains the formula =COUNTIF(secondList,A2)=0, cell A3 =COUNTIF(secondList,A3)=0, etc.
8. To highlight the teams in the second list that are not in the first list, select the range B1:B20, create a new rule using the formula =COUNTIF(firstList,B1)=0, and set the format to orange fill.
Result.
Denver Broncos, Arizona Cardinals, Minnesota Vikings and Pittsburgh Steelers are not in the first list.
Conflicting Rules
Sometimes multiple conditional formatting rules in Excel conflict.
A higher rule always wins.
This example illustrates two different results.
1. The value 95 is higher than 80 but is also the highest value (Top 1).
The formats (yellow fill vs green fill and yellow text color vs green text color) conflict.
A higher rule always wins.
As a result, the value 95 is colored yellow.
Result:
2. Move the second rule up.
The value 95 is the highest value (Top 1) but is also higher than 80. The formats (green fill vs yellow fill and green text color vs yellow text color) conflict.
A higher rule always wins.
As a result, the value 95 is colored green.
Result:
Note: only use the Stop If True check boxes for backwards compatibility with earlier versions of Microsoft Excel.
Heat Map
To create a heat map in Excel, simply use conditional formatting.
A heat map is a graphical representation of data where individual values are represented as colors.
To create a heat map, execute the following steps.
1. Select the range B3:M11.
2. On the Home tab, in the Styles group, click Conditional Formatting.
3. Click Color Scales and click a subtype.
Result.
A heat map with numbers.
4. Select the range B3:M11.
5. Right click, and then click Format Cells (or press CTRL + 1).
6. Select the Custom category.
7. Type the following number format code: ;;;
8. Click OK.
Result.
A heat map in Excel.
Note: you can clearly see that the summer of 2014 in New York was cool and that Christmas 2015 in New York was warm.
Column Chart
Column charts are used to compare values across categories by using vertical bars.
To create a column chart, execute the following steps.
1. Select the range A1:A7, hold down CTRL, and select the range C1:D7.
2. On the Insert tab, in the Charts group, click the Column symbol.
3. Click Clustered Column.
Result:
Note: only if you have numeric labels, empty cell A1 before you create the column chart.
By doing this, Excel does not recognize the numbers in column A as a data series and automatically places these numbers on the horizontal (category) axis.
After creating the chart, you can enter the text Year into cell A1 if you like.
Line Chart
Line charts are used to display trends over time.
Use a line chart if you have text labels, dates or a few numeric labels on the horizontal axis.
Use a scatter plot (XY chart) to show scientific XY data.
To create a line chart, execute the following steps.
1. Select the range A1:D7.
2. On the Insert tab, in the Charts group, click the Line symbol.
3. Click Line with Markers.
Result:
Note: only if you have numeric labels, empty cell A1 before you create the line chart.
By doing this, Excel does not recognize the numbers in column A as a data series and automatically places these numbers on the horizontal (category) axis.
After creating the chart, you can enter the text Year into cell A1 if you like.
Let's customize this line chart.
To change the data range included in the chart, execute the following steps.
4. Select the line chart.
5. On the Chart Design tab, in the Data group, click Select Data.
6. Uncheck Dolphins and Whales and click OK.
Result:
To change the color of the line and the markers, execute the following steps.
7. Right click the line and click Format Data Series.
The Format Data Series pane appears.
8. Click the paint bucket icon and change the line color.
9. Click Marker and change the fill color and border color of the markers.
Result:
To add a trendline, execute the following steps.
10. Select the line chart.
11. Click the + button on the right side of the chart, click the arrow next to Trendline and then click More Options.
The Format Trendline pane appears.
12. Choose a Trend/Regression type.
Click Linear.
13. Specify the number of periods to include in the forecast.
Type 2 in the Forward box.
Result:
To change the axis type to Date axis, execute the following steps.
14. Right click the horizontal axis, and then click Format Axis.
The Format Axis pane appears.
15. Click Date axis.
Result:
Conclusion: the trendline predicts a population of approximately 250 bears in 2024.
Pie Chart
Pie charts are used to display the contribution of each value (slice) to a total (pie).
Pie charts always use one data series.
To create a pie chart of the 2017 data series, execute the following steps.
1. Select the range A1:D2.
2. On the Insert tab, in the Charts group, click the Pie symbol.
3. Click Pie.
Result:
4. Click on the pie to select the whole pie.
Click on a slice to drag it away from the center.
Result:
Note: only if you have numeric labels, empty cell A1 before you create the pie chart.
By doing this, Excel does not recognize the numbers in column A as a data series and automatically creates the correct chart.
After creating the chart, you can enter the text Year into cell A1 if you like.
Let's create one more cool pie chart.
5. Select the range A1:D1, hold down CTRL and select the range A3:D3.
6. Create the pie chart (repeat steps 2-3).
7. Click the legend at the bottom and press Delete.
8. Select the pie chart.
9. Click the + button on the right side of the chart and click the check box next to Data Labels.
10. Click the paintbrush icon on the right side of the chart and change the color scheme of the pie chart.
Result:
11. Right click the pie chart and click Format Data Labels.
12. Check Category Name, uncheck Value, check Percentage and click Center.
Result:
Note: right click the data labels and click Font to change the font size and font color of the data labels.
Bar Chart
A bar chart is the horizontal version of a column chart.
Use a bar chart if you have large text labels.
To create a bar chart, execute the following steps.
1. Select the range A1:B6.
2. On the Insert tab, in the Charts group, click the Column symbol.
3. Click Clustered Bar.
Result:
Area Chart
An area chart is a line chart with the areas below the lines filled with colors.
Use a stacked area chart to display the contribution of each value to a total over time.
To create an area chart, execute the following steps.
1. Select the range A1:D7.
2. On the Insert tab, in the Charts group, click the Line symbol.
3. Click Area.
Result.
In this example, some areas overlap.
Below you can find the corresponding line chart to clearly see this.
4. Change the chart's subtype to Stacked Area (the one next to Area).
Result:
Note: only if you have numeric labels, empty cell A1 before you create the area chart.
By doing this, Excel does not recognize the numbers in column A as a data series and automatically places these numbers on the horizontal (category) axis.
After creating the chart, you can enter the text Year into cell A1 if you like.
Scatter Plot
Only Markers | Straight Lines
Use a scatter plot (XY chart) to show scientific XY data.
Scatter plots are often used to find out if there's a relationship between variable X and Y.
Only Markers
To find out if there is a relationship between X (a person's salary) and Y (his/her car price), execute the following steps.
1. Select the range A1:B10.
2. On the Insert tab, in the Charts group, click the Scatter symbol.
3. Click Scatter.
Result:
Note: we added a trendline to clearly see the relationship between these two variables.
Straight Lines
To create a scatter plot with straight lines, execute the following steps.
1. Select the range A1:D22.
2. On the Insert tab, in the Charts group, click the Scatter symbol.
3. Click Scatter with Straight Lines.
Note: also see the subtype Scatter with Smooth Lines.
Result:
Note: we added a horizontal and vertical axis title.
The horizontal axis of a scatter plot is a value axis, so you have more axis scaling options (the same as a vertical axis which always is a value axis).
Data Series
Select Data Source | Switch Row/Column | Add, Edit, Remove and Move
A row or column of numbers that are plotted in a chart is called a data series.
You can plot one or more data series in a chart.
To create a column chart, execute the following steps.
1. Select the range A1:D7.
2. On the Insert tab, in the Charts group, click the Column symbol.
3. Click Clustered Column.
Result:
Select Data Source
To launch the Select Data Source dialog box, execute the following steps.
1. Select the chart.
Right click, and then click Select Data.
The Select Data Source dialog box appears.
2. You can find the three data series (Bears, Dolphins and Whales) on the left and the horizontal axis labels (Jan, Feb, Mar, Apr, May and Jun) on the right.
Switch Row/Column
If you click Switch Row/Column, you'll have 6 data series (Jan, Feb, Mar, Apr, May and Jun) and three horizontal axis labels (Bears, Dolphins and Whales).
Result:
Add, Edit, Remove and Move
You can use the Select Data Source dialog box to add, edit, remove and move data series, but there's a quicker way.
1. Select the chart.
2. Simply change the range on the sheet.
Result:
Axes
Axis Type | Axis Titles | Axis Scale
Most chart types have two axes: a horizontal axis (or x-axis) and a vertical axis (or y-axis).
This example teaches you how to change the axis type, add axis titles and how to change the scale of the vertical axis.
To create a column chart, execute the following steps.
1. Select the range A1:B7.
2. On the Insert tab, in the Charts group, click the Column symbol.
3. Click Clustered Column.
Result:
Axis Type
Excel also shows the dates between 8/24/2018 and 9/1/2018. To remove these dates, change the axis type from Date axis to Text axis.
1. Right click the horizontal axis, and then click Format Axis.
The Format Axis pane appears.
2. Click Text axis.
Result:
Axis Titles
To add a vertical axis title, execute the following steps.
1. Select the chart.
2. Click the + button on the right side of the chart, click the arrow next to Axis Titles and then click the check box next to Primary Vertical.
3. Enter a vertical axis title.
For example, Visitors.Result:
Axis Scale
By default, Excel automatically determines the values on the vertical axis.
To change these values, execute the following steps.
1. Right click the vertical axis, and then click Format Axis.
The Format Axis pane appears.
2. Fix the maximum bound to 10000.
3. Fix the major unit to 2000.
Result:
Trendline
This example teaches you how to add a trendline to a chart in Excel.
1. Select the chart.
2. Click the + button on the right side of the chart, click the arrow next to Trendline and then click More Options.
The Format Trendline pane appears.
3. Choose a Trend/Regression type.
Click Linear.
4. Specify the number of periods to include in the forecast.
Type 3 in the Forward box.
5. Check "Display Equation on chart" and "Display R-squared value on chart".
Result:
Explanation: Excel uses the method of least squares to find a line that best fits the points.
The R-squared value equals 0.9295, which is a good fit.
The closer to 1, the better the line fits the data.
The trendline predicts 120 sold Wonka bars in period 13. You can verify this by using the equation.
y = 7.7515 * 13 + 18.267 = 119.0365.
6. Instead of using this equation, you can use the FORECAST.LINEAR function in Excel.
This function predicts the same future values.
7. The FORECAST.ETS function in Excel predicts a future value using Exponential Triple Smoothing, which takes into account seasonality.
Tip: visit our page about forecasting to learn more about these functions.
Error Bars
This example teaches you how to add error bars to a chart in Excel.
1. Select the chart.
2. Click the + button on the right side of the chart, click the arrow next to Error Bars and then click More Options.
Notice the shortcuts to quickly display error bars using the Standard Error, a percentage value of 5% or 1 standard deviation.
The Format Error Bars pane appears.
3. Choose a Direction.
Click Both.
4. Choose an End Style.
Click Cap.
5. Click Fixed value and enter the value 10.
Result:
Note: if you add error bars to a scatter plot, Excel also adds horizontal error bars.
In this example, these error bars have been removed.
The vertical error bar in period 1 predicts 10 to 30 sold Wonka bars, the vertical error bar in period 2 predicts 22 to 42 sold Wonka bars, etc.
Sparklines
Create Sparklines | Customize Sparklines | Sparkline Types | Sparkline Axes | Hidden and Empty Cells
Sparklines in Excel are graphs that fit in one cell.
Sparklines are great for displaying trends.
Excel offers three sparkline types: Line, Column and Win/Loss.
Create Sparklines
To create sparklines, execute the following steps.
1. Select the cells where you want the sparklines to appear.
In this example, we select the range G2:G4.
2. On the Insert tab, in the Sparklines group, click Line.
3. Click in the Data Range box and select the range B2:F4.
4. Click OK.
Result:
5. Change the value in cell F2 to 1186.
Result.
Excel automatically updates the sparkline.
Customize Sparklines
To customize sparklines, execute the following steps.
1. Select the sparklines.
2. On the Sparkline tab, in the Show group, check High Point and Low Point.
Result:
Note: to make the sparklines larger, simply change the row height and column width of the sparkline cells.
3. On the Sparkline tab, in the Style group, choose a nice visual style.
Result:
Note: the high points are colored green now and the low points are colored red.
To delete a sparkline, execute the following steps.
4. Select 1 or more sparklines.
5. On the Sparkline tab, in the Group group, click Clear.
Note: when creating multiple sparklines at once (one for each row or column of data), your sparklines are grouped.
To customize each sparkline individually, first select the grouped sparklines and click Ungroup.
Sparkline Types
Excel offers three sparkline types: Line, Column and Win/Loss.
You can easily change to a different type of sparkline at any time.
1. Below you can find the Line sparklines we created in the previous two paragraphs.
2. Select the Line sparklines.
3. On the Sparkline tab, in the Type group, click Column.
Result:
4. Select the column sparklines.
5. On the Sparkline tab, in the Type group, click Win/Loss.
6. On the Sparkline tab, in the Show group, uncheck High Point and Low Point and check Negative Points.
Result:
Note: we changed the data to negative and positive values.
A win/loss sparkline only shows whether each value is positive (win) or negative (loss).
Sparkline Axes
By default, each sparkline has its own vertical scale.
The maximum value is plotted at the top of the cell.
The minimum value is plotted at the bottom of the cell.
1. Below you can find the column sparklines we created in the previous paragraph.
Note: all green bars have the same height, but the maximum values (B2, E3 and F4) are different!
2. Select the column sparklines.
3. On the Sparkline tab, in the Group group, click Axis.
4. Under Vertical Axis Minimum Value Options and Vertical Axis Maximum Value Options, select Same for All Sparklines.
Result:
Conclusion: now you can clearly see that the earnings of Jack are much higher.
5. Here's another cool little trick.
Below you can find three sparklines with negative values.
6. Select the sparklines.
7. On the Sparkline tab, in the Group group, click Axis.
8. Under Horizontal Axis Options, click Show Axis.
9. On the Sparkline tab, in the Show group, check Negative Points.
Result:
Note: the horizontal axis only appears if the sparkline has data that crosses the zero axis.
On the Sparkline tab, in the Style group, click Marker Color to change the color of the negative points.
Hidden and Empty Cells
By default, Excel does not show hidden data in a sparkline and empty cells are shown as gaps.
1. Select 1 or more sparklines.
2. On the Sparkline tab, in the Sparkline group, click Edit Data.
3. Click Hidden & Empty cells.
The following dialog box appears.
Note: to show hidden data in a sparkline, check "Show data in hidden rows and columns".
4. You can show empty cells as gaps (first sparkline below), zero (second sparkline below) or connect the data points with a line (third sparkline below).
Note: now it's your turn! Download the Excel file and try to create a few sparklines.
Practice makes perfect.
Combination Chart
A combination chart is a chart that combines two or more chart types in a single chart.
To create a combination chart, execute the following steps.
1. Select the range A1:C13.
2. On the Insert tab, in the Charts group, click the Combo symbol.
3. Click Create Custom Combo Chart.
The Insert Chart dialog box appears.
4. For the Rainy Days series, choose Clustered Column as the chart type.
5. For the Profit series, choose Line as the chart type.
6. Plot the Profit series on the secondary axis.
7. Click OK.
Result:
Gauge Chart
A gauge chart (or speedometer chart) combines a Doughnut chart and a Pie chart in a single chart.
If you are in a hurry, simply download the Excel file.
This is what the spreadsheet looks like.
To create a gauge chart, execute the following steps.
1. Select the range H2:I6.
Note: the Donut series has 4 data points and the Pie series has 3 data points.
2. On the Insert tab, in the Charts group, click the Combo symbol.
3. Click Create Custom Combo Chart.
The Insert Chart dialog box appears.
4. For the Donut series, choose Doughnut (fourth option under Pie) as the chart type.
5. For the Pie series, choose Pie as the chart type.
6. Plot the Pie series on the secondary axis.
7. Click OK.
8. Remove the chart title and the legend.
9. Select the chart.
On the Format tab, in the Current Selection group, select the Pie series.
10. On the Format tab, in the Current Selection group, click Format Selection and change the angle of the first slice to 270 degrees.
11. Hold down CTRL and use the ← and → keys to select a single data point.
On the Format tab, in the Shape Styles group, change the Shape Fill of each point.
Point 1 = No Fill, point 2 = black and point 3 = No Fill.
Result:
Explanation: the Pie chart is nothing more than a transparent slice of 75 points, a black slice of 1 point (the needle) and a transparent slice of 124 points.
12. Repeat steps 9 to 11 for the Donut series.
Point 1 = red, point 2 = yellow, point 3 = green and point 4 = No Fill.
Result:
13. Select the chart.
On the Format tab, in the Current Selection group, select the Chart Area.
In the Shape Styles group, change the Shape Fill to No fill and the Shape Outline to No Outline.
14. Use the Spin Button to change the value in cell I3 from 75 to 76. The Pie chart changes to a transparent slice of 76 points, a black slice of 1 point (the needle), and a transparent slice of 200 - 1 - 76 = 123 points.
The formula in cell I5 ensures that the 3 slices sum up to 200 points.
Thermometer Chart
This example teaches you how to create a thermometer chart in Excel.
A thermometer chart shows you how much of a goal has been achieved.
To create a thermometer chart, execute the following steps.
1. Select cell B16.
Note: adjacent cells should be empty.
2. On the Insert tab, in the Charts group, click the Column symbol.
3. Click Clustered Column.
Result:
Further customize the chart.
4. Remove the chart tile and the horizontal axis.
5. Right click the blue bar, click Format Data Series and change the Gap Width to 0%.
6. Change the width of the chart.
7. Right click the percentages on the chart, click Format Axis, fix the minimum bound to 0, the maximum bound to 1 and set the Major tick mark type to Outside.
Result:
Gantt Chart
Excel does not offer Gantt as chart type, but it's easy to create a Gantt chart by customizing the stacked bar chart type.
Below you can find our Gantt chart data.
To create a Gantt chart, execute the following steps.
1. Select the range A3:C11.
2. On the Insert tab, in the Charts group, click the Column symbol.
3. Click Stacked Bar.
Result:
4. Enter a title by clicking on Chart Title.
For example, Build a House.
5. Click the legend at the bottom and press Delete.
6. The tasks (Foundation, Walls, etc.) are in reverse order.
Right click the tasks on the chart, click Format Axis and check 'Categories in reverse order'.
Result:
7. Right click the blue bars, click Format Data Series, Fill & Line icon, Fill, No fill.
8. Dates and times are stored as numbers in Excel and count the number of days since January 0, 1900. 1-jun-2017 (start) is the same as 42887. 15-jul-2017 (end) is the same as 42931. Right click the dates on the chart, click Format Axis and fix the minimum bound to 42887, maximum bound to 42931 and Major unit to 7.
Result.
A Gantt chart in Excel.
Note that the plumbing and electrical work can be executed simultaneously.
Pareto Chart
Excel 2016 or later | All Versions
This example teaches you how to create a Pareto chart in Excel.
The Pareto principle states that, for many events, roughly 80% of the effects come from 20% of the causes.
In this example, we will see that roughly 80% of the complaints come from 20% of the complaint types.
Excel 2016 or later
To create a Pareto chart in Excel 2016 or later, execute the following steps.
1. Select the range A3:B13.
2. On the Insert tab, in the Charts group, click the Histogram symbol.
3. Click Pareto.
Result:
Note: a Pareto chart combines a column chart and a line graph.
4. Enter a chart title.
5. Click the + button on the right side of the chart and click the check box next to Data Labels.
Result:
Conclusion: the orange Pareto line shows that (789 + 621) / 1722 ≈ 80% of the complaints come from 2 out of 10 = 20% of the complaint types (Overpriced and Small portions).
In other words: the Pareto principle applies.
All Versions
If you don't have Excel 2016 or later, simply create a Pareto chart by combining a column chart and a line graph.
This method works with all versions of Excel.
1. First, select a number in column B.
2. Next, sort your data in descending order.
On the Data tab, in the Sort & Filter group, click ZA.
3. Calculate the cumulative count.
Enter the formula shown below into cell C5 and drag the formula down.
4. Calculate the cumulative %.
Enter the formula shown below into cell D4 and drag the formula down.
Note: cell C13 contains the total number of complaints.
When we drag this formula down, the absolute reference ($C$13) stays the same, while the relative reference (C4) changes to C5, C6, C7, etc.
5. Select the data in column A, B and D.
To achieve this, hold down CTRL and select each range.
6. On the Insert tab, in the Charts group, click the Column symbol.
7. Click Clustered Column.
8. Right click on the orange bars (Cumulative %) and click Change Series Chart Type...
The Change Chart Type dialog box appears.
9. For the Cumulative % series, choose Line with Markers as the chart type.
10. Plot the Cumulative % series on the secondary axis.
11. Click OK.
Note: Excel 2010 does not offer combo chart as one of the built-in chart types.
If you're using Excel 2010, instead of executing steps 8-10, simply select Line with Markers and click OK.
Next, right click on the orange/red line and click Format Data Series.
Select Secondary Axis and click Close.
12. Right click the percentages on the chart, click Format Axis and set the Maximum to 100.
Result:
Conclusion: the Pareto chart shows that 80% of the complaints come from 20% of the complaint types (Overpriced and Small portions).
In other words: the Pareto principle applies.
Group Pivot Table Items
Group Products | Group Dates
This example teaches you how to group pivot table items.
Learn how to group products and how to group dates by quarters.
Below you can find a pivot table.
Go back to Pivot Tables to learn how to create this pivot table.
Group Products
The Product field contains 7 items.
Apple, Banana, Beans, Broccoli, Carrots, Mango and Orange.
To create two groups, execute the following steps.
1. In the pivot table, select Apple and Banana.
2. Right click and click on Group.
3. In the pivot table, select Beans, Broccoli, Carrots, Mango and Orange.
4. Right click and click on Group.
Result:
Note: to change the name of a group (Group1 or Group2), select the name, and edit the name in the formula bar.
To ungroup, select the group, right click and click on Ungroup.
5. To collapse the groups, click the minus signs.
Conclusion: Apple and Banana (Group1) have a higher total than all the other products (Group2) together.
Group Dates
To create the pivot table below, instead of the Product field, add the Date field to the Rows area.
The Date field contains many items.
6-Jan, 7-Jan, 8-Jan, 10-Jan, 11-Jan, etc.
To group these dates by quarters, execute the following steps.
1. Click any cell inside the column with dates.
2. Right click and click on Group.
3. Select Quarters and click OK.
Note: also see the options to group by seconds, minutes, hours, etc.
Result:
Conclusion: Quarter 2 is the best quarter.
Multi-level Pivot Table
Multiple Row Fields | Multiple Value Fields | Multiple Report Filter Fields
It's perfectly ok to drag more than one field to an area in a pivot table.
We will look at an example of multiple row fields, multiple value fields and multiple report filter fields.
Remember, our data set consists of 213 records and 6 fields.
Order ID, Product, Category, Amount, Date and Country.
Multiple Row Fields
First, insert a pivot table.
Next, drag the following fields to the different areas.
1. Category field and Country field to the Rows area.
2. Amount field to the Values area.
Below you can find the multi-level pivot table.
Multiple Value Fields
First, insert a pivot table.
Next, drag the following fields to the different areas.
1. Country field to the Rows area.
2. Amount field to the Values area (2x).
Note: if you drag the Amount field to the Values area for the second time, Excel also populates the Columns area.
Pivot table:
3. Next, click any cell inside the Sum of Amount2 column.
4. Right click and click on Value Field Settings.
5. Enter Percentage for Custom Name.
6. On the Show Values As tab, select % of Grand Total.
7. Click OK.
Result:
Multiple Report Filter Fields
First, insert a pivot table.
Next, drag the following fields to the different areas.
1. Order ID to the Rows area.
2. Amount field to the Values area.
3. Country field and Product field to the Filters area.
4. Next, select United Kingdom from the first filter drop-down and Broccoli from the second filter drop-down.
The pivot table shows all the 'Broccoli' orders to the United Kingdom.
Frequency Distribution
Did you know that you can use pivot tables to easily create a frequency distribution in Excel? You can also use the Analysis Toolpak to create a histogram.
Remember, our data set consists of 213 records and 6 fields.
Order ID, Product, Category, Amount, Date and Country.
First, insert a pivot table.
Next, drag the following fields to the different areas.
1. Amount field to the Rows area.
2. Amount field (or any other field) to the Values area.
3. Click any cell inside the Sum of Amount column.
4. Right click and click on Value Field Settings.
5. Choose Count and click OK.
6. Next, click any cell inside the column with Row Labels.
7. Right click and click on Group.
8. Enter 1 for Starting at, 10000 for Ending at, and 1000 for By.
9. Click OK.
Result:
To easily compare these numbers, create a pivot chart.
10. Click any cell inside the pivot table.
11. On the PivotTable Analyze tab, in the Tools group, click PivotChart.
The Insert Chart dialog box appears.
12. Click OK.
Result:
Pivot Chart
Insert Pivot Chart | Filter Pivot Chart | Change Pivot Chart Type
A pivot chart is the visual representation of a pivot table in Excel.
Pivot charts and pivot tables are connected with each other.
Below you can find a two-dimensional pivot table.
Go back to Pivot Tables to learn how to create this pivot table.
Insert Pivot Chart
To insert a pivot chart, execute the following steps.
1. Click any cell inside the pivot table.
2. On the PivotTable Analyze tab, in the Tools group, click PivotChart.
The Insert Chart dialog box appears.
3. Click OK.
Below you can find the pivot chart.
This pivot chart will amaze and impress your boss.
Note: any changes you make to the pivot chart are immediately reflected in the pivot table and vice versa.
Filter Pivot Chart
To filter this pivot chart, execute the following steps.
1. Use the standard filters (triangles next to Product and Country).
For example, use the Country filter to only show the total amount of each product exported to the United States.
2. Remove the Country filter.
3. Because we added the Category field to the Filters area, we can filter this pivot chart (and pivot table) by Category.
For example, use the Category filter to only show the vegetables exported to each country.
Change Pivot Chart Type
You can change to a different type of pivot chart at any time.
1. Select the chart.
2. On the Design tab, in the Type group, click Change Chart Type.
3. Choose Pie.
4. Click OK.
Result:
Note: pie charts always use one data series (in this case, Beans).
To get a pivot chart of a country, swap the data over the axis.
First, select the chart.
Next, on the Design tab, in the Data group, click Switch Row/Column.
Slicers
Use slicers in Excel to quickly and easily filter pivot tables.
Connect multiple slicers to multiple pivot tables to create awesome reports.
Below you can find a pivot table.
Go back to Pivot Tables to learn how to create this pivot table.
To insert a slicer, execute the following steps.
1. Click any cell inside the pivot table.
2. On the PivotTable Analyze tab, in the Filter group, click Insert Slicer.
3. Check Country and click OK.
4. Click United States to find out which products we export the most to the United States.
Conclusion: bananas are our main export product to the United States.
The report filter (cell B1) changes to United States.
OK, that was pretty easy.
Let's insert a second slicer.
5. Click any cell inside the pivot table.
6. On the PivotTable Analyze tab, in the Filter group, click Insert Slicer.
7. Check Product and click OK.
8. Select the slicer.
9. On the Slicer tab, in the Slicer Styles group, click a slicer style.
10. Use the second slicer.
Click the Multi-Select button to select multiple products.
Note: instead of using the Multi-Select button, hold down CTRL to select multiple items.
To really impress your boss, execute the following steps.
11. Insert a second pivot table.
To connect both slicers to this pivot table, execute the following steps.
12. Select the first slicer.
13. On the Slicer tab, in the Slicer group, click Report Connections.
14. Select the second pivot table and click OK.
15. Repeat steps 12-14 for the second slicer.
16. Use both slicers.
Conclusion: the total amount of apples exported to Canada equals $24,867 (6 orders) and the total amount of oranges exported to Canada equals $19,929 (3 orders).
17. Click the icon in the upper-right corner of a slicer to clear the filter.
Note: we didn't export any beans or carrots to Canada.
Try it yourself, download the Excel file and use slicers to create awesome reports.
Update Pivot Table
Refresh | Change Data Source
Any changes you make to the data set are not automatically picked up by the pivot table.
Refresh the pivot table or change the data source to update the pivot table with the applied changes.
Refresh
If you change any of the text or numbers in your data set, you need to refresh the pivot table.
1. Click any cell inside the pivot table.
2. Right click and click on Refresh.
To refresh a pivot table automatically when opening an Excel file, execute the following steps.
3. Click any cell inside the pivot table.
4. On the PivotTable Analyze tab, in the PivotTable group, click Options.
Excel shows the PivotTable Options dialog box.
5. On the Data tab, check "Refresh data when opening the file".
6. Click OK.
From now on, whenever you open this Excel file, Excel will automatically refresh this pivot table (and all other pivot tables with this source data in this Excel file).
Change Data Source
If you change the size of your data set by adding or deleting rows/columns, you need to update the source data for the pivot table.
1. Click any cell inside the pivot table.
2. On the PivotTable Analyze tab, in the Data group, click Change Data Source.
Tip: change your data set to a table before you insert a pivot table.
This way your data source will be updated automatically when you add or delete rows/columns.
This can save time.
You still have to refresh though.
Calculated Field/Item
Calculated Field | Calculated Item
This example teaches you how to insert a calculated field or calculated item in a pivot table.
Below you can find a pivot table.
Go back to Pivot Tables to learn how to create this pivot table.
Calculated Field
A calculated field uses the values from another field.
To insert a calculated field, execute the following steps.
1. Click any cell inside the pivot table.
2. On the PivotTable Analyze tab, in the Calculations group, click Fields, Items & Sets.
3. Click Calculated Field.
The Insert Calculated Field dialog box appears.
4. Enter Tax for Name.
5. Type the formula =IF(Amount>100000, 3%*Amount, 0)
6. Click Add.
Note: use the Insert Field button to quickly insert fields when you type a formula.
To delete a calculated field, select the field and click Delete (under Add).
7. Click OK.
Excel automatically adds the Tax field to the Values area.
Result:
Calculated Item
A calculated item uses the values from other items.
To insert a calculated item, execute the following steps.
1. Click any Country in the pivot table.
2. On the PivotTable Analyze tab, in the Calculations group, click Fields, Items & Sets.
3. Click Calculated Item.
The Insert Calculated Item dialog box appears.
4. Enter Oceania for Name.
5. Type the formula =3%*(Australia+'New Zealand')
6. Click Add.
Note: use the Insert Item button to quickly insert items when you type a formula.
To delete a calculated item, select the item and click Delete (under Add).
7. Repeat steps 4 to 6 for North America (Canada and United States) and Europe (France, Germany and United Kingdom) with a 4% and 5% tax rate respectively.
8. Click OK.
Result:
Note: we created two groups (Sales and Taxes).
GETPIVOTDATA
To quickly enter a GETPIVOTDATA function in Excel, type an equal sign (=) and click a cell in a pivot table.
The GETPIVOTDATA function can be quite useful.
1. First, select cell B14 below and type =D7 (without clicking cell D7 in the pivot table) to reference the amount of beans exported to France.
2. Use the filter to only show the amounts of vegetables exported to each country.
Note: cell B14 now references the amount of carrots exported to France, not the amount of beans.
GETPIVOTDATA to the rescue!
3. Remove the filter.
Select cell B14 again, type an equal sign (=) and click cell D7 in the pivot table.
Note: Excel automatically inserts the GETPIVOTDATA function shown above.
4. Again, use the filter to only show the amounts of vegetables exported to each country.
Note: the GETPIVOTDATA function correctly returns the amount of beans exported to France.
5. The GETPIVOTDATA function can only return data that is visible.
For example, use the filter to only show the amounts of fruit exported to each country.
Note: the GETPIVOTDATA function returns a #REF! error because the value 680 (beans to France) is not visible.
6. The dynamic GETPIVOTDATA function below returns the amount of mango exported to Canada.
Note: this GETPIVOTDATA function has 6 arguments (data field, a reference to any cell inside the pivot table and 2 field/item pairs).
Create a drop-down list in cell B14 and cell B15 to quickly select the first and second item (see downloadable Excel file).
7. The GETPIVOTDATA function below has 4 arguments (data field, a reference to any cell inside the pivot table and 1 field/item pair) and returns the total amount exported to the USA.
8. If the total amount exported to the USA changes (for example, by using a filter), the value returned by the GETPIVOTDATA function also changes.
If you don't want Excel to automatically insert a GETPIVOTDATA function, you can turn off this feature.
9. Click any cell inside the pivot table.
10. On the PivotTable Analyze tab, in the PivotTable group, click the drop-down arrow next to Options and uncheck Generate GetPivotData.
Structured References
When working with tables in Excel, you can use structured references to make your formulas easier to understand.
For example, we have the following table.
1. Select cell E1, type Bonus, and press Enter.
Excel automatically formats the column for you.
2. Select cell E2 and type =0.02*[
3. A list of structured references (the columns) appears.
Select Sales from the list.
4. Close with a square bracket and press Enter.
Result.
Excel automatically copies the formula down the column for you.
Note: click AutoCorrect Options and click Undo Calculated Column to only insert the formula into cell E2.
To refer to this table in a formula, execute the following steps.
5. First, select a cell inside the table.
Next, on the Table Design tab, in the Properties group, we can see that Table1 is the name of this table.
6. Select cell E18 and enter the formula shown below.
Explanation: this formula calculates the sum of the Sales column.
Enter =SUM(Table1[ and Excel will give you a list of structured references you can use.
This formula updates automatically when you add or delete records.
Learn more about Excel Tables |
1. Tables |
Master Excel tables and analyze your data quickly and easily.
Learn how to create a table, sort a table, filter a table, and much more. |
|
2. Structured References |
When working with tables in Excel, you can use structured references to make your formulas easier to understand. |
|
3. Table Styles |
Quickly format a range of cells by choosing a table style.
You can also create your own table style.
Quickly format a cell by choosing a cell style. |
|
4. Merge Tables |
You can use tables and the VLOOKUP function in Excel to quickly merge two tables.
This trick will bring your Excel game to a new level. |
|
5. Table as Source Data |
One of the great things about tables in Excel is that you can use a table as source data for a chart, pivot table, etc. |
|
6. Quick Analysis |
Use the Quick Analysis tool in Excel to quickly analyze your data.
Quickly calculate totals, quickly insert tables, quickly apply conditional formatting and more. |
|
Table Styles
Quickly format a range of cells by choosing a table style.
You can also create your own table style.
Quickly format a cell by choosing a cell style.
1. Click any single cell inside the data set.
2. On the Home tab, in the Styles group, click Format as Table.
3. Choose a table style.
Note: click New Table Style to create your own table style or right click a table style and click Duplicate to create a new table style that is similar to an existing one.
Modifying a custom table style affects all tables in a workbook that use that table style.
This can save a lot of time.
4. Excel automatically selects the data for you.
Check 'My table has headers' and click on OK.
Result.
This is another way to create a table.
You can change a table style at anytime.
5. First, select a cell inside the table.
Next, on the Table Design tab, in the Table Styles group, click a table style (hover over a style to see a live preview).
Result.
A different visual style.
To convert this table back to a normal range of cells (with table formatting), execute the following steps.
6. First, select a cell inside the table.
Next, on the Table Design tab, in the Tools group, click Convert to Range.
Result.
A nicely formatted range of cells.
To convert this table back to a normal range of cells (without table formatting), execute the following steps.
7. Press Ctrl + Z to undo the previous step.
8. First, select a cell inside the table.
Next, on the Table Design tab, in the Table Styles group, click the first style (None).
Result.
This only removes the table formatting.
You can still sort, filter, add a total row, etc.
9. Finally, on the Table Design tab, in the Tools group, click Convert to Range.
Result.
A normal range of cells.
Learn more about Excel Tables |
1. Tables |
Master Excel tables and analyze your data quickly and easily.
Learn how to create a table, sort a table, filter a table, and much more. |
|
2. Structured References |
When working with tables in Excel, you can use structured references to make your formulas easier to understand. |
|
3. Table Styles |
Quickly format a range of cells by choosing a table style.
You can also create your own table style.
Quickly format a cell by choosing a cell style. |
|
4. Merge Tables |
You can use tables and the VLOOKUP function in Excel to quickly merge two tables.
This trick will bring your Excel game to a new level. |
|
5. Table as Source Data |
One of the great things about tables in Excel is that you can use a table as source data for a chart, pivot table, etc. |
|
6. Quick Analysis |
Use the Quick Analysis tool in Excel to quickly analyze your data.
Quickly calculate totals, quickly insert tables, quickly apply conditional formatting and more. |
|
Merge Tables
You can use tables and the VLOOKUP function in Excel to quickly merge two tables.
This trick will bring your Excel game to a new level.
Our goal is to create one table that consists of a list of cities, countries, and country codes.
First, insert two tables.
1. Select a cell in the first range.
2. On the Insert tab, in the Tables group, click Table.
3. Excel automatically selects the data for you.
Click OK.
4. Repeat these steps for the second range.
Result so far:
Now comes the most important part.
5. Select cell C2 and enter =VLOOKUP(
6. Enter the first argument by selecting cell B2. Excel replaces this cell reference with [@Country] because we're working with tables here.
This is called a structured reference.
7. Enter the second argument by selecting the range E2:F6. Excel replaces this range reference with Table2.
8. Use 2 for the third argument because the codes are in the second column of the red table.
9. Use FALSE for the fourth argument to find an exact match.
10. Press Enter.
Note: Excel automatically copied the VLOOKUP function to the other cells.
That saves time.
11. Enter a new city and country.
Excel automatically looks up the corresponding country code for you.
Wow!
Conclusion: tables can make VLOOKUP formulas a lot easier.
Try it yourself.
Download the Excel file and enter a new city and country.
Learn more about Excel Tables |
1. Tables |
Master Excel tables and analyze your data quickly and easily.
Learn how to create a table, sort a table, filter a table, and much more. |
|
2. Structured References |
When working with tables in Excel, you can use structured references to make your formulas easier to understand. |
|
3. Table Styles |
Quickly format a range of cells by choosing a table style.
You can also create your own table style.
Quickly format a cell by choosing a cell style. |
|
4. Merge Tables |
You can use tables and the VLOOKUP function in Excel to quickly merge two tables.
This trick will bring your Excel game to a new level. |
|
5. Table as Source Data |
One of the great things about tables in Excel is that you can use a table as source data for a chart, pivot table, etc. |
|
6. Quick Analysis |
Use the Quick Analysis tool in Excel to quickly analyze your data.
Quickly calculate totals, quickly insert tables, quickly apply conditional formatting and more. |
|
Table as Source Data
One of the great things about tables in Excel is that your can use a table as source data for a chart, pivot table, etc.
To see why this is useful, let's create a simple chart.
1. Select a cell in the source data.
2. Press Ctrl + T to quickly insert a table.
3. Press Enter.
Result so far:
4. On the Insert tab, in the Charts group, click the Column symbol.
5. Click Clustered Column.
Result:
Now comes the most important part.
New rows or columns added to the table will automatically be included in the chart.
6. Select cell A8 and type Jul (Excel automatically formats this new row for you).
7. Enter the data for this month.
Excel automatically updates this dynamic chart.
That's pretty awesome.
Note: as mentioned earlier, you can also use a table to create a dynamic pivot table, or even better, use a table and the new UNIQUE function in Excel 365/2021 to create a magic drop-down list.
Learn more about Excel Tables |
1. Tables |
Master Excel tables and analyze your data quickly and easily.
Learn how to create a table, sort a table, filter a table, and much more. |
|
2. Structured References |
When working with tables in Excel, you can use structured references to make your formulas easier to understand. |
|
3. Table Styles |
Quickly format a range of cells by choosing a table style.
You can also create your own table style.
Quickly format a cell by choosing a cell style. |
|
4. Merge Tables |
You can use tables and the VLOOKUP function in Excel to quickly merge two tables.
This trick will bring your Excel game to a new level. |
|
5. Table as Source Data |
One of the great things about tables in Excel is that you can use a table as source data for a chart, pivot table, etc. |
|
6. Quick Analysis |
Use the Quick Analysis tool in Excel to quickly analyze your data.
Quickly calculate totals, quickly insert tables, quickly apply conditional formatting and more. |
|
Quick Analysis
Totals | Tables | Formatting | Charts | Sparklines
Use the Quick Analysis tool in Excel to quickly analyze your data.
Quickly calculate totals, quickly insert tables, quickly apply conditional formatting and more.
Totals
Instead of displaying a total row at the end of an Excel table, use the Quick Analysis tool to quickly calculate totals.
1. Select a range of cells and click the Quick Analysis button.
2. For example, click Totals and click Sum to sum the numbers in each column.
Result:
3. Select the range A1:D7 and add a column with a running total.
Note: total rows are colored blue and total columns are colored yellow-orange.
Tables
Use tables in Excel to sort, filter and summarize data.
A pivot table in Excel allows you to extract the significance from a large, detailed data set.
1. Select a range of cells and click the Quick Analysis button.
2. To quickly insert a table, click Tables and click Table.
Note: visit our page about Tables to learn more about this topic.
3. Download the Excel file (right side of this page) and open the second sheet.
4. Click any single cell inside the data set.
5. Press CTRL + q.
This shortcut selects the entire data set and opens the Quick Analysis tool.
6. To quickly insert a pivot table, click Tables and click one of the pivot table examples.
Note: pivot tables are one of Excel's most powerful features.
Visit our page about Pivot Tables to learn more about this topic.
Formatting
Data bars, color scales and icon sets in Excel make it very easy to visualize values in a range of cells.
1. Select a range of cells and click the Quick Analysis button.
2. To quickly add data bars, click Data Bars.
Note: a longer bar represents a higher value.
Visit our page about Data Bars to learn more about this topic.
3. To quickly add a color scale, click Color Scale.
Note: the shade of the color represents the value in the cell.
Visit our page about Color Scales to learn more about this topic.
4. To quickly add an icon set, click Icon Set.
Note: each icon represents a range of values.
Visit our page about Icon Sets to learn more about this topic.
5. To quickly highlight cells that are greater than a value, click Greater Than.
6. Enter the value 100 and select a formatting style.
7. Click OK.
Result.
Excel highlights the cells that are greater than 100.
Note: visit our page about Conditional Formatting to learn much more about this topic.
Charts
You can use the Quick Analysis tool to quickly create a chart.
The Recommended Charts feature analyzes your data and suggests useful charts.
1. Select a range of cells and click the Quick Analysis button.
2. For example, click Charts and click Clustered Column to create a clustered column chart.
Note: click More to view more recommended charts.
Visit our chapter about Charts to learn more about this topic.
Sparklines
Sparklines in Excel are graphs that fit in one cell.
Sparklines are great for displaying trends.
1. Download the Excel file (right side of this page) and open the third sheet.
2. Select the range A1:F4 and click the Quick Analysis button.
3. For example, click Sparklines and click Line to insert sparklines.
Customized result:
Note: visit our page about Sparklines to learn how to customize sparklines.
Learn more about Excel Tables |
1. Tables |
Master Excel tables and analyze your data quickly and easily.
Learn how to create a table, sort a table, filter a table, and much more. |
|
2. Structured References |
When working with tables in Excel, you can use structured references to make your formulas easier to understand. |
|
3. Table Styles |
Quickly format a range of cells by choosing a table style.
You can also create your own table style.
Quickly format a cell by choosing a cell style. |
|
4. Merge Tables |
You can use tables and the VLOOKUP function in Excel to quickly merge two tables.
This trick will bring your Excel game to a new level. |
|
5. Table as Source Data |
One of the great things about tables in Excel is that you can use a table as source data for a chart, pivot table, etc. |
|
6. Quick Analysis |
Use the Quick Analysis tool in Excel to quickly analyze your data.
Quickly calculate totals, quickly insert tables, quickly apply conditional formatting and more. |
|
Data Tables
One Variable Data Table | Two Variable Data Table
Instead of creating different scenarios, you can create a data table to quickly try out different values for formulas.
You can create a one variable data table or a two variable data table.
Assume you own a book store and have 100 books in storage.
You sell a certain % for the highest price of $50 and a certain % for the lower price of $20. If you sell 60% for the highest price, cell D10 below calculates a total profit of 60 * $50 + 40 * $20 = $3800.
One Variable Data Table
To create a one variable data table, execute the following steps.
1. Select cell B12 and type =D10 (refer to the total profit cell).
2. Type the different percentages in column A.
3. Select the range A12:B17.
We are going to calculate the total profit if you sell 60% for the highest price, 70% for the highest price, etc.
4. On the Data tab, in the Forecast group, click What-If Analysis.
5. Click Data Table.
6. Click in the 'Column input cell' box (the percentages are in a column) and select cell C4.
We select cell C4 because the percentages refer to cell C4 (% sold for the highest price).
Together with the formula in cell B12, Excel now knows that it should replace cell C4 with 60% to calculate the total profit, replace cell C4 with 70% to calculate the total profit, etc.
Note: this is a one variable data table so we leave the Row input cell blank.
7. Click OK.
Result.
Conclusion: if you sell 60% for the highest price, you obtain a total profit of $3800, if you sell 70% for the highest price, you obtain a total profit of $4100, etc.
Note: the formula bar indicates that the cells contain an array formula.
Therefore, you cannot delete a single result.
To delete the results, select the range B13:B17 and press Delete.
Two Variable Data Table
To create a two variable data table, execute the following steps.
1. Select cell A12 and type =D10 (refer to the total profit cell).
2. Type the different unit profits (highest price) in row 12.
3. Type the different percentages in column A.
4. Select the range A12:D17.
We are going to calculate the total profit for the different combinations of 'unit profit (highest price)' and '% sold for the highest price'.
5. On the Data tab, in the Forecast group, click What-If Analysis.
6. Click Data Table.
7. Click in the 'Row input cell' box (the unit profits are in a row) and select cell D7.
8. Click in the 'Column input cell' box (the percentages are in a column) and select cell C4.
We select cell D7 because the unit profits refer to cell D7. We select cell C4 because the percentages refer to cell C4. Together with the formula in cell A12, Excel now knows that it should replace cell D7 with $50 and cell C4 with 60% to calculate the total profit, replace cell D7 with $50 and cell C4 with 70% to calculate the total profit, etc.
9. Click OK.
Result.
Conclusion: if you sell 60% for the highest price, at a unit profit of $50, you obtain a total profit of $3800, if you sell 80% for the highest price, at a unit profit of $60, you obtain a total profit of $5200, etc.
Note: the formula bar indicates that the cells contain an array formula.
Therefore, you cannot delete a single result.
To delete the results, select the range B13:D17 and press Delete.
Goal Seek
Goal Seek Example 1 | Goal Seek Example 2 | Goal Seek Precision | More about Goal Seek
If you know the result you want from a formula, use Goal Seek in Excel to find the input value that produces this formula result.
Goal Seek Example 1
Use Goal Seek in Excel to find the grade on the fourth exam that produces a final grade of 70.
1. The formula in cell B7 calculates the final grade.
2. The grade on the fourth exam in cell B5 is the input cell.
3. On the Data tab, in the Forecast group, click What-If Analysis.
4. Click Goal Seek.
The Goal Seek dialog box appears.
5. Select cell B7.
6. Click in the 'To value' box and type 70.
7. Click in the 'By changing cell' box and select cell B5.
8. Click OK.
Result.
A grade of 90 on the fourth exam produces a final grade of 70.
Goal Seek Example 2
Use Goal Seek in Excel to find the loan amount that produces a monthly payment of $1500.
1. The formula in cell B5 calculates the monthly payment.
Explanation: the PMT function calculates the payment for a loan.
If you've never heard of this function before, that's OK.
The higher the loan amount, the higher the monthly payment.
Assume, you can only afford $1500 a month.
What is your maximum loan amount?
2. The loan amount in cell B3 is the input cell.
3. On the Data tab, in the Forecast group, click What-If Analysis.
4. Click Goal Seek.
The Goal Seek dialog box appears.
5. Select cell B5.
6. Click in the 'To value' box and type -1500 (negative, you are paying out money).
7. Click in the 'By changing cell' box and select cell B3.
8. Click OK.
Result.
A loan amount of $250,187 produces a monthly payment of $1500.
Goal Seek Precision
Goal seek returns approximate solutions.
You can change the iteration settings in Excel to find a more precise solution.
1. The formula in cell B1 calculates the square of the value in cell A1.
2. Use goal seek to find the input value that produces a formula result of 25.
Result.
Excel returns an approximate solution.
3. On the File tab, click Options, Formulas.
4. Under Calculation options, decrease the Maximum Change value by inserting some zeros.
The default value is 0.001.
5. Click OK.
6. Use Goal Seek again.
Excel returns a more precise solution.
More about Goal Seek
There are many problems Goal Seek can't solve.
Goal Seek requires a single input cell and a single output (formula) cell.
Use the Solver in Excel to solve problems with multiple input cells.
Sometimes you need to start with a different input value to find a solution.
1. The formula in cell B1 below produces a result of -0.25.
2. Use Goal Seek to find the input value that produces a formula result of +0.25.
Result.
Excel can't find a solution.
3. Click Cancel.
4. Start with an input value greater than 8.
5. Use Goal Seek again.
Excel finds a solution.
Explanation: y = 1 / (x - 8) is discontinuous at x = 8 (dividing by 0 is not possible).
In this example, Goal seek cannot reach one side of the x-axis (x>8) if it starts on the other side of the x-axis (x<8) or vice versa.
Quadratic Equation
A quadratic equation is of the form ax2 + bx + c = 0 where a ≠ 0. A quadratic equation can be solved by using the quadratic formula.
You can also use Excel's Goal Seek feature to solve a quadratic equation.
1. For example, we have the formula y = 3x2 - 12x + 9.5. It's easy to calculate y for any given x.
For x = 1, y = 0.5
2. For x = 2, y = -2.5
3. But what if we want to know x for any given y? For example, y = 24.5. We need to solve 3x2 - 12x + 9.5 = 24.5. We can solve the quadratic equation 3x2 - 12x + 9.5 - 24.5 = 0 by using the quadratic formula.
3x2 - 12x -15 = 0
a = 3, b = -12, c = -15
D = b2- 4ac = (-12)2 - 4 * 3 * -15 = 144 + 180 = 324
x = |
-b + √D |
or |
x = |
-b - √D |
2a |
2a |
x = |
12 + √324 |
or |
x = |
12 - √324 |
6 |
6 |
x = |
12 + 18 |
or |
x = |
12 - 18 |
6 |
6 |
4. You can use Excel's Goal Seek feature to obtain the exact same result.
On the Data tab, in the Forecast group, click What-If Analysis.
5. Click Goal Seek.
The Goal Seek dialog box appears.
6. Select cell B2.
7. Click in the 'To value' box and type 24.5
8. Click in the 'By changing cell' box and select cell A2.
9. Click OK.
Result.
Note: Excel returns the solution x = 5. Excel finds the other solution if you start with an x-value closer to x = -1. For example, enter the value 0 into cell A2 and repeat steps 5 to 9. To find the roots, set y = 0 and solve the quadratic equation 3x2 - 12x + 9.5 = 0. In this case, set 'To value' to 0.
Transportation Problem
Formulate the Model | Trial and Error | Solve the Model
Use the solver in Excel to find the number of units to ship from each factory to each customer that minimizes the total cost.
Formulate the Model
The model we are going to solve looks as follows in Excel.
1. To formulate this transportation problem, answer the following three questions.
a. What are the decisions to be made? For this problem, we need Excel to find out how many units to ship from each factory to each customer.
b. What are the constraints on these decisions? Each factory has a fixed supply and each customer has a fixed demand.
c. What is the overall measure of performance for these decisions? The overall measure of performance is the total cost of the shipments, so the objective is to minimize this quantity.
2. To make the model easier to understand, create the following named ranges.
Range Name |
Cells |
UnitCost |
C4:E6 |
Shipments |
C10:E12 |
TotalIn |
C14:E14 |
Demand |
C16:E16 |
TotalOut |
G10:G12 |
Supply |
I10:I12 |
TotalCost |
I16 |
3. Insert the following functions.
Explanation: The SUM functions calculate the total shipped from each factory (Total Out) to each customer (Total In).
Total Cost equals the sumproduct of UnitCost and Shipments.
Trial and Error
With this formulation, it becomes easy to analyze any trial solution.
For example, if we ship 100 units from Factory 1 to Customer 1, 200 units from Factory 2 to Customer 2, 100 units from Factory 3 to Customer 1 and 200 units from Factory 3 to Customer 3, Total Out equals Supply and Total In equals Demand.This solution has a total cost of 27800.
It is not necessary to use trial and error.
We shall describe next how the Excel Solver can be used to quickly find the optimal solution.
Solve the Model
To find the optimal solution, execute the following steps.
1. On the Data tab, in the Analyze group, click Solver.
Note: can't find the Solver button? Click here to load the Solver add-in.
Enter the solver parameters (read on).
The result should be consistent with the picture below.
You have the choice of typing the range names or clicking on the cells in the spreadsheet.
2. Enter TotalCost for the Objective.
3. Click Min.
4. Enter Shipments for the Changing Variable Cells.
5. Click Add to enter the following constraint.
6. Click Add to enter the following constraint.
7. Check 'Make Unconstrained Variables Non-Negative' and select 'Simplex LP'.
8. Finally, click Solve.
Result:
The optimal solution:
Conclusion: it is optimal to ship 100 units from Factory 1 to Customer 2, 100 units from Factory 2 to Customer 2, 100 units from Factory 2 to Customer 3, 200 units from Factory 3 to Customer 1 and 100 units from Factory 3 to Customer 3. This solution gives the minimum cost of 26000. All constraints are satisfied.
Assignment Problem
Formulate the Model | Trial and Error | Solve the Model
Use the solver in Excel to find the assignment of persons to tasks that minimizes the total cost.
Formulate the Model
The model we are going to solve looks as follows in Excel.
1. To formulate this assignment problem, answer the following three questions.
a. What are the decisions to be made? For this problem, we need Excel to find out which person to assign to which task (Yes=1, No=0).
For example, if we assign Person 1 to Task 1, cell C10 equals 1. If not, cell C10 equals 0. b. What are the constraints on these decisions? Each person can only do one task (Supply=1).
Each task only needs one person (Demand=1).
c. What is the overall measure of performance for these decisions? The overall measure of performance is the total cost of the assignment, so the objective is to minimize this quantity.
2. To make the model easier to understand, create the following named ranges.
Range Name |
Cells |
Cost |
C4:E6 |
Assignment |
C10:E12 |
PersonsAssigned |
C14:E14 |
Demand |
C16:E16 |
TasksAssigned |
G10:G12 |
Supply |
I10:I12 |
TotalCost |
I16 |
3. Insert the following functions.
Explanation: The SUM functions calculate the number of tasks assigned to a person and the number of persons assigned to a task.
Total Cost equals the sumproduct of Cost and Assignment.
Trial and Error
With this formulation, it becomes easy to analyze any trial solution.
For example, if we assign Person 1 to Task 1, Person 2 to task 2 and Person 3 to Task 3, Tasks Assigned equals Supply and Persons Assigned equals Demand.This solution has a total cost of 147.
It is not necessary to use trial and error.
We shall describe next how the Excel Solver can be used to quickly find the optimal solution.
Solve the Model
To find the optimal solution, execute the following steps.
1. On the Data tab, in the Analyze group, click Solver.
Note: can't find the Solver button? Click here to load the Solver add-in.
Enter the solver parameters (read on).
The result should be consistent with the picture below.
You have the choice of typing the range names or clicking on the cells in the spreadsheet.
2. Enter TotalCost for the Objective.
3. Click Min.
4. Enter Assignment for the Changing Variable Cells.
5. Click Add to enter the following constraint.
Note: binary variables are either 0 or 1.
6. Click Add to enter the following constraint.
7. Click Add to enter the following constraint.
8. Check 'Make Unconstrained Variables Non-Negative' and select 'Simplex LP'.
9. Finally, click Solve.
Result:
The optimal solution:
Conclusion: it is optimal to assign Person 1 to task 2, Person 2 to Task 3 and Person 3 to Task 1. This solution gives the minimum cost of 129. All constraints are satisfied.
Capital Investment
Formulate the Model | Trial and Error | Solve the Model
Use the solver in Excel to find the combination of capital investments that maximizes the total profit.
Formulate the Model
The model we are going to solve looks as follows in Excel.
1. To formulate this binary integer programming (BIP) model, answer the following three questions.
a. What are the decisions to be made? For this problem, we need Excel to find out which capital investments to make (Yes=1, No=0).
b. What are the constraints on these decisions? First, the amount of capital used by the investments cannot exceed the limited amount of capital available (50).
For example, investment One uses 12 units of capital.Second, only investment One or investment Two can be made.
Third, only investment Three or investment Four can be made.
Fourth, investment Six and investment Seven can only be made if investment Five is made.
c. What is the overall measure of performance for these decisions? The overall measure of performance is the total profit of the capital investments made, so the objective is to maximize this quantity.
2. To make the model easier to understand, create the following named ranges.
Range Name
|
Cells
|
Profit |
C5:I5 |
YesNo |
C13:I13 |
TotalProfit |
M13 |
3. Insert the following five SUMPRODUCT functions.
Explanation: cell K7 (the amount of capital used) equals the sumproduct of the range C7:I7 and YesNo, cell K8 equals the sumproduct of the range C8:I8 and YesNo, etc.
Total Profit equals the sumproduct of Profit and YesNo.
Trial and Error
With this formulation, it becomes easy to analyze any trial solution.
1. For example, if we make investment One and Two, the second constraint is violated.
2. For example, if we make investment Six and Seven, without making investment Five, the fourth constraint is violated.
3. However, it's OK to make investment One, Five and Six.
All constraints are satisfied.
It is not necessary to use trial and error.
We shall describe next how the Excel Solver can be used to quickly find the optimal solution.
Solve the Model
To find the optimal solution, execute the following steps.
1. On the Data tab, in the Analyze group, click Solver.
Note: can't find the Solver button? Click here to load the Solver add-in.
Enter the solver parameters (read on).
The result should be consistent with the picture below.
2. Enter TotalProfit for the Objective.
3. Click Max.
4. Enter YesNo for the Changing Variable Cells.
5. Click Add to enter the following constraint.
6. Click Add to enter the following constraint.
Note: binary variables are either 0 or 1.
7. Check 'Make Unconstrained Variables Non-Negative' and select 'Simplex LP'.
8. Finally, click Solve.
Result:
The optimal solution:
Conclusion: it is optimal to make investments Two, Four, Five and Seven.
This solution gives the maximum profit of 146. All constraints are satisfied.
Shortest Path Problem
Formulate the Model | Trial and Error | Solve the Model
Use the solver in Excel to find the shortest path from node S to node T in an undirected network.
Points in a network are called nodes (S, A, B, C, D, E and T).
Lines in a network are called arcs (SA, SB, SC, AC, etc).
Formulate the Model
The model we are going to solve looks as follows in Excel.
1. To formulate this shortest path problem, answer the following three questions.
a. What are the decisions to be made? For this problem, we need Excel to find out if an arc is on the shortest path or not (Yes=1, No=0).
For example, if SB is part of the shortest path, cell F5 equals 1. If not, cell F5 equals 0. b. What are the constraints on these decisions? The Net Flow (Flow Out - Flow In) of each node should be equal to Supply/Demand.
Node S should only have one outgoing arc (Net Flow = 1).
Node T should only have one ingoing arc (Net Flow = -1).
All other nodes should have one outgoing arc and one ingoing arc if the node is on the shortest path (Net Flow = 0) or no flow (Net Flow = 0).
c. What is the overall measure of performance for these decisions? The overall measure of performance is the total distance of the shortest path, so the objective is to minimize this quantity.
2. To make the model easier to understand, create the following named ranges.
Range Name |
Cells |
From |
B4:B21 |
To |
C4:C21 |
Distance |
D4:D21 |
Go |
F4:F21 |
NetFlow |
I4:I10 |
SupplyDemand |
K4:K10 |
TotalDistance |
F23 |
3. Insert the following functions.
Explanation: The SUMIF functions calculate the Net Flow of each node.
For node S, the SUMIF function sums the values in the Go column with an "S" in the From column.As a result, only cell F4, F5 or F6 can be 1 (one outgoing arc).
For node T, the SUMIF function sums the values in the Go column with a "T" in the To column.As a result, only cell F15, F18 or F21 can be 1 (one ingoing arc).
For all other nodes, Excel looks in the From and To column.Total Distance equals the sumproduct of Distance and Go.
Trial and Error
With this formulation, it becomes easy to analyze any trial solution.
1. For example, the path SBET has a total distance of 16.
It is not necessary to use trial and error.
We shall describe next how the Excel Solver can be used to quickly find the optimal solution.
Solve the Model
To find the optimal solution, execute the following steps.
1. On the Data tab, in the Analyze group, click Solver.
Note: can't find the Solver button? Click here to load the Solver add-in.
Enter the solver parameters (read on).
The result should be consistent with the picture below.
You have the choice of typing the range names or clicking on the cells in the spreadsheet.
2. Enter TotalDistance for the Objective.
3. Click Min.
4. Enter Go for the Changing Variable Cells.
5. Click Add to enter the following constraint.
6. Check 'Make Unconstrained Variables Non-Negative' and select 'Simplex LP'.
7. Finally, click Solve.
Result:
The optimal solution:
Conclusion: SADCT is the shortest path with a total distance of 11.
Maximum Flow Problem
Formulate the Model | Trial and Error | Solve the Model
Use the solver in Excel to find the maximum flow from node S to node T in a directed network.
Points in a network are called nodes (S, A, B, C, D, E and T).
Lines in a network are called arcs (SA, SB, SC, AC, etc).
Formulate the Model
The model we are going to solve looks as follows in Excel.
1. To formulate this maximum flow problem, answer the following three questions.
a. What are the decisions to be made? For this problem, we need Excel to find the flow on each arc.
For example, if the flow on SB is 2, cell D5 equals 2. b. What are the constraints on these decisions? The Net Flow (Flow Out - Flow In) of node A, B, C, D and E should be equal to 0. In other words, Flow Out = Flow In.
Also, each arc has a fixed capacity.
The flow on each arc should be less than this capacity.
c. What is the overall measure of performance for these decisions? The overall measure of performance is the maximum flow, so the objective is to maximize this quantity.
The maximum flow equals the Flow Out of node S.
2. To make the model easier to understand, create the following named ranges.
Range Name |
Cells |
From |
B4:B15 |
To |
C4:C15 |
Flow |
D4:D15 |
Capacity |
F4:F15 |
SupplyDemand |
K5:K9 |
MaximumFlow |
D17 |
3. Insert the following functions.
Explanation: The SUMIF functions calculate the Net Flow of each node.
For node A, the first SUMIF function sums the values in the Flow column with an "A" in the From column (Flow Out).The second SUMIF function sums the values in the Flow column with an "A" in the To column (Flow In).
Maximum Flow equals the value in cell I4, which is the flow out of node S.
Because node A, B, C, D and E have a Net Flow of 0, Flow Out of node S will equal Flow In of node T.
Trial and Error
With this formulation, it becomes easy to analyze any trial solution.
1. For example, the path SADT with a flow of 2. The path SCT with a flow of 4. The path SBET with a flow of 2. These paths givea total flow of 8.
It is not necessary to use trial and error.
We shall describe next how the Excel Solver can be used to quickly find the optimal solution.
Solve the Model
To find the optimal solution, execute the following steps.
1. On the Data tab, in the Analyze group, click Solver.
Note: can't find the Solver button? Click here to load the Solver add-in.
Enter the solver parameters (read on).
The result should be consistent with the picture below.
You have the choice of typing the range names or clicking on the cells in the spreadsheet.
2. Enter MaximumFlow for the Objective.
3. Click Max.
4. Enter Flow for the Changing Variable Cells.
5. Click Add to enter the following constraint.
6. Click Add to enter the following constraint.
7. Check 'Make Unconstrained Variables Non-Negative' and select 'Simplex LP'.
8. Finally, click Solve.
Result:
The optimal solution:
Conclusion: the path SADT with a flow of 2. The path SCT with a flow of 4. The path SBET with a flow of 2. The path SCET with a flow of 2. The path SACET with a flow of 1. The path SACDT with a flow of 1. These paths givea maximum flow of 12.
Sensitivity Analysis
Reduced Cost | Shadow Price
Sensitivity analysis gives you insight in how the optimal solution changes when you change the coefficients of the model.
After the solver found a solution, you can create a sensitivity report.
1. Before you click OK, select Sensitivity from the Reports section.
Below you can find the optimal solution and the sensitivity report.
It is optimal to order 94 bicycles and 54 mopeds.
This solution gives the maximum profit of 25600. This solution uses all the resources available (93000 units of capital and 101 units of storage).
You can find these numbers in the Final Value column.
Reduced Cost
The reduced costs tell us how much the objective coefficients (unit profits) can be increased or decreased before the optimal solution changes.
If we increase the unit profit of Child Seats with 20 or more units, the optimal solution changes.
1. At a unit profit of 69, it's still optimal to order 94 bicycles and 54 mopeds.
Below you can find the optimal solution.
2. At a unit profit of 71, the optimal solution changes.
Conclusion: it is only profitable to order child seats if you can sell them for at least 70 units.
Shadow Price
The shadow prices tell us how much the optimal solution can be increased or decreased if we change the right hand side values (resources available) with one unit.
1. With 101 units of storage available, the total profit is 25600. Below you can find the optimal solution.
2. With 102 units of storage available, the total profit is 25700 (+100).
Note: with a shadow price of 100 for this resource, this is according to our expectations.
This shadow price is only valid between 101 - 23,5 and 101 + 54 (see sensitivity report).
System of Linear Equations
This example shows you how to solve a system of linear equations in Excel.
For example, we have the following system of linear equations:
5x |
+ |
1y |
+ |
8z |
= |
46 |
4x |
- |
2y |
|
|
= |
12 |
6x |
+ |
7y |
+ |
4z |
= |
50 |
In matrix notation, this can be written as AX = B
|
|
5 |
1 |
8 |
|
|
|
|
x |
|
|
|
|
46 |
|
with A = |
|
4 |
-2 |
0 |
|
, |
X = |
|
y |
|
, |
B = |
|
12 |
|
|
|
6 |
7 |
4 |
|
|
|
|
z |
|
|
|
|
50 |
|
If A-1 (the inverse of A) exists, we can multiply both sides by A-1 to obtain X = A-1B.
To solve this system of linear equations in Excel, execute the following steps.
1. Use the MINVERSE function to return the inverse matrix of A.
First, select the range B6:D8. Next, insert the MINVERSE function shown below.
Finish by pressing CTRL + SHIFT + ENTER.
Note: the formula bar indicates that the cells contain an array formula.
Therefore, you cannot delete a single result.
To delete the results, select the range B6:D8 and press Delete.
2. Use the MMULT function to return the product of matrix A-1 and B.
First, select the range G6:G8. Next, insert the MMULT function shown below.
Finish by pressing CTRL + SHIFT + ENTER.
3. Put it all together.
First, select the range G6:G8. Next, insert the formula shown below.
Finish by pressing CTRL + SHIFT + ENTER.
4. If you have Excel 365 or Excel 2021, simply select cell G6, enter the same formula as above and press Enter.
Bye bye curly braces.
Note: this dynamic array formula, entered into cell G6, fills multiple cells.
Wow! This behavior in Excel 365/2021 is called spilling.
Histogram
This example teaches you how to make a histogram in Excel.
1. First, enter the bin numbers (upper levels) in the range C4:C8.
2. On the Data tab, in the Analysis group, click Data Analysis.
Note: can't find the Data Analysis button? Click here to load the Analysis ToolPak add-in.
3. Select Histogram and click OK.
4. Select the range A2:A19.
5. Click in the Bin Range box and select the range C4:C8.
6. Click the Output Range option button, click in the Output Range box and select cell F3.
7. Check Chart Output.
8. Click OK.
9. Click the legend on the right side and press Delete.
10. Properly label your bins.
11. To remove the space between the bars, right click a bar, click Format Data Series and change the Gap Width to 0%.
12. To add borders, right click a bar, click Format Data Series, click the Fill & Line icon, click Border and select a color.
Result:
If you have Excel 2016 or later, simply use the Histogram chart type.
13. Select the range A1:A19.
14. On the Insert tab, in the Charts group, click the Histogram symbol.
15. Click Histogram.
Result.
A histogram with 3 bins.
Note: Excel uses Scott's normal reference rule for calculating the number of bins and the bin width.
16. Right click the horizontal axis, and then click Format Axis.
The Format Axis pane appears.
17. Define the histogram bins.
We'll use the same bin numbers as before (see first picture on this page).
Bin width: 5. Number of bins: 6. Overflow bin: 40. Underflow bin: 20.
Result:
Recall, we made the following histogram using the Analysis ToolPak (steps 1-12).
Conclusion: the bin labels look different, but the histograms are the same.
≤20 is the same as 0-20, (20, 25] is the same as 21-25, etc.
Tip: you can also use pivot tables to easily create a frequency distribution in Excel.
Descriptive Statistics
You can use the Analysis Toolpak add-in to generate descriptive statistics.
For example, you may have the scores of 14 participants for a test.
To generate descriptive statistics for these scores, execute the following steps.
1. On the Data tab, in the Analysis group, click Data Analysis.
Note: can't find the Data Analysis button? Click here to load the Analysis ToolPak add-in.
2. Select Descriptive Statistics and click OK.
3. Select the range A2:A15 as the Input Range.
4. Select cell C1 as the Output Range.
5. Make sure Summary statistics is checked.
6. Click OK.
Result:
Tip: visit our page about statistical functions to learn more about this topic.
Anova
This example teaches you how to perform a single factor ANOVA (analysis of variance) in Excel.
A single factor or one-way ANOVA is used to test the null hypothesis that the means of several populations are all equal.
Below you can find the salaries of people who have a degree in economics, medicine or history.
H0: μ1 = μ2 = μ3
H1: at least one of the means is different.
To perform a single factor ANOVA, execute the following steps.
1. On the Data tab, in the Analysis group, click Data Analysis.
Note: can't find the Data Analysis button? Click here to load the Analysis ToolPak add-in.
2. Select Anova: Single Factor and click OK.
3. Click in the Input Range box and select the range A2:C10.
4. Click in the Output Range box and select cell E1.
5. Click OK.
Result:
Conclusion: if F > F crit, we reject the null hypothesis.
This is the case, 15.196 > 3.443. Therefore, we reject the null hypothesis.
The means of the three populations are not all equal.
At least one of the means is different.
However, the ANOVA does not tell you where the difference lies.
You need a t-Test to test each pair of means.
F-Test
This example teaches you how to perform an F-Test in Excel.
The F-Test is used to test the null hypothesis that the variances of two populations are equal.
Below you can find the study hours of 6 female students and 5 male students.
H0: σ12 = σ22
H1: σ12 ≠ σ22
To perform an F-Test, execute the following steps.
1. On the Data tab, in the Analysis group, click Data Analysis.
Note: can't find the Data Analysis button? Click here to load the Analysis ToolPak add-in.
2. Select F-Test Two-Sample for Variances and click OK.
3. Click in the Variable 1 Range box and select the range A2:A7.
4. Click in the Variable 2 Range box and select the range B2:B6.
5. Click in the Output Range box and select cell E1.
6. Click OK.
Result:
Important: be sure that the variance of Variable 1 is higher than the variance of Variable 2. This is the case, 160 > 21.7. If not, swap your data.
As a result, Excel calculates the correct F value, which is the ratio of Variance 1 to Variance 2 (F = 160 / 21.7 = 7.373).
Conclusion: if F > F Critical one-tail, we reject the null hypothesis.
This is the case, 7.373 > 6.256. Therefore, we reject the null hypothesis.
The variances of the two populations are unequal.
t-Test
This example teaches you how to perform a t-Test in Excel.
The t-Test is used to test the null hypothesis that the means of two populations are equal.
Below you can find the study hours of 6 female students and 5 male students.
H0: μ1 - μ2 = 0
H1: μ1 - μ2 ≠ 0
To perform a t-Test, execute the following steps.
1. First, perform an F-Test to determine if the variances of the two populations are equal.
This is not the case.
2. On the Data tab, in the Analysis group, click Data Analysis.
Note: can't find the Data Analysis button? Click here to load the Analysis ToolPak add-in.
3. Select t-Test: Two-Sample Assuming Unequal Variances and click OK.
4. Click in the Variable 1 Range box and select the range A2:A7.
5. Click in the Variable 2 Range box and select the range B2:B6.
6. Click in the Hypothesized Mean Difference box and type 0 (H0: μ1 - μ2 = 0).
7. Click in the Output Range box and select cell E1.
8. Click OK.
Result:
Conclusion: We do a two-tail test (inequality).
lf t Stat < -t Critical two-tail or t Stat > t Critical two-tail, we reject the null hypothesis.
This is not the case, -2.365 < 1.473 < 2.365. Therefore, we do not reject the null hypothesis.
The observed difference between the sample means (33 - 24.8) is not convincing enough to say that the average number of study hours between female and male students differ significantly.
Moving Average
This example teaches you how to calculate the moving average of a time series in Excel.
A moving average is used to smooth out irregularities (peaks and valleys) to easily recognize trends.
1. First, let's take a look at our time series.
2. On the Data tab, in the Analysis group, click Data Analysis.
Note: can't find the Data Analysis button? Click here to load the Analysis ToolPak add-in.
3. Select Moving Average and click OK.
4. Click in the Input Range box and select the range B2:M2.
5. Click in the Interval box and type 6.
6. Click in the Output Range box and select cell B3.
7. Click OK.
8. Plot a graph of these values.
Explanation: because we set the interval to 6, the moving average is the average of the previous 5 data points and the current data point.
As a result, peaks and valleys are smoothed out.
The graph shows an increasing trend.
Excel cannot calculate the moving average for the first 5 data points because there are not enough previous data points.
9. Repeat steps 2 to 8 for interval = 2 and interval = 4.
Conclusion: The larger the interval, the more the peaks and valleys are smoothed out.
The smaller the interval, the closer the moving averages are to the actual data points.
Exponential Smoothing
This example teaches you how to apply exponential smoothing to a time series in Excel.
Exponential smoothing is used to smooth out irregularities (peaks and valleys) to easily recognize trends.
1. First, let's take a look at our time series.
2. On the Data tab, in the Analysis group, click Data Analysis.
Note: can't find the Data Analysis button? Click here to load the Analysis ToolPak add-in.
3. Select Exponential Smoothing and click OK.
4. Click in the Input Range box and select the range B2:M2.
5. Click in the Damping factor box and type 0.9. Literature often talks about the smoothing constant α (alpha).
The value (1- α) is called the damping factor.
6. Click in the Output Range box and select cell B3.
7. Click OK.
8. Plot a graph of these values.
Explanation: because we set alpha to 0.1, the previous data point is given a relatively small weight while the previous smoothed value is given a large weight (i.e.
0.9).
As a result, peaks and valleys are smoothed out.
The graph shows an increasing trend.
Excel cannot calculate the smoothed value for the first data point because there is no previous data point.
The smoothed value for the second data point equals the previous data point.
9. Repeat steps 2 to 8 for alpha = 0.3 and alpha = 0.8.
Conclusion: The smaller alpha (larger the damping factor), the more the peaks and valleys are smoothed out.
The larger alpha (smaller the damping factor), the closer the smoothed values are to the actual data points.
Correlation
The correlation coefficient (a value between -1 and +1) tells you how strongly two variables are related to each other.
We can use the CORREL function or the Analysis Toolpak add-in in Excel to find the correlation coefficient between two variables.
- A correlation coefficient of +1 indicates a perfect positive correlation.
As variable X increases, variable Y increases.
As variable X decreases, variable Y decreases.
- A correlation coefficient of -1 indicates a perfect negative correlation.
As variable X increases, variable Z decreases.
As variable X decreases, variable Z increases.
- A correlation coefficient near 0 indicates no correlation.
To use the Analysis Toolpak add-in in Excel to quickly generate correlation coefficients between multiple variables, execute the following steps.
1. On the Data tab, in the Analysis group, click Data Analysis.
Note: can't find the Data Analysis button? Click here to load the Analysis ToolPak add-in.
2. Select Correlation and click OK.
3. For example, select the range A1:C6 as the Input Range.
4. Check Labels in first row.
5. Select cell A8 as the Output Range.
6. Click OK.
Result.
Conclusion: variables A and C are positively correlated (0.91).
Variables A and B are not correlated (0.19).
Variables B and C are also not correlated (0.11)
.
You can verify these conclusions by looking at the graph.
Regression
R Square | Significance F and P-Values | Coefficients | Residuals
This example teaches you how to run a linear regression analysis in Excel and how to interpret the Summary Output.
Below you can find our data.
The big question is: is there a relation between Quantity Sold (Output) and Price and Advertising (Input).
In other words: can we predict Quantity Sold if we know Price and Advertising?
1. On the Data tab, in the Analysis group, click Data Analysis.
Note: can't find the Data Analysis button? Click here to load the Analysis ToolPak add-in.
2. Select Regression and click OK.
3. Select the Y Range (A1:A8).
This is the predictor variable (also called dependent variable).
4. Select the X Range(B1:C8).
These are the explanatory variables (also called independent variables).
These columns must be adjacent to each other.
5. Check Labels.
6. Click in the Output Range box and select cell A11.
7. Check Residuals.
8. Click OK.
Excel produces the following Summary Output (rounded to 3 decimal places).
R Square
R Square equals 0.962, which is a very good fit.
96% of the variation in Quantity Sold is explained by the independent variables Price and Advertising.
The closer to 1, the better the regression line (read on) fits the data.
Significance F and P-values
To check if your results are reliable (statistically significant), look at Significance F (0.001).
If this value is less than 0.05, you're OK.
If Significance F is greater than 0.05, it's probably better to stop using this set of independent variables.
Delete a variable with a high P-value (greater than 0.05) and rerun the regression until Significance F drops below 0.05.
Most or all P-values should be below below 0.05. In our example this is the case.
(0.000, 0.001 and 0.005).
Coefficients
The regression line is: y = Quantity Sold = 8536.214 -835.722 * Price + 0.592 * Advertising.
In other words, for each unit increase in price, Quantity Sold decreases with 835.722 units.
For each unit increase in Advertising, Quantity Sold increases with 0.592 units.This is valuable information.
You can also use these coefficients to do a forecast.
For example, if price equals $4 and Advertising equals $3000, you might be able to achieve a Quantity Sold of 8536.214 -835.722 * 4 + 0.592 * 3000 = 6970. Residuals
The residuals show you how far away the actual data points are fom the predicted data points (using the equation).
For example, the first data point equals 8500. Using the equation, the predicted data point equals 8536.214 -835.722 * 2 + 0.592 * 2800 = 8523.009, giving a residual of 8500 - 8523.009 = -23.009.
You can also create a scatter plot of these residuals.
Swap Values
This example teaches you how to swap two values in Excel VBA.
You will often need this structure in more complicated programs as we will see later.
Situation:
Two values on your worksheet.
Place a command button on your worksheet and add the following code lines:
1. First, we declare a variable called temp of type Double.
Dim temp As Double
2. We initialize the variable temp with the value of cell A1.
temp = Range("A1").Value
3. Now we can safely write the value of cell B1 to cell A1 (we have stored the value of cell A1 to temp so we will not lose it).
Range("A1").Value = Range("B1").Value
4. Finally, we write the value of cell A1 (written to temp) to cell B1.
Range("B1").Value = temp
5. Click the command button two times.
Result:
Run Code from a Module
As a beginner to Excel VBA, you might find it difficult to decide where to put your VBA code.
The Create a Macro chapter illustrates how to run code by clicking on a command button.
This example teaches you how to run code from a module.
1. Open the Visual Basic Editor.
2. Click Insert, Module.
3. Create a procedure (macro) called Cyan.
Sub Cyan()End Sub
Note: a procedure is either a sub or a function.
Learn more about functions and subs here, if you like.
4. The sub changes the background color of your worksheet to cyan.
To achieve this, add the following code line.
Cells.Interior.ColorIndex = 28
Note: instead of ColorIndex number 28 (cyan), you can use any ColorIndex number.
To run the procedure, execute the following steps.
5. Click Macros.
6. Select Cyan and click Run.
Result:
Note: code placed into a module is available to the whole workbook.
That means you can select Sheet2 or Sheet3 and change the background color of these sheets as well.
The Add a Macro to the Toolbar program illustrates how to make a macro available to all your workbooks (Excel files).
Remember, code placed on a sheet (assigned to a command button) is only available for that particular sheet.
Macro Recorder
Record a Macro | Run a Recorded Macro | See the Macro
The Macro Recorder, a very useful tool included in Excel VBA, records every task you perform with Excel.
All you have to do is record a specific task once.
Next, you can execute the task over and over with the click of a button.
The Macro Recorder is also a great help when you don't know how to program a specific task in Excel VBA.
Simply open the Visual Basic Editor after recording the task to see how it can be programmed.
Unfortunately, there are a lot of things you cannot do with the Macro Recorder.
For example, you cannot loop through a range of data with the Macro Recorder.Moreover, the Macro Recorder uses a lot more code than is required, which can slow your process down.
Record a Macro
1. On the Developer tab, click Record Macro.
2. Enter a name.
3. Select This Workbook from the drop-down list.
As a result, the macro will only be available in the current workbook.
Note: if you store your macro in Personal Macro Workbook, the macro will be available to all your workbooks (Excel files).
This is possible because Excel stores your macro in a hidden workbook that opens automatically when Excel starts.
If you store your macro in New Workbook, the macro will only be available in an automatically new opened workbook.
4. Click OK.
5. Right mouse click on the active cell (selected cell).
Be sure not to select any other cell! Next, click Format Cells.
6. Select Percentage.
7. Click OK.
8. Finally, click Stop Recording.
Congratulations.
You've just recorded a macro with the Macro Recorder!
Run a Recorded Macro
Now we'll test the macro to see if it can change the number format to Percentage.
1. Enter some numbers between 0 and 1.
2. Select the numbers.
3. On the Developer tab, click Macros.
4. Click Run.
Result:
See the Macro
To take a look at the macro, open the Visual Basic Editor.
Note: the macro has been placed into a module called Module1. Code placed into a module is available to the whole workbook.
That means you change the number format of cells on other sheets as well.
Remember, code placed on a sheet (assigned to a command button) is only available for that particular sheet.
You can ignore the Option Explicit statement for now.
Use Relative References
By default, Excel records macros in absolute mode.
However, sometimes it is useful to record macros in relative mode.
This program teaches you how to do this.
If you don't know how to record a macro, we highly recommend you to read this example first.
Recording in Absolute Mode
To record a macro in absolute mode, execute the following steps.
1. First, click Record Macro.
2. Next, select cell B3. Type Sales and press enter.
3. Type Production and press enter.
4. Type Logistics and press enter.
Result:
5. Click Stop Recording.
6. Empty Range("B3:B5").
7. Select any cell on the sheet and run the recorded macro.
Result:
A macro recorded in absolute mode always produces the same result.
Recording in Relative Mode
Wouldn't it be nice to place these words anywhere on the sheet automatically? Not just Range("B3:B5").
This would make the macro much more flexible.
Solution: record the macro in relative mode.
1. Select "Use Relative References".
2. First, select any single cell (for example, cell B8).
3. Next, click Record Macro.
4. Type Sales and press enter.
5. Type Production and press enter.
6. Type Logistics and press enter.
Result:
7. Click Stop Recording.
8. Select any other cell (for example, cell D4) and run the recorded macro.
Result:
Excel places the words relative to the initial selected cell.
That's why it's called recording in relative mode.
FormulaR1C1
This example illustrates the difference between A1, R1C1 and R[1]C[1] style in Excel VBA.
1. Place a command button on your worksheet and add the following code line (A1 style):
Range("D4").Formula = "=B3*10"
Result:
2. Add the following code line (R1C1 style):
Range("D4").FormulaR1C1 = "=R3C2*10"
Result:
Explanation: cell D4 references cell B3 (row 3, column 2).
This is an absolute reference ($ symbol in front of the row number and column letter).
3. Add the following code line (R[1]C[1] style):
Range("D4").FormulaR1C1 = "=R[-1]C[-2]*10"
Result:
Explanation: cell D4 references cell B3 (one row above and 2 columns to the left).
This is a relative reference.
This code line gives the exact same result as the code line used at step 1.
4. Why learning about this? Because the Macro Recorder uses the FormulaR1C1 property (R[1]C[1] style).
The Macro Recorder creates the following code lines if you enter the formula =B3*10 into cell D4.
Explanation: you can see that this is the exact same code line used at step 3.
Add a Macro to the Toolbar
If you use an Excel macro frequently, you can add it to the Quick Access Toolbar.
This way you can quickly access your macro.
First, we record an empty macro.
1. On the Developer tab, click Record Macro.
2. Name the macro MyName.
Choose to store the macro in Personal Macro Workbook.
This way the macro will be available to all your workbooks (Excel files).
This is possible because Excel stores your macro in a hidden workbook that opens automatically when Excel starts.
3. Click OK.
4. Click Stop Recording.
5. Open the Visual Basic Editor.
6. Create the macro:
This macro places your name in the Active Cell.
7. Close the Visual Basic Editor.
8. Now we can add this macro to the Quick Access Toolbar.
Click the down arrow and click More Commands.
9. Under Choose commands, select Macros.
10. Select the macro and click Add.
11. You can modify the button that will be added to the Quick Access Toolbar by clicking on Modify.
For example, choose a smiley.
12. Click OK twice.
13. You can now execute the macro.
For example, select cell E2 and click on the smiley button added to the Quick Access Toolbar.Result:
14. When you close Excel, Excel asks you to save the changes you made to the Personal Macro Workbook.
Click Save to store this macro in a hidden workbook that opens automatically when Excel starts.
This way the macro will be available to all your workbooks (Excel files).
Enable Macros
Enable macros in Excel when the message bar appears.
Change your macro security settings in the Trust Center.
To create macros, turn on the Developer tab.
1. When the message bar appears, click Enable Content to enable macros.
Note: by clicking Enable Content, the Excel file becomes a trusted document.
As a result, you won't see the Security Warning again when you open this specific Excel file in the future.
2. To change your macro security settings, on the Developer tab, click Macro Security.
The Trust Center opens.
1. The first option disables all macros.
2. The second option always asks you to enable a macro.
Use this security level if you are downloading a lot of Excel files from the internet.
Don't click Enable Content (see first screenshot on this page) if you don't trust the owner of the Excel file.
3. The third option only allows macros with a digital signature to run, and asks you to enable others.
4. The fourth option enables all macros.
Use this security level if you are a beginner and only typing your own macros at the moment.
With this security level you don't have to enable macros all the time.
5. If you're new to Excel VBA, let's create a simple macro.
Protect Macro
Just like you can password protect workbooks and worksheets, you can password protect a macro in Excel from being viewed (and executed).
Place a command button on your worksheet and add the following code lines:
1. First, create a simple macro that you want to protect.
Range("A1").Value = "This is secret code"
2. Next, click Tools, VBAProject Properties.
3. On the Protection tab, check "Lock project for viewing" and enter a password twice.
4. Click OK.
5. Save, close and reopen the Excel file.
Try to view the code.
The following dialog box will appear:
You can still execute the code by clicking on the command button but you cannot view or edit the code anymore (unless you know the password).
The password for the downloadable Excel file is "easy".
6. If you want to password protect the macro from being executed, add the following code lines:
Dim password As Variant
password = Application.InputBox("Enter Password", "Password Protected")
Select Case password
Case Is = False
'do nothing
Case Is = "easy"
Range("A1").Value = "This is secret code"
Case Else
MsgBox "Incorrect Password"
End Select
Result when you click the command button on the sheet:
Explanation: The macro uses the InputBox method of the Application object.
If the users clicks Cancel, this method returns False and nothing happens (InputBox disappears).
Only when the user knows the password ("easy" again), the secret code will be executed.
If the entered password is incorrect, a MsgBox is displayed.
Note that the user cannot take a look at the password in the Visual Basic Editor because the project is protected from being viewed.
MsgBox Function
The MsgBox function in Excel VBA can return a result while a simple MsgBox cannot.
Situation:
Place a command button on your worksheet and add the following code lines:
1. First, we declare a variable called answer of type Integer.
Dim answer As Integer
2. We use the MsgBox function to initialize the variable answer with the input from the user.
The MsgBox function, when using parentheses, has three arguments.
The first part is used for the message in the message box.
Use the second part to specify which buttons and icons you want to appear in the message box.
The third part is displayed in the title bar of the message box.
answer = MsgBox("Are you sure you want to empty the sheet?", vbYesNo + vbQuestion, "Empty Sheet")
Note: Place your cursor on vbYesNo in the Visual Basic Editor and click F1 to see which other buttons and icons you can use.
Instead of the constants vbYesNo and vbQuestion, you can also use the corresponding values 4 and 32.
3. If the user clicks the Yes button, Excel VBA empties the sheet.
If the user clicks the No button, nothing happens.
Add the following code lines to achieve this.
If answer = vbYes Then
Cells.ClearContents
Else
'do nothingEnd If
4. Click the command button on the sheet.
5. Click Yes.
Result:
InputBox Function
You can use the InputBox function in Excel VBA to prompt the user to enter a value.
Place a command button on your worksheet and add the following code lines:
1. First, declare the variable myValue of type Variant.
Dim myValue As Variant
Note: we use a variable of type Variant here because a Variant variable can hold any type of value.
This way the user can enter text, numbers, etc.
2. Add the following code line to show the input box.
myValue = InputBox("Give me some input")
3. Write the value of myValue to cell A1.
Range("A1").Value = myValue
Result when the user enters the value 5 and clicks the OK button.
4. The InputBox function has more optional arguments.
The following code line shows an input box with a title displayed in the title bar and has a default value.
The default value will be used if no other input is provided.
myValue = InputBox("Give me some input", "Hi", 1)
Result when the user only clicks the OK button.
Note: Place your cursor on InputBox in the Visual Basic Editor and click F1 for help on the other optional arguments.
Path and FullName
The Path property in Excel VBA returns the complete, saved path to the workbook (Excel file).
The FullName property in Excel VBA returns the complete, saved path, including the name of the workbook.
Download path-fullname.xlsm and add it to "C:\test\"
Place a command button on your worksheet and add the following code lines:
1. The following code line returns the complete path to path-fullname.xlsm.
MsgBox Workbooks("path-fullname.xlsm").Path
Result:
2. The following code line returns the complete path, including the name of the active workbook.
MsgBox ActiveWorkbook.FullName
Result:
For a practical example of the FullName property, see our example program Create a Footer Before Printing.Close and Open
The Close and Open Method in Excel VBA can be used to close and open workbooks.
Remember, the Workbooks collection contains all the Workbook objects that are currently open.
Place a command button on your worksheet and add the following code lines:
1. The code line below closes close-open.xlsm.
Workbooks("close-open.xlsm").Close
2. The code line below closes the first opened/created workbook.
Workbooks(1).Close
3. The code line below closes the active workbook.
ActiveWorkbook.Close
4. The code line below closes all workbooks that are currently open.
Workbooks.Close
5. The code line below opens sales.xlsx.
Workbooks.Open ("sales.xlsx")
Note: you can only open sales.xlsx without specifying the file's path if it's stored in your default file location.
To change the default file location, on the File tab, click Options, Save.
6. You can also use the GetOpenFilename method of the Application object to display the standard Open dialog box.
Dim MyFile As String
MyFile = Application.GetOpenFilename()
7. Select a file and click Open.
Note: GetOpenFilename doesn't actually open the file.
8. Next, you can open the workbook as usual.
Workbooks.Open (MyFile)
Loop through Books and Sheets
Below we will look at a program in Excel VBA that loops through all open workbooks and worksheets, and displays all the names.
Situation:
Add the following code lines to the command button:
1. First, we declare two objects and one variable.
One object of type Workbook we call book, one object of type Worksheet we call sheet, and a variable of type String we call text.
Dim book As Workbook, sheet As Worksheet, text As String
2. We want to loop through all open workbooks.
To achieve this, add the following code line:
For Each book In Workbooks
3. We write the text "Workbook: ", the name of the workbook, and the text "Worksheets: "" to the variable text.
text = text & "Workbook: " & book.Name & vbNewLine & "Worksheets: " & vbNewLine
Note: you can use the & operator to concatenate (join) elements.
To start a new line, you can use vbNewLine.
4. To loop through all the worksheets of a workbook, add the following code line:
For Each sheet In book.Worksheets
5. We write the names of the worksheets of a workbook to the variable text.
text = text & sheet.Name & vbNewLine
6. Close the second loop.Next sheet
7. Add a white line.
text = text & vbNewLine
8. Don't forget to close the first loop.Next book
9. Finally, we display the variable text using a MsgBox.
MsgBox text
10. Test the program.
Before you click on the command button, give your worksheets some descriptive names and open a blank workbook with three worksheets.
Result:
Sales Calculator
Below we will look at a program in Excel VBA that calculates the total sales of each employee over a period of three years.
Situation:
The other two sheets have the same setup, but with different combinations of months and employees, and different sales numbers.
There are several ways to calculate the total sales of each employee in Excel, but we will see that it can be done in Excel VBA very easily.
Place a command button on your worksheet and add the following code lines:
1. First, we declare three variables and one Worksheet object.
One variable of type String we call employee, one variable of type Integer we call total, one Worksheet object we call sheet, and one variable of type Integer we call i.
Dim employee As String, total As Integer, sheet As Worksheet, i As Integer
2. We initialize two variables.
We initialize the variable total with value 0. We use the InputBox function to get the employee name from the user.
total = 0
employee = InputBox("Enter the employee name (case sensitive)")
3. After the user has entered an employee name, we want to calculate the total sales of this employee.
The workbook consists of three sheets.
We want a program that can still be used if sheets are added in the future.
Therefore we use the following code line:
For Each sheet In Worksheets
4. We start another For Next loop.
For i = 2 To 13
5. If the entered employee name matches with the employee name in column B, Excel VBA adds the sales number to the variable total.
Add the following code lines:
If sheet.Cells(i, 2).Value = employee Then
total = total + sheet.Cells(i, 3).ValueEnd If
6. Don't forget to close both loops.Next iNext sheet
7. Finally, we display the total sales of the employee using a msgbox.
MsgBox "Total sales of " & employee & " is " & total
8. Test the program.
Result for David:
Files in a Directory
Below we will look at a program in Excel VBA that loops through all closed workbooks and worksheets in a directory, and displays all the names.
Download Book1.xlsx, Book2.xlsx, Book3.xlsx, Book4.xlsx and Book5.xlsx and add them to "C:\test\"
Situation:
Add the following code lines to the command button:
1. First, we declare two variables of type String, a Worksheet object and two variables of type Integer.
Dim directory As String, fileName As String, sheet As Worksheet, i As Integer, j As Integer
2. To avoid screen flicker, turn off screen updating.
Application.ScreenUpdating = False
3. Initialize the variable directory.
We use the Dir function to find the first *.xl?? file stored in this directory.
directory = "c:\test\"
fileName = Dir(directory & "*.xl??")
Note: the Dir function supports the use of multiple character (*) and single character (?) wildcards to search for all different type of Excel files.
4. The variable fileName now holds the name of the first Excel file found in the directory.
Add a Do While Loop.
Do While fileName <> ""
Loop
Add the following code lines (at 5, 6, 7, 8 and 9) to the loop.
5. Initialize the variables of type Integer and add the name of the Excel file to the first column of row i.
i = i + 1
j = 2
Cells(i, 1) = fileName
6. There is no simple way to extract data (or sheet names) from closed Excel files.
Therefore, we open the Excel file.
Workbooks.Open (directory & fileName)
7. Add all the sheet names of the Excel file to the other columns of row i.
For Each sheet In Workbooks(fileName).Worksheets
Workbooks("files-in-a-directory.xlsm").Worksheets(1).Cells(i, j).Value = sheet.Name
j = j + 1Next sheet
8. Close the Excel file.
Workbooks(fileName).Close
9. The Dir function is a special function.
To get the other Excel files, you can use the Dir function again with no arguments.
fileName = Dir()
Note: when no more file names match, the Dir function returns a zero-length string ("").
As a result, Excel VBA will leave the Do While loop.
10. Turn on screen updating again (outside the loop).
Application.ScreenUpdating = True
11. Test the program.
Result:
Import Sheets
Below we will look at a program in Excel VBA that imports sheets from other Excel files into one Excel file.
Download Book4.xlsx, Book5.xlsx and add them to "C:\test\"
Situation:
Add the following code lines to the command button:
1. First, we declare two variables of type String, a Worksheet object and one variable of type Integer.
Dim directory As String, fileName As String, sheet As Worksheet, total As Integer
2. Turn off screen updating and displaying alerts.
Application.ScreenUpdating = False
Application.DisplayAlerts = False
3. Initialize the variable directory.
We use the Dir function to find the first *.xl?? file stored in this directory.
directory = "c:\test\"
fileName = Dir(directory & "*.xl??")
Note: The Dir function supports the use of multiple character (*) and single character (?) wildcards to search for all different type of Excel files.
4. The variable fileName now holds the name of the first Excel file found in the directory.
Add a Do While Loop.
Do While fileName <> ""
Loop
Add the following code lines (at 5, 6, 7 and 8) to the loop.
5. There is no simple way to copy worksheets from closed Excel files.
Therefore we open the Excel file.
Workbooks.Open (directory & fileName)
6. Import the sheets from the Excel file into import-sheet.xlsm.
For Each sheet In Workbooks(fileName).Worksheets
total = Workbooks("import-sheets.xlsm").Worksheets.count
Workbooks(fileName).Worksheets(sheet.Name).Copy _
after:=Workbooks("import-sheets.xlsm").Worksheets(total)Next sheet
Explanation: the variable total holds track of the total number of worksheets of import-sheet.xlsm.
We use the Copy method of the Worksheet object to copy each worksheet and paste it after the last worksheet of import-sheets.xlsm.
7. Close the Excel file.
Workbooks(fileName).Close
8. The Dir function is a special function.
To get the other Excel files, you can use the Dir function again with no arguments.
fileName = Dir()
Note: When no more file names match, the Dir function returns a zero-length string ("").
As a result, Excel VBA will leave the Do While loop.
9. Turn on screen updating and displaying alerts again (outside the loop).
Application.ScreenUpdating = True
Application.DisplayAlerts = True
10. Test the program.
Result:
Programming Charts
Below we will look at two programs in Excel VBA.
One program loops through all charts on a sheet and changes each chart to a pie chart.
The other program changes some properties of the first chart.
1. Create some charts (or download the Excel file).
Place a command button on the worksheet and add the following code lines:
1. First, we need to declare a ChartObject object.
The ChartObject object acts as a container for a Chart object.
We call the ChartObject cht but you can use any name.
Dim cht As ChartObject
2. The ChartObjects collection contains all the embedded charts on a single sheet.
We want to loop through all charts on the first sheet.
Add the following For Each Next loop.
For Each cht In Worksheets(1).ChartObjectsNext cht
3. The Chart object represents a chart in a workbook.
Add the following code line to the For Each Next loop to change each chart to a pie chart.
cht.Chart.ChartType = xlPie
Note: again, cht acts as a container for the Chart object.
We use the ChartType property to change the chart type.
We use the built-in constant xlPie to change each chart to a pie chart.
4. Result when you click the command button on the sheet:
Now we will change some properties of the first chart.
Place another command button on the worksheet and add the following code lines:
5. The ChartObjects collection contains all the embedded charts on a single sheet.
Add the following code line to activate the first chart:
Worksheets(1).ChartObjects(1).Activate
We can now refer to this chart as the ActiveChart.
6. Add the following code line to change the Chart title.
ActiveChart.ChartTitle.Text = "Sales Report"
7. Add the following code line to move the legend to the bottom of the chart:
ActiveChart.Legend.Position = xlBottom
8. Result when you click the command button on the sheet:
CurrentRegion
This example illustrates the CurrentRegion property in Excel VBA.
The current region is a range bounded by any combination of blank rows and blank columns.
Can you find the current region of cell A1?
Place a command button on your worksheet and add the following code line:
Range("A1").CurrentRegion.Select
Result when you click the command button on the sheet:
Here is another example.
Can you find the current region of cell B3?
Code:
Range("B3").CurrentRegion.Select
Result:
The value 1 in row 1 has no influence on the current region of cell B3. Row 2 is empty!
Dynamic Range
Below we will look at a program in Excel VBA that colors the maximum value of a dynamic range.
Situation:
Each time we add a number and we click the command button, we want Excel VBA to color the maximum value of these numbers.
Place a command button on your worksheet and add the following code lines:
1. First, we declare one variable and two Range objects.
One variable of type Double we call maximum.
We call the Range objects rng and cell.
Dim maximum As Double, rng As Range, cell As Range
2. We add the line which changes the background color of all cells to 'No Fill'.
Cells.Interior.ColorIndex = 0
3. We initialize rng with the numbers.
We use the CurrentRegion property for this.
CurrentRegion is useful when we don't know the exact boundaries of a range in advance.
Set rng = Range("A1").CurrentRegion
4. We initialize maximum with the maximum value of the numbers.
We use the worksheet function Max to find the maximum value.
maximum = WorksheetFunction.Max(rng)
5. Finally, we color the maximum value.
We use a For Each Next Loop.
For Each cell In rng
If cell.Value = maximum Then cell.Interior.ColorIndex = 22Next cell
Note: instead of ColorIndex number 22 (red), you can use any ColorIndex number.
6. Add a number.
Result when you click the command button on the sheet:
Resize
Contract | Expand
The Resize property in Excel VBA makes a range a specific number of rows and columns smaller or larger.
The Resize property always takes the top left cell of a range as the starting point.
Contract
To contract the size of a range, specify a smaller number of rows or columns than the original range.
Place a command button on your worksheet and add the following code line:
Range("A1:C4").Resize(3, 2).Select
Result:
Explanation: this code line resizes Range("A1:C4") to 3 rows and 2 columns and selects this range (border for illustration only).
Code line:
Range("A1:C4").Resize(, 1).Select
Result:
Explanation: this code line resizes Range("A1:C4") to 1 column (we omit any row specification) and selects this range.
Expand
To expand the size of a range, specify a larger number of rows or columns than the original range.
Code line:
Range("A1:C4").Resize(, 5).Select
Result:
Explanation: this code line resizes Range("A1:C4") to 5 columns.
The Select method selects Range("A1:E4").
Code line:
Range("A1:C4").Resize(10) = 99
Result:
Explanation: this code line resizes Range("A1:C4") to 10 rows.
Instead of using the Select method, you can work with the resized range directly.
For example, set the values of the cells in the resized range to 99. Entire Rows and Columns
This example teaches you how to select entire rows and columns in Excel VBA.
Are you ready?
Place a command button on your worksheet and add the following code lines:
1. The following code line selects the entire sheet.
Cells.Select
Note: because we placed our command button on the first worksheet, this code line selects the entire first sheet.
To select cells on another worksheet, you have to activate this sheet first.
For example, the following code lines select the entire second worksheet.Worksheets(2).Activate
Worksheets(2).Cells.Select
2. The following code line selects the second column.
Columns(2).Select
3. The following code line selects the seventh row.
Rows(7).Select
4. To select multiple rows, add a code line like this:
Rows("5:7").Select
5. To select multiple columns, add a code line like this:
Columns("B:E").Select
6. Be careful not to mix up the Rows and Columns properties with the Row and Column properties.
The Rows and Columns properties return a Range object.
The Row and Column properties return a single value.
Code line:
MsgBox Cells(5, 2).Row
Result:
7. Select cell D6. The following code line selects the entire row of the active cell.
ActiveCell.EntireRow.Select
Note: border for illustration only.
8. Select cell D6. The following code line enters the value 2 into the first cell of the column that contains the active cell.
ActiveCell.EntireColumn.Cells(1).Value = 2
Note: border for illustration only.
9. Select cell D6. The following code line enters the value 3 into the first cell of the row below the row that contains the active cell.
ActiveCell.EntireRow.Offset(1, 0).Cells(1).Value = 3
Note: border for illustration only.
Offset
The Offset property in Excel VBA takes the range which is a particular number of rows and columns away from a certain range.
Place a command button on your worksheet and add the following code lines:
1. The Offset property below returns a range which is 3 rows below and 2 columns to the right of a range.
Range("A1:A2").Offset(3, 2).Select
Explanation: the Select method selects this range.
The Offset property always takes the top left cell of a range as the starting point.
Border for illustration only.
2. The Offset property below returns a range which is 1 row above and 4 columns to the left of a range.
Range("F5:H5").Offset(-1, -4).Select
3. You can also offset by a number of rows only.
For example, return a range which is 5 rows below a range.Range("B2:D3").Offset(5).Select
4. Finally, you can also offset by a number of columns only.
For example, return a cell which is 2 columns to the left of a cell.Range("G8").Offset(0, -2).Select
For a practical example of the offset property, see our example program Create a Pattern.From Active Cell to Last Entry
This example illustrates the End property of the Range object in Excel VBA.
We will use this property to select the range from the Active Cell to the last entry in a column.
Situation:
Some sales figures in column A.
Assume that you will be adding more sales figures over time.
Place a command button on your worksheet and add the following code lines:
1. To select the last entry in a column, simply add the following code line:
Range("A5").End(xlDown).Select
Note: instead of Range("A5"), you can also use Range("A1"), Range("A2"), etc.
This code line is equivalent to pressing the END+DOWN ARROW.
Result when you click the command button on the sheet:
2. To select the range from cell A5 to the last entry in the column, add the following code line:
Range(Range("A5"), Range("A5").End(xlDown)).Select
Result when you click the command button on the sheet:
3. To select the range from the Active Cell to the last entry in the column, simply replace Range("A5") with ActiveCell.
Range(ActiveCell, ActiveCell.End(xlDown)).Select
Result when you select cell A2 and click the command button on the sheet:
Note: you can use the constants xlUp, xlToRight and xlToLeft to move in the other directions.
This way you can select a range from the Active Cell to the last entry in a row.
Union and Intersect
The Union method in Excel VBA returns a Range object that represents the union of two or more ranges (borders below for illustration only).
Code line:
Union(Range("B2:C7"), Range("C6:F8")).Select
Result:
Note: the Union method doesn't return the mathematical union (cell C6 and cell C7 are included twice).
The Intersect method in Excel VBA returns a Range object that represents the intersection of two or more ranges (borders below for illustration only).
Code line:
Intersect(Range("B2:C7"), Range("C6:F8")).Select
Result:
Test a Selection
This program in Excel VBA uses the Count property, IsNumeric function, IsEmpty function and Intersect method to test a selection.
Situation:
Place a command button on your worksheet and add the following code lines:
1. First, we declare two Range objects.
We call the Range objects rng and cell.
Dim rng As Range, cell As Range
2. We initialize the Range object rng with Range("C4:D10") and the Range object cell with the selected range.
Set rng = Range("C4:D10")
Set cell = Selection
3. Add the following code lines:
If cell.Count = 1 And IsNumeric(cell) And Not IsEmpty(cell) And Not Intersect(rng, cell) Is Nothing Then
MsgBox "You win"
Else
MsgBox "You lose"End If
Explanation: Intersect(rng, cell) returns a Range object that represents the intersection of the two ranges.
If this range object is not Nothing, the single number (first three conditions) is in the bordered range.
4. Test the program.
Only when you select a single number in the bordered range the result will be:
In all other cases the result will be:
Possible Football Matches
Below we will look at a program in Excel VBA that shows a print preview of all the possible football matches from a list of teams.
Situation:
1. First, we declare one Range object and four variables.
We call the Range object rng.
One String variable we call matchname, and three Integer variables we call counter, i and j.
Dim rng As Range, matchname As String, counter As Integer, i As Integer, j As Integer
2. We initialize rng with the team names.
We use CurrentRegion because we don't know the exact boundaries of the range in advance (we want this program to work for 3 teams but also for 12 teams).
We initialize counter with value 0.
Set rng = Range("A1").CurrentRegion
counter = 0
3. We write all the possible football matches to column C.
First, we empty column C.
Worksheets(1).Columns(3) = ""
4. We start a Double Loop.
For i = 1 To rng.Count
For j = i + 1 To rng.Count
5. We write a matchname to the variable matchname.
matchname = rng.Cells(i).Value & " vs " & rng.Cells(j).Value
For example, for i = 1 and j = 2, Excel VBA writes the matchname Kickers vs Shooters.For i = 1 and j = 3, Excel VBA writes the matchname Kickers vs Little Giants, etc.
6. We write the matchname to column C.
Cells(counter + 1, 3).Value = matchname
7. The counter keeps track of the number of matchnames written to column C.
Excel VBA increments counter by 1 each time it writes a matchname to column C.
To achieve this, add the following code line:
counter = counter + 1
8. Don't forget to close the two loops.Next jNext i
9. We show a print preview of all the possible football matches.
ActiveSheet.Columns(3).PrintPreview
10. Test the program.
Part of the result:
Note: column C is manually centered to get this result.
Font
The Font property of the Range object in Excel VBA gives access to a lot of other properties.
That is because the Font property returns an object itself; the Font object.
The Font object has many properties like the Color property and the Bold property.
Color property
To change the color of an Excel range, use the Font property of the Range object, and then the Color property of the Font object.
1. Add the following code line:
Range("A1").Font.Color = -16776961
Explanation: Where do we get this strange number from? Well, we started the Macro Recorder and changed the color of a cell to red.
You can do this for every color!
2. The following code line gives the exact same result.
Range("A1").Font.Color = vbRed
Explanation: vbRed is a sort of built-in constant in Excel VBA.
Place your cursor on vbRed in the Visual Basic Editor and click F1 to see which other constants you can use.
3. The following code line gives the exact same result.
Range("A1").Font.Color = RGB(255, 0, 0)
Explanation: RGB stands for Red, Green and Blue.
These are the three primary colors.
Each component can take on a value from 0 to 255. With this function you can make every color.
RGB(255,0,0) gives the pure Red color.
Bold property
The following code line bolds a range:
Range("A1").Font.Bold = True
To unbold a range, you can use the False keyword.
The Font object has many more properties.
If you want to program these sort of things, just use the Macro Recorder to see how to do it! Usually code created by the Macro Recorder is too long.
For example, the Macro Recorder creates the following code when we bold Range("A1").
We have just seen that these two code lines can be written as one code line.
Background Colors
Changing background colors in Excel VBA is easy.
Use the Interior property to return an Interior object.
Then use the ColorIndex property of the Interior object to set the background color of a cell.
Place three command buttons on your worksheet and add the following code lines:
1. The code line below sets the background color of cell A1 to light blue.
Range("A1").Interior.ColorIndex = 37
Result:
2. The following code line sets the background color of cell A1 to 'No Fill'.
Range("A1").Interior.ColorIndex = 0
Result:
3. If you want to know the ColorIndex number of a color, simply ask Excel VBA.
MsgBox Selection.Interior.ColorIndex
Select cell A1 and click the command button on the sheet:
Result:
4. The ColorIndex property gives access to a color palette of 56 colors.
Note: download the Excel file to see how we created this color palette.
5. If you can't find the specific color you are looking for, use the Color property and the RGB function.
Range("A1").Interior.Color = RGB(255, 0, 0)
Explanation: RGB stands for Red, Green and Blue.
These are the three primary colors.
Each component can take on a value from 0 to 255. With this function you can make every color.
RGB(255,0,0) gives the pure Red color (ColorIndex = 3 produces the exact same result).
Areas Collection
This example illustrates the Areas collection in Excel VBA.
Below we have bordered Range("B2:C3,C5:E5").
This range has two areas.
The comma separates the two areas.
Place a command button on your worksheet and add the following code lines:
1. First, we declare two Range objects.
We call the Range objects rangeToUse and singleArea.
Dim rangeToUse As Range, singleArea As Range
2. We initialize the Range object rangeToUse with Range("B2:C3,C5:E5")
Set rangeToUse = Range("B2:C3,C5:E5")
3. To count the number of areas of rangeToUse, add the following code line:
MsgBox rangeToUse.Areas.Count
Result:
4. You can refer to the different areas of rangeToUse by using the index values.
The following code line counts the numbers of cells of the first area.
MsgBox rangeToUse.Areas(1).Count
Result:
5. You can also loop through each area of rangeToUse and count the number of cells of each area.
The macro below does the trick.
For Each singleArea In rangeToUse.Areas
MsgBox singleArea.CountNext singleArea
Result:
For a practical example of the areas collection, see our example program Compare Ranges.Compare Ranges
Below we will look at a program in Excel VBA that compares randomly selected ranges and highlights cells that are unique.
If you are not familiar with areas yet, we highly recommend you to read this example first.
Situation:
Note: the only unique value in this example is the 3 since all other values occur in at least one more area.
To select Range("B2:B7,D3:E6,D8:E9"), hold down Ctrl and select each area.
Place a command button on your worksheet and add the following code lines:
1. First, we declare four Range objects and two variables of type Integer.
Dim rangeToUse As Range, singleArea As Range, cell1 As Range, cell2 As Range, i As Integer, j As Integer
2. We initialize the Range object rangeToUse with the selected range.
Set rangeToUse = Selection
3. Add the line which changes the background color of all cells to 'No Fill'.
Also add the line which removes the borders of all cells.
Cells.Interior.ColorIndex = 0
Cells.Borders.LineStyle = xlNone
4. Inform the user when he or she only selects one area.
If Selection.Areas.Count <= 1 Then
MsgBox "Please select more than one area."
Else
End If
The next code lines (at 5, 6 and 7) must be added between Else and End If.
5. Color the cells of the selected areas.
rangeToUse.Interior.ColorIndex = 38
6. Border each area.
For Each singleArea In rangeToUse.Areas
singleArea.BorderAround ColorIndex:=1, Weight:=xlThinNext singleArea
7. The rest of this program looks as follows.
For i = 1 To rangeToUse.Areas.Count
For j = i + 1 To rangeToUse.Areas.Count
For Each cell1 In rangeToUse.Areas(i)
For Each cell2 In rangeToUse.Areas(j)
If cell1.Value = cell2.Value Then
cell1.Interior.ColorIndex = 0
cell2.Interior.ColorIndex = 0
End If
Next cell2
Next cell1
Next jNext i
Explanation: this may look a bit overwhelming, but it's not that difficult.
rangeToUse.Areas.Count equals 3, so the first two code lines reduce to For i = 1 to 3 and For j = i + 1 to 3. For i = 1, j = 2, Excel VBA compares all values of the first area with all values of the second area.
For i = 1, j = 3, Excel VBA compares all values of the first area with all values of the third area.For i = 2, j = 3, Excel VBA compares all values of the second area with all values of the third area.If values are the same, it sets the background color of both cells to 'No Fill', because they are not unique.
Result when you click the command button on the sheet:
Option Explicit
We strongly recommend to use Option Explicit at the start of your Excel VBA code.
Using Option Explicit forces you to declare all your variables.
For example, place a command button on your worksheet and add the following code lines:Dim myVar As Integer
myVar = 10
Range("A1").Value = mVar
Result when you click the command button on the sheet:
Clearly, cell A1 does not contain the value 10. That is because we accidentally misspelled myVar.
As a result, Excel VBA places the value of the undeclared, empty variable mVar into cell A1.
When using Option Explicit, the code lines above generate an error because we did not declare the variable mVar.
Result:
1. Click OK.
Then Click on Reset (Stop) to stop the debugger.
2. Correct mVar so that it reads myVar.
Result when you click the command button on the sheet:
Now you know why you should always use Option Explicit at the start of your Excel VBA code.
It avoids incorrectly typing the name of an existing variable.
Fortunately, you can instruct Excel VBA to automatically add Option Explicit.
1. In the Visual Basic Editor, click on Tools and then click on Options.
2. Check Require Variable Declaration.
Note: Option Explicit will not be added automatically to existing Excel files.
Simply type in Option Explicit yourself if you want to use it.
Variable Scope
The scope of a variable in Excel VBA determines where that variable may be used.
You determine the scope of a variable when you declare it.
There are three scoping levels: procedure level, module level, and public module level.
Place a command button on your worksheet and add the following code lines:
1. Place the two procedures (a procedure is either a sub or a function) into a module.
In the Visual Basic Editor, click Insert, Module.
Add the following code lines:
2. Result when you click the command button on the sheet (call the two subs):
Explanation: the variable txt has scope procedure level because it is declared in the procedure (between Sub and End Sub).
As a result, you can only use this variable in sub1. The variable txt cannot be used in sub2.
3. When you want a variable to be available to all procedures in a module, you are saying you want the variable to have module level scope.
You need to declare the variable in the General Declarations section (at the top of the module).
Slightly adjust the code as follows:
4. Result when you click the command button on the sheet:
Explanation: the variable txt can now be used in sub2. Module level is used interchangeably with private module level.
That is because by default variables declared with the Dim statement in the General Declarations section are scoped as private.
You can also scope a variable as public.
Read on.
5. By using the Public keyword, your variable will be available to all procedures in all modules in a workbook.
This is called public module level scope.
Slightly adjust the code as follows:
Explanation: now you can create a new module and place a sub called sub3 into this module.
Use the same code as sub2. Add sub3 to your command button code.
When you click the command button on the worksheet, you will get three message boxes saying "Variable can only be used in this procedure" (see downloadable Excel file).
Life of Variables
Sometimes you want to retain the value of a variable in Excel VBA when a procedure ends.
You can achieve this by using the Static keyword.
1. Place a command button on your worksheet and add the following code lines:
2. Result when you click the command button on the sheet:
3. Result when you click another time:
Explanation: Excel VBA destroys the variable when the procedure ends.
Each time you click the command button on the sheet, Excel VBA creates the variable x again, adds the value 1 to it, and displays the result.
4. Now replace the keyword Dim with the keyword Static.
5. Result when you click the command button on the sheet:
6. Result when you click another time:
Conclusion: static variables retain their values, even when a procedure ends.
Note: static variables will be destroyed when you click the Reset (Stop) button or when you close your workbook.
Type Mismatch
The type mismatch error in Excel VBA occurs when you try to assign a value to a variable that isn't of the correct type.
Place a command button on your worksheet and add the following code lines:
Dim number As Integer
number = "bike"
Result when you click the command button on the sheet:
Explanation: you cannot assign a string value (bike) to a variable of type Integer.
The type mismatch error (run-time error 13) often occurs when using the InputBox function in Excel VBA.
1. Place a command button on your worksheet and add the following code lines:
Dim number As Integer
number = InputBox("Enter a number", "Square Root")
MsgBox "The square root of " & number & " is " & Sqr(number)
2. Click the command button on the sheet, enter the string value hundred and click OK.
Result:
3. Clik End.
4. To display a friendly message instead of the type mismatch error, update the code as follows.
Dim number As Variant
number = InputBox("Enter a number", "Square Root")
If IsNumeric(number) Then
MsgBox "The square root of " & number & " is " & Sqr(number)
Else
MsgBox "Please enter a number"End If
Explanation: a variable of type Variant can hold any type of value (see first line).
The IsNumeric function in Excel VBA checks if a value is a number.
5. Repeat step 2.
Result:
6. Finally, check if this simple square root calculator works.
Result:
Tip: download the Excel file (right side of this page) and give it a try.
Logical Operators
Logical Operator And | Logical Operator Or | Logical Operator Not
The three most used logical operators in Excel VBA are: And, Or and Not.
As always, we will use easy examples to make things more clear.
Logical Operator And
Place a command button on your worksheet and add the following code lines:
Dim score1 As Integer, score2 As Integer, result As String
score1 = Range("A1").Value
score2 = Range("B1").Value
If score1 >= 60 And score2 > 1 Then
result = "pass"
Else
result = "fail"End If
Range("C1").Value = result
Explanation: if score1 is greater than or equal to 60 and score2 is greater than 1, Excel VBA returns pass, else Excel VBA returns fail.
Result when you click the command button on the sheet:
Conclusion: Excel VBA returns fail because score2 is not greater than 1.
Logical Operator Or
Place a command button on your worksheet and add the following code lines:
Dim score1 As Integer, score2 As Integer, result As String
score1 = Range("A1").Value
score2 = Range("B1").Value
If score1 >= 60 Or score2 > 1 Then
result = "pass"
Else
result = "fail"End If
Range("C1").Value = result
Explanation: if score1 is greater than or equal to 60 or score2 is greater than 1, Excel VBA returns pass, else Excel VBA returns fail.
Result when you click the command button on the sheet:
Conclusion: Excel VBA returns pass because score1 is greater than or equal to 60.
Logical Operator Not
Place a command button on your worksheet and add the following code lines:
Dim score1 As Integer, score2 As Integer, result As String
score1 = Range("A1").Value
score2 = Range("B1").Value
If score1 >= 60 And Not score2 = 1 Then
result = "pass"
Else
result = "fail"End If
Range("C1").Value = result
Explanation: if score1 is greater than or equal to 60 and score2 is not equal to 1, Excel VBA returns pass, else Excel VBA returns fail.
Result when you click the command button on the sheet:
Conclusion: Excel VBA returns fail because score2 is equal to 1.
Select Case
Instead of multiple If Then statements in Excel VBA, you can use the Select Case structure.
Situation:
Place a command button on your worksheet and add the following code lines:
1. First, declare two variables.
One variable of type Integer named score and one variable of type String named result.
Dim score As Integer, result As String
2. We initialize the variable score with the value of cell A1.
score = Range("A1").Value
3. Add the Select Case structure.
Select Case score
Case Is >= 80
result = "very good"
Case Is >= 70
result = "good"
Case Is >= 60
result = "sufficient"
Case Else
result = "insufficient"
End Select
Explanation: Excel VBA uses the value of the variable score to test each subsequent Case statement to see if the code under the Case statement should be executed.
4. Write the value of the variable result to cell B1.
Range("B1").Value = result
5. Test the program.
Result when you click the command button on the sheet:
Note: Excel VBA executes the code under the second Case statement for all values greater than or equal to 70 and less than 80.
Tax Rates
Below we will look at a program in Excel VBA that calculates the tax on an income.
The following tax rates apply to individuals who are residents of Australia.
Taxable income |
Tax on this income |
0 - $6,000 |
Nil |
$6,001 - $35,000 |
15c for each $1 over $6,000 |
$35,001 - $80,000 |
$4,350 plus 30c for each $1 over $35,000 |
$80,001 - $180,000 |
$17,850 plus 38c for each $1 over $80,000 |
$180,001 and over |
$55,850 plus 45c for each $1 over $180,000 |
Situation:
1. First, we declare two double variables.
One double variable we call income, and one double variable we call tax.
Dim income As Double
Dim tax As Double
2. We initialize the variable income with the value of cell A2 and round it.
income = Round(Range("A2").Value)
3. We place the rounded value into cell A2 again.
Range("A2").Value = income
4. We use the Select Case statement to calculate the tax on an income.
Excel VBA uses income to test each subsequent Case statement to see if the code under the Case statement should be executed.
Select Case income
Case Is >= 180001
tax = 55850 + 0.45 * (income - 180000)
Case Is >= 80001
tax = 17850 + 0.38 * (income - 80000)
Case Is >= 35001
tax = 4350 + 0.3 * (income - 35000)
Case Is >= 6001
tax = 0.15 * (income - 6000)
Case Else
tax = 0
End Select
Example: if income is 37000, tax equals 4350 + 0.3 * (37000-35000) = 4350 + 600 = $4950
5. We write the value of the variable tax to cell B2.
Range("B2").Value = tax
6. Place this code in a command button and test it.
Result:
Mod Operator
Mod 101 | Even or Odd | Divisible by Another Number
The Mod operator in Excel VBA gives the remainder of a division.
This page starts with some simple examples.
Mod 101
Place a command button on your worksheet and add the following code line:
MsgBox 7 Mod 2
Result when you click the command button on the sheet:
Explanation: 7 divided by 2 equals 3 with a remainder of 1.
Code line:
MsgBox 8 Mod 2
Result:
Explanation: 8 divided by 2 equals 4 with a remainder of 0.
Even or Odd
Let's create a program that uses the Mod operator to check if a number is even or odd.
Code lines:
Dim x As Integer
x = Range("A1").Value
If x Mod 2 = 0 Then
Range("B1").Value = "Even"
Else
Range("B1").Value = "Odd"End If
For example, enter the value 100 into cell A1 and click the command button on the sheet.Result:
Explanation: a number is even if it is divisible by 2 without a remainder.
Divisible by Another Number
Let's create a program that uses the Mod operator to check if a number is divisible by another number.
Code lines:
Dim x As Integer
x = Range("A1").Value
If x Mod 4 = 0 Then
Range("B1").Value = "Divisible by 4"
Else
Range("B1").Value = "Not divisible by 4"End If
For example, enter the value 50 into cell A1 and click the command button on the sheet.Result:
Explanation: 50 divided by 4 equals 12 with a remainder of 2. In other words, 50 is not divisible by 4.
Prime Number Checker
Below we will look at a program in Excel VBA that checks whether a number is a prime number or not.
Before you start: in mathematics, a prime number is a number that has exactly two distinct number divisors: 1 and itself.
The smallest twenty-five prime numbers are: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89 and 97. For example, 8 has 1, 2, 4 and 8 as divisors and is not a prime number.
Situation:
1. First, we declare three variables.
One Integer variable we call divisors, one Long variable we call number and one Long variable we call i.
We use Long variables here because Long variables have larger capacity than Integer variables.
Dim divisors As Integer, number As Long, i As Long
2. We initialize two variables.
We initialize the variable divisors with value 0. We use the InputBox function to get a number from the user.
divisors = 0
number = InputBox("Enter a number")
After the user has entered a number, we want to check whether this number is a prime number or not.
Remember, a prime number has exactly two distinct number divisors: 1 and itself.
3. We start a For Next loop.
For i = 1 To number
4. Now comes the most important part of the program.
To calculate the number of divisors of a number, we use the Mod operator.
The Mod operator gives the remainder of a division.
For example, 7 mod 2 = 1 because 7 divided by 2 equals 3 with a remainder of 1. Only if 'number mod i' = 0, i is a divisor of number.In this case we want to increment the variable divisors by 1. The macro below does the trick.
If number Mod i = 0 Then
divisors = divisors + 1End If
Excel VBA checks this for i = 1, i = 2, i = 3, i = 4 until i = number.
Note that i = 1 and i = number always are divisors of number.
Only if these numbers are the only divisors of number, the number is a prime number.
5. Don't forget to close the loop.Next i
6. If divisors equals 2, we display a msgbox saying that the entered number is a prime number.
If the number of divisors is higher than 2, we display a msgbox saying that the entered number is not a prime number.
If divisors = 2 Then
MsgBox number & " is a prime number"
Else
MsgBox number & " is not a prime number"End If
7. Test the program.
Result for 104729:
Find Second Highest Value
Below we will look at a program in Excel VBA that finds the second highest value.
Situation:
1. First, we declare two Range objects and two variables of type Double.
We call the Range objects rng and cell.
One double variable we call highestValue, and one double variable we call secondHighestValue.
Dim rng As Range, cell As Range
Dim highestValue As Double, secondHighestValue As Double
2. We initialize the Range object rng with the selected range and the two Double variables with value 0.
Set rng = Selection
highestValue = 0
secondHighestValue = 0
3. First, we want to find the highest value.
We want to check each cell in a randomly selected range (this range can be of any size).
In Excel VBA, you can use the For Each Next loop for this.
Add the following code lines:
'Find Highest Value
For Each cell In rngNext cell
Note: rng and cell are randomly chosen here, you can use any names.
Remember to refer to these names in the rest of your code.
The green line is a comment and is only added here to provide information about this piece of code.
4. We check each cell in this range.
If it's higher than highestValue, we write the value to the variable highestValue.
Add the following code line to the loop.
If cell.Value > highestValue Then highestValue = cell.Value
Note: the first value is always higher than highestValue because the starting value of highestValue is 0.
5. Second, we want to find the second highest Value.
We add another For Each Next loop.
'Find Second Highest Value
For Each cell In rngNext cell
6. We check each cell in the selected range again.
If it's higher than secondHighestValue and lower than highestValue, we write the value to the variable secondHighestValue.
Add the following code line to the loop.
If cell.Value > secondHighestValue And cell.Value < highestValue Then secondHighestValue = cell.Value
7. Finally, we display the second highest value using a MsgBox.
MsgBox "Second Highest Value is " & secondHighestValue
8. Place your macro in a command button, select the numbers, and click on the command button.
Result:
Note: understanding If Then statements and loops in Excel VBA is important if you want to write more complicated programs in the future.
However, in this example, you can also use WorksheetFunction.Large to quickly find the second highest value.
9. The following code line produces the exact same result:
MsgBox "Second Highest Value is " & WorksheetFunction.Large(Range("A1:A11"), 2)
Note: use the value 3 to find the third highest value, the value 4 to find the fourth highest value, etc.
Sum by Color
Below we will look at a program in Excel VBA that sums numbers by color.
Situation:
You have lent money to two twelve people.
Some people have given it back (in black) and some still owe you money (red).
You want to know how much money you still receive.
1. First, we declare two variables of type Integer.
One named toReceive and one named i.
We initialize the variable toReceive with value 0.
Dim toReceive As Integer, i As
Integer
toReceive = 0
2. Second, we start a For Next loop.
For i = 1 To 12
3. We now check each number and only if the color of the number is red we add the number to toReceive.
If Cells(i, 1).Font.Color = vbRed Then
toReceive = toReceive + Cells(i, 1).ValueEnd If
4. Don't forget to close the loop.Next i
5. Finally, we display the money still to receive.
We use the & operator to concatenate (join) two strings.
Although toReceive is not a string it works here.
MsgBox "Still to receive " & toReceive & " dollars"
6. Place your macro in a command button and test it.
Result:
Delete Blank Cells
Below we will look at a program in Excel VBA that deletes blank cells.
Situation:
1. First, we declare two variables of type Integer.
One named counter and one named i.
We initialize the variable counter with value 0.
Dim counter As Integer, i As Integer
counter = 0
2. Next, we check for each cell whether it is empty or not (<> means not equal to).
We are using a loop for this.
If not empty, we write the value to column B.
The counter holds track of the number of cells that have been copied to column B.
Each time we copy a value to column B, we increment counter by 1. This piece of the program looks as follows:
For i = 1 To 10
If Cells(i, 1).Value <> "" Then
Cells(counter + 1, 2).Value = Cells(i, 1).Value
counter = counter + 1
End IfNext i
Result so far:
3. Finally, we empty Range("A1:A10"), copy the values of column B to column A, and empty Range("B1:B10").
Range("A1:A10").Value = ""
Range("A1:A10").Value = Range("B1:B10").Value
Range("B1:B10") = ""
Result:
Loop through Defined Range
Below we will look at a program that loops through a defined range.
For example, when we want to square the numbers in Range("A1:A3").Did you know you can also loop through a dynamic range?
Situation:
Place a command button on your worksheet and add the following code lines:
1. First, we declare two Range objects.
We call the Range objects rng and cell.
Dim rng As Range, cell As Range
2. We initialize the Range object rng with Range("A1:A3").
Set rng = Range("A1:A3")
3. Add the For Each Next loop.
For Each cell In rngNext cell
Note: rng and cell are randomly chosen here, you can use any names.
Remember to refer to these names in the rest of your code.
4. Next, we square each cell in this range.
To achieve this, add the following code line to the loop:
cell.Value = cell.Value * cell.Value
Result when you click the command button on the sheet:
5. If you want to check each cell in a randomly selected range, simply replace:
Set rng = Range("A1:A3")
with:
Set rng = Selection
6. Now, for example select Range("A1:A2").
Result when you click the command button on the sheet:
Loop through Entire Column
Below we will look at a program in Excel VBA that loops through the entire first column and colors all values that are lower than a certain value.
Place a command button on your worksheet and add the following code lines:
1. First, declare a variable called i of type Long.
We use a variable of type Long here because Long variables have larger capacity than Integer variables.
Dim i As Long
2. Next, add the code line which changes the font color of all the cells in column A to black.
Columns(1).Font.Color = vbBlack
3. Add the loop.
For i = 1 To Rows.CountNext i
Note: worksheets can have up to 1,048,576 rows in Excel 2007 or later.
No matter what version you are using, the code line above loops through all rows.
4. Next, we color all values that are lower than the value entered into cell D2. Empty cells are ignored.
Add the following code lines to the loop.
If Cells(i, 1).Value < Range("D2").Value And Not IsEmpty(Cells(i, 1).Value) Then
Cells(i, 1).Font.Color = vbRedEnd If
Result when you click the command button on the sheet (this may take a while):
Do Until Loop
Although not used very often on this site, you might find yourself in a situation where you want to use the Do Until Loop in Excel VBA.
Code placed between Do Until and Loop will be repeated until the part after Do Until is true.
Place a command button on your worksheet and add the following code lines:
Dim i As Integer
i = 1
Do Until i > 6
Cells(i, 1).Value = 20
i = i + 1Loop
Result when you click the command button on the sheet:
Explanation: until i is higher than 6, Excel VBA places the value 20 into the cell at the intersection of row i and column 1 and increments i by 1. As a result, the value 20 will be placed into column A six times (not seven because Excel VBA stops when i equals 7).
Step Keyword
You can use the Step keyword in Excel VBA to specify a different increment for the counter variable of a loop.
1. Place a command button on your worksheet and add the following code lines:
Dim i As Integer
For i = 1 To 6 Step 2
Cells(i, 1).Value = 100Next i
Result when you click the command button on the sheet:
Explanation: The code lines between For and Next will be executed three times.
For i = 1, Excel VBA enters the value 100 into the cell at the intersection of row 1 and column 1. When Excel VBA reaches Next i, it increases i with 2 and jumps back to the For statement.For i = 3, Excel VBA enters the value 100 into the cell at the intersection of row 3 and column 1, etc.
2. Place a command button on your worksheet and add the following code lines:
Dim j As Integer
For j = 8 To 3 Step -1
Cells(6, j).Value = 50Next j
Result when you click the command button on the sheet:
Explanation: The code lines between For and Next will be executed six times.
For j = 8, Excel VBA enters the value 50 into the cell at the intersection of row 6 and column 8. When Excel VBA reaches Next j, it decreases j with 1 and jumps back to the For statement.For j = 7, Excel VBA enters the value 50 into the cell at the intersection of row 6 and column 7, etc.Create a Pattern
Below we will look at a program in Excel VBA that creates a pattern.
Situation:
Place a command button on your worksheet and add the following code lines:
1. First, we declare two variables of type Integer.
One named i and one named j.
Dim i As Integer, j As Integer
2. Second, we add two For Next loops.
For i = 1 To 5 Step 2
For j = 1 To 5 Step 2
3. Next, we add the line which changes the background color of the cells to light gray.
Cells(i, j).Interior.ColorIndex = 15
Note: instead of ColorIndex number 15 (light gray), you can use any ColorIndex number.
4. Close the two For Next loops.
Next jNext i
5. Test the program.
Result so far.
For example, for i = 1 and j = 1, Excel VBA colors Cells(1,1), for i = 1 and j = 3 (Step 2), Excel VBA colors Cells(1,3), for i = 1 and j = 5, Excel VBA colors Cells(1,5), for i = 3 (Step 2) and j = 1, Excel VBA colors Cells(3,1), etc.
6. We are almost there.
The only thing we need to do, is color the cells which are offset by 1 row below and 1 column to the right of the cells already colored.
Add the following code line to the loop.
Cells(i, j).Offset(1, 1).Interior.ColorIndex = 15
7. Test the program.
Result:
Sort Numbers
Below we will look at a program in Excel VBA that sorts numbers.
Situation:
Place a command button on your worksheet and add the following code lines:
1. First, we declare three variables of type Integer and one Range object.
Dim i As Integer, j As Integer, temp As Integer, rng As Range
2. We initialize the Range object rng with the numbers in column A.
We use the CurrentRegion property for this.
CurrentRegion is useful when we don't know the exact boundaries of a range in advance (we want this program to work for 9 numbers but also for 90 numbers).
Set rng = Range("A1").CurrentRegion
3. We start two For Next loops.
For i = 1 To rng.Count
For j = i + 1 To rng.CountExplanation: rng.Count equals 9, so the first two code lines reduce to For i = 1 to 9 and For j = i + 1 to 9. For i = 1, j = 2, 3, ...
, 8 and 9 are checked.
4. To sort the numbers properly, we compare the first number with the next number.
If the next number is smaller, we swap the numbers.
Add the following If Then statement.
If rng.Cells(j) < rng.Cells(i) Then
End If
If the above statement is true, we swap the numbers.
For example: for i = 1 and j = 2, the numbers 2 and 10 are being compared.The above statement is not true.
Thus, no need to swap the numbers.
Excel VBA increments j by 1 and repeats the code lines for i = 1 and j = 3. You can easily see that 5 is larger than 2, so still no need to swap the numbers.
We get the same result for j = 4, j = 5 and j = 6. When we arrive at j = 7, the above statement is true since 1 is smaller than 2.
5. We swap the numbers.
We temporarily store one number to temp, so that Excel VBA can swap the numbers properly.
Add the following code lines in the If statement.
'swap numbers
temp = rng.Cells(i)
rng.Cells(i) = rng.Cells(j)
rng.Cells(j) = temp
6. We close the second For Next loop (Outside the If statement).Next j
For i = 1 and j = 7, Excel VBA swapped the numbers.That means we get 1 at the first position and 2 at position 7. Now that we have 1 at the first position, we will compare this value with 5 (for j = 8) and 4 (for j = 9).
There is no need to swap the numbers (1 is the smallest number).
This way Excel VBA gets (for i = 1) the smallest number at the first position.
To get the second smallest number at the second position, Excel VBA repeats the exact same steps for i = 2. To get the third smallest number at the third position, Excel VBA repeats the exact same steps for i = 3, etc.
7. Close the first For Next loop (Outside the If statement).Next i
8. Test your program.
Result:
Note: this program is a great exercise.
Understanding loops in Excel VBA is essential if you want to write more complicated programs in the future! Having said that, you can also use the Sort method in Excel VBA to quickly sort numbers.
9. The following code line produces the exact same result:
Range("A1:A9").Sort Key1:=Range("A1"), Order1:=xlAscending, Header:=xlNo
Note: use xlDescending to sort in descending order.
Use Header:=xlYes if your data has headers.
10. Bonus.
Use extra keys to sort on multiple columns.
Example code line:
Range("A1:B9").Sort Key1:=Range("A1"), Order1:=xlAscending, Key2:=Range("B1"), Order2:=xlDescending, Header:=xlYes
Randomly Sort Data
Below we will look at a program in Excel VBA that randomly sorts data (in this example randomly sorts names).
Situation:
1. First, we declare four variables.
One variable of type String we call TempString, one variable of type Integer we call TempInteger, one variable of type Integer we call i, and one variable of type Integer we call j.
Dim tempString As String, tempInteger As Integer, i As Integer, j As Integer
2. We write 5 random numbers to column B (one for each name).
We use the worksheet function RandBetween for this.
For i = 1 To 5
Cells(i, 2).Value = WorksheetFunction.RandBetween(0, 1000)Next i
Result so far:
We will use the numbers next to each name to sort the names.
The name with the lowest number first, the name with the second lowest number, second, etc.
3. We start a Double Loop.
For i = 1 To 5
For j = i + 1 To 5
4. Add the following code line:
If Cells(j, 2).Value < Cells(i, 2).Value Then
Example: for i = 1 and j = 2, Wendy and Richard are compared.
Because Richard has a lower number, we swap Wendy and Richard.
Richard is at the first position now.
For i = 1 and j = 3, Richard and Joost are compared.Joost has a higher number so nothing happens.
This way, Excel VBA gets the name with the lowest number at the first position.
For i = 2, Excel VBA gets the name with the second lowest number at the second position, etc.
5. If true, we swap the names.
tempString = Cells(i, 1).Value
Cells(i, 1).Value = Cells(j, 1).Value
Cells(j, 1).Value = tempString
6. And we swap the numbers.
tempInteger = Cells(i, 2).Value
Cells(i, 2).Value = Cells(j, 2).Value
Cells(j, 2).Value = tempInteger
7. Don't forget to close the If statement.End If
8. Don't forget to close the two loops.
Next jNext i
9. Test the program.
Result:
Note: you can add a line which deletes the numbers in column B.
It's even nicer to place the numbers of each name in an array, so no numbers are placed on your worksheet.
However, for illustrative purpose we've chosen to place the values on the sheet.
Remove Duplicates
Below we will look at a program in Excel VBA that removes duplicates.
Situation:
In column A we have 10 numbers.
We want to remove the duplicates from these numbers and place the unique numbers in column B.
1. First, we declare four variables.
toAdd of type Boolean, uniqueNumbers of type Integer, i of type Integer, and j of type Integer.
Dim toAdd As Boolean, uniqueNumbers As Integer, i As Integer, j As Integer
2. Next, we write the first number of column A to column B since the first number is always 'unique'.
Cells(1, 2).Value = Cells(1, 1).Value
3. We initialize two variables.
We've just added one number to column B, so we initialize uniqueNumbers with the value 1. We set toAdd to True assuming that the next number needs to be added as well (this is not necessarily true of course).
uniqueNumbers = 1
toAdd = True
We need to determine whether the second number is 'unique' or not.
This can be done in a very easy way.
Only if the number is not already in column B, the second number needs to be added to column B.
4. We also need to check this for the third number, fourth number, and so on.
We start a For Next loop for this.
For i = 2 To 10
5. Now comes the most important part of the program.
If the second number is equal to one of the numbers in column B (so far we only have one unique number), we set toAdd to False because in this case we don't want to add this number! (it is not 'unique').
At the moment uniqueNumbers is still equal to 1, but uniqueNumbers can be a whole list.
To check this whole list, we need another For Next loop.
Again: if the number we want to add is equal to one of the numbers in this list, toAdd will be set to False and the number will not be added.
Add the following code lines:
For j = 1 To uniqueNumbers
If Cells(i, 1).Value = Cells(j, 2).Value Then
toAdd = False
End IfNext j
6. Only if toAdd is still True and not set to False, Excel VBA needs to add the number to column B.
At the same time, we increment uniqueNumbers by 1 because we have one unique number more now.
The following code lines get the job done:
If toAdd = True Then
Cells(uniqueNumbers + 1, 2).Value = Cells(i, 1).Value
uniqueNumbers = uniqueNumbers + 1End If
7. Finally, we set toAdd to True assuming the next number (third number) needs to be added.
Again this is not necessarily true.
toAdd = True
8. Don't forget to close the loop.Next i
9. Place your macro in a command button and test it.
Result:
Complex Calculations
The kth term, Tk, of a certain mathematical series is defined by the following formula:
The first term, T1, of the series is obtained by substituting k = 1 into the formula i.e.
T1 |
= |
12 + 6 + 1 |
= |
1 |
and |
9 + 7 |
2 |
T2 |
= |
22 + 12 + 1 |
= |
17 |
...
and so on |
18 + 7 |
25 |
Below we will look at a program in Excel VBA that calculates any term Tk and summation of terms up to N.
Explanation: the user has the option to enter "All" or "Odd", to respectively calculate the sum of the first N terms of the series or the sum of only the odd terms up to N.
Place a command button on your worksheet and add the following code lines:
1. First, we declare four variables of type Integer and one variable of type String.
Dim i As Integer, term As Integer, N As Integer, stepSize As Integer
Dim sumType As String
2. Second, we initialize the variables.
i = 0
N = Range("C2").Value
sumType = Range("C3").Value
3. Empty the fields.
Range("A8:B1000").Value = ""
Range("C6").Value = ""
4. Determine stepSize.
Select Case sumType
Case Is = "All"
stepSize = 1
Case Is = "Odd"
stepSize = 2
Case Else
MsgBox "Enter a valid expression in cell C3"
End
End Select
Tip: go through our Select Case program to learn more about the Select Case structure.
5. Do the calculations.
For term = 1 To N Step stepSize
Cells(8 + i, 1).Value = term
Cells(8 + i, 2).Value = (term ^ 2 + (6 * term) + 1) / ((9 * term) + 7)
Range("C6").Value = Range("C6").Value + Cells(8 + i, 2).Value
i = i + 1Next term
Explanation: we use the Step keyword to specify the increment (1 for "All" and 2 for "Odd") for the counter variable of the loop.
Result:
Knapsack Problem
Below we will look at a program in Excel VBA that solves a small instance of a knapsack problem.
Definition: Given a set of items, each with a weight and a value, determine the items to include in a collection so that the total value is as large as possible and the total weight is less than a given limit.
It derives its name from the problem faced by someone who is constrained by a fixed-size knapsack and must fill it with the most useful items.
Example: 5 items with weights, values and limit as given.
In Excel this problem looks as follows:
1. First, we declare five variables of type Double with names limit, weight, value, totalWeight and maximumValue.
Dim limit As Double, weight As Double, value As Double, totalWeight As Double, maximumValue As Double
2. Next, we declare five variables of type Integer with with names i, j, k, l, m.
Dim i As Integer, j As Integer, k As Integer, l As Integer, m As Integer
3. We initialize two variables.
We initialize the variable limit with the value of cell D6. We initialize the variable maximumValue with value 0.
limit = Range("D6").value
maximumValue = 0
4. Next, we check each possible solution.
We can either include an item (1) or leave it out (0).
We start 5 For Next loops.
One for each item.
For i = 0 To 1
For j = 0 To 1
For k = 0 To 1
For l = 0 To 1
For m = 0 To 1
5. We calculate the weight and the value of a possible solution.
weight = 12 * i + 2 * j + 1 * k + 1 * l + 4 * m
value = 4 * i + 2 * j + 2 * k + 1 * l + 10 * m
6. Only if value is higher than maximumValue and weight is lower than limit, we've found a new better solution.
If value > maximumValue And weight <= limit Then
7. If true, we write the new solution to row 4, weight to totalWeight and value to maximumValue.
Range("B4").value = i
Range("C4").value = j
Range("D4").value = k
Range("E4").value = l
Range("F4").value = m
totalWeight = weight
maximumValue = value
8. Don't forget to close the If statement.End If
9. Don't forget to close the 5 For Next loops.Next m
Next l
Next k
Next jNext i
Excel VBA checks each possible solution this way and as a result the optimal solution will appear in row 4. Remember, 1 means we include an item, 0 means we leave it out.
10. Finally, write totalWeight and maximumValue of the optimal solution to respectively cell B6 and B8.
Range("B6").value = totalWeight
Range("B8").value = maximumValue
11. Test the program.
Result:
Conclusion: it's optimal to include the last four items with a maximum value of 15. This solution with a total weight of 2 + 1 + 1 + 4 = 8 does not exceed the limit of 15.
Note: by making the weights and values variable you can solve any knapsack problem of this size (see downloadable Excel file).
Debugging
Single Step | Breakpoint
This example teaches you how to debug code in Excel VBA.
Single Step
By pressing F8, you can single step through your code.
The is very useful because it allows you to see the effect of each code line on your worksheet.
Place a command button on your worksheet and add the following code lines:
Dim i As Integer, j As Integer
For i = 1 To 2
For j = 1 To 5
Cells(i, j).Value = WorksheetFunction.RandBetween(20, 100)
Next jNext i
Result when you click the command button on the sheet:
1. Empty the range A1:E2.
2. Open the Visual Basic Editor and reduce the size of the screen so that you can see the Visual Basic Editor and worksheet at the same time.
3. In the Visual Basic Editor, place your cursor before Private and press F8.
The first line turns yellow.
4. Press F8 four times.
For i = 1 and j = 1, Excel VBA enters a random number between 20 and 100 into the cell at the intersection of row 1 and column 1. By holding the cursor steady on a variable, you can see the value of the variable.
5. Press F8 two more times.
For i = 1 and j = 2, Excel VBA enters a random number between 20 and 100 into the cell at the intersection of row 1 and column 2.
6. Single step through the rest of the code to see how Excel VBA enters the other numbers.
This is an excellent way to learn how a loop works.
If you wish to stop the program, click the Reset (Stop) button.
Breakpoint
You set a breakpoint to halt execution at a specific code line.
1. Empty the range A1:E2.
2. To set a breakpoint, click on the left margin (in grey) where you want to place the breakpoint.
A red dot appears.
3. Click on the green arrow to execute the macro until the breakpoint.
Result:
Only part of the macro (for i = 1) has been executed.
4. To remove the breakpoint, click on the red dot.
Next, click on the green arrow to continue execution.
If you receive a macro from someone else, remember, debugging is great way to understand the code.
You can easily see the effect of each code line on your worksheet.
Error Handling
Below we will look at two programs in Excel VBA.
One program simply ignores errors.
The other program continues execution at a specified line upon hitting an error.
Situation:
Both programs calculate the square root of numbers.
Square Root 1
Add the following code lines to the 'Square Root 1' command button.
1. First, we declare two Range objects.
We call the Range objects rng and cell.
Dim rng As Range, cell As Range
2. We initialize the Range object rng with the selected range.
Set rng = Selection
3. We want to calculate the square root of each cell in a randomly selected range (this range can be of any size).
In Excel VBA, you can use the For Each Next loop for this.
Add the following code lines:
For Each cell In rngNext cell
Note: rng and cell are randomly chosen here, you can use any names.
Remember to refer to these names in the rest of your code.
4. Add the following code line to the loop.
On Error Resume Next
5. Next, we calculate the square root of a value.
In Excel VBA, we can use the Sqr function for this.
Add the following code line to the loop.
cell.Value = Sqr(cell.Value)
6. Exit the Visual Basic Editor and test the program.
Result:
Conclusion: Excel VBA has ignored cells containing invalid values such as negative numbers and text.
Without using the 'On Error Resume Next' statement you would get two errors.
Be careful to only use the 'On Error Resume Next' statement when you are sure ignoring errors is OK.
Square Root 2
Add the following code lines to the 'Square Root 2' command button.
1. The same program as Square Root 1 but replace 'On Error Resume Next' with:
On Error GoTo InvalidValue:
Note: InvalidValue is randomly chosen here, you can use any name.
Remember to refer to this name in the rest of your code.
2. Outside the For Each Next loop, first add the following code line:
Exit Sub
Without this line, the rest of the code (error code) will be executed, even if there is no error!
3. Excel VBA continues execution at the line starting with 'InvalidValue:' upon hitting an error (don't forget the colon).
Add the following code line:
InvalidValue:
4. We keep our error code simple for now.
We display a MsgBox with some text and the address of the cell where the error occurred.
MsgBox "can't calculate square root at cell " & cell.Address
5. Add the following line to instruct Excel VBA to resume execution after executing the error code.
Resume Next
6. Exit the Visual Basic Editor and test the program.
Result:
Err Object
If you are not familiar with Error Handling yet, we highly recommend you to read this example first.
When an error in Excel VBA occurs, the properties of the Err object are filled with information.
Situation:
The program below calculates the square root of numbers.
1. Place a command button on your worksheet and add the following code lines:
Dim rng As Range, cell As Range
Set rng = Selection
For Each cell In rng
On Error GoTo InvalidValue:
cell.Value = Sqr(cell.Value)Next cell
Exit Sub
InvalidValue:
MsgBox Err.Number & " " & Err.Description & " at cell " & cell.Address
Resume Next
Result when you select Range("B2:B6") and click the command button on the sheet:
Explanation: when an error occurs, the number property of the Err object is filled with an unique error number of the current error and the Description property is filled with the error description of the current error.
2. These descriptions may not be very helpful to the users of your program.
You can make the error messages more user friendly by modifying the last part of the macro as follows:
InvalidValue:
Select Case Err.Number
Case Is = 5
MsgBox "Can't calculate square root of negative number at cell " & cell.Address
Case Is = 13
MsgBox "Can't calculate square root of text at cell " & cell.Address
End Select
Resume Next
Tip: go through our Select Case program to learn more about the Select Case structure.
Result:
Interrupt a Macro
You can interrupt a macro in Excel at any time by pressing Esc or Ctrl + Break.
Place a command button on your worksheet and add the following code lines:
Dim x As Long
x = 5
Do While x > 2
x = x + 1Loop
1. Click the command button on the sheet.
This macro never stops because the part after 'Do While' will always be true (x will always be higher than 2).
2. To halt this infinite loop, press Esc or Ctrl + Break.
The following dialog box will appear:
3. Click End to end the macro, click Debug to take a look at the macro in the Visual Basic Editor.
4. Add the following code line at the start of your code if you don't want users of your program to be able to interrupt your macro (not recommended).
Application.EnableCancelKey = xlDisabled
5. Although Excel VBA resets the EnableCancelKey property automatically to xlInterrupt at the end of your macro, it's good practice (when using the previous code line) to end your macro with the following code line:
Application.EnableCancelKey = xlInterrupt
Note: if Excel freezes and you cannot interrupt your macro anymore, press Ctrl + Alt + Delete and close Excel.
Subscript Out of Range
Workbooks | Worksheets | Array
The 'subscript out of range' error in Excel VBA occurs when you refer to a nonexistent collection member or a nonexistent array element.
Place a command button on your worksheet and add the code lines below.
To execute the code lines, click the command button on the sheet.
Workbooks
The Workbooks collection in Excel VBA contains all the Workbook objects that are currently open.
1. The code line below closes sales.xlsm.
Workbooks("sales.xlsm").Close
Result when there's no open workbook with this name:
Note: to fix this 'subscript out of range' error (run-time error 9), open sales.xlsm before clicking the command button.
Worksheets
The Worksheets collection in Excel VBA contains all the Worksheet objects in a workbook.
Our workbook has 3 worksheets.
1. The code line below tries to place the word Hello into cell A1 on the 4th worksheet.
Worksheets(4).Range("A1").Value = "Hello"
Result when you click the command button on the sheet:
Explanation: the 'subscript out of range' error pops up because there's no 4th worksheet.
To fix this error, change the 4 to a 1, 2 or 3 (or insert a new worksheet by clicking the plus sign).
Array
An array is a group of variables.
In Excel VBA, you can refer to a specific variable (element) of an array by using the array name and the index number.
1. The first code line below declares a String array with name Films.
The array consists of five elements.
2. Next, we initialize each element of the array.
3. The final code line tries to display the 6th element using a MsgBox.
Dim Films(1 To 5) As String
Films(1) = "Lord of the Rings"
Films(2) = "Speed"
Films(3) = "Star Wars"
Films(4) = "The Godfather"
Films(5) = "Pulp Fiction"
MsgBox Films(6)
Result when you click the command button on the sheet:
Explanation: the 'subscript out of range' error pops up because there's no 6th element.
To fix this error, change the 6 to a 1, 2, 3, 4 or 5 (or declare a String array with 6 elements).
Macro Comments
A macro comment is a piece of text in a macro which will not be executed by Excel VBA.
It is only there to provide you information about the macro.
To insert a comment, execute the following steps.
1. Open the Visual Basic Editor.
2. To let Excel VBA know that you want to insert a comment, precede the text with an apostrophe.
Note: Excel VBA colors the line green to indicate that it's a comment.
Comments become more useful as program size increases.
You can also convert multiple code lines to comments temporarily.
Sometimes this is easier than deleting and rewriting them.
3. First, display the Edit toolbar.
Click View, Toolbars, Edit.
4. Select the code lines.
5. Click the Comment Block button.
Note: To remove the apostrophes, select the code lines and click the Uncomment Block button next to the Comment Block button.
Separate Strings
Below we will look at a program in Excel VBA that separates strings.
Situation:
Place a command button on your worksheet and add the following code lines:
1. First, we declare a variable called fullname of type String, a variable called commaposition of type Integer, and a variable called i of type Integer.
Dim fullname As String, commaposition As Integer, i As Integer
The problem we are dealing with is that we need to tell Excel VBA where we want to separate the string.
In case of Smith, Mike the comma is at position 6 while in case of Williams, Janet the comma is at position 9.
2. We use a loop to execute the operations on each name entered in Excel.
First, we initialize the variable fullname.
Next, we use the Instr function to find the position of the comma.
For i = 2 To 7
fullname = Cells(i, 1).Value
commaposition = InStr(fullname, ",")
3. Finally, we want to write the part after the comma to column B and the part in front of the comma to column C.
You can achieve this by adding the lines:
Cells(i, 2).Value = Mid(fullname, commaposition + 2)
Cells(i, 3).Value = Left(fullname, commaposition - 1)
Mid(fullname, commaposition + 2) means we want the part of fullname starting at character 'commaposition + 2' (this is exactly the first name).
Left(fullname, commaposition - 1) means we want the part of fullname starting at the beginning until character 'commaposition- 1' (this is exactly the last name).
4. Don't forget to close the loop.Next i
5. Add six names separated by a comma and space to Range("A2:A7").
6. Test the program.
Result:
Reverse Strings
Below we will look at a program in Excel VBA that can reverse strings.
Situation:
Place a command button on your worksheet and add the following code lines:
1. First, we declare four variables.
One variable called text of type String, one variable called reversedText also of type String, one variable called length of type Integer, and one variable called i of type Integer.
Dim text As String, reversedText As String, length As Integer, i As Integer
2. We initialize two variables.
We use the InputBox function to get a text string from the user.
We use the Len function in Excel VBA to get the length of a string.
text = InputBox("Enter the text you want to reverse")
length = Len(text)
3. We start a For Next loop.
For i = 0 To length - 1
4. Now comes the simple trick.
We take the last character from text and place it at the front of ReversedText.
We can use the Mid function in Excel VBA to extract a character from a string.
We use the & operator to concatenate (join) two strings.
reversedText = reversedText & Mid(text, (length - i), 1)
5. Don't forget to close the loop.Next i
Example: text = "Car".
The length of text is 3. For i = 0 to 2, we extract the substring of text starting at position length - i with length 1. Thus, for i = 0, Mid(text, 3, 1) equals r.
We place r at the first position of reversedText.
For i = 1, Mid(text, 2, 1) equals a.We add a to reversedText which becomes ra.
For i = 2, Mid(text, 1, 1) equals C.We add C to reversedText which becomes raC.
6. Finally, we display reversedText using a MsgBox.
msgbox reversedText
7. Test the program.
Result:
Convert to Proper Case
Below we will look at a program in Excel VBA that converts text to proper case.
That is, the first letter in each word in uppercase, and all other letters in lowercase.
Situation:
1. First, we declare two Range objects.
We call the Range objects rng and cell.
Dim rng As Range, cell As Range
2. We initialize the Range object rng with the selected range.
Set rng = Selection
3. We want to check each cell in a randomly selected range (this range can be of any size).
In Excel VBA, you can use the For Each Next loop for this.
Add the following code lines:
For Each cell In rngNext cell
Note: rng and cell are randomly chosen here, you can use any names.
Remember to refer to these names in the rest of your code.
4. To ignore a cell that contains a formula, add the following code line between For Each and Next (only if cell.HasFormula is false we continue).
If Not cell.HasFormula Then
End If
5. Next, we want to convert each word in this range to 'proper case'.
You can use the worksheet function Proper for this task.
Add the following code line in your if statement.
cell.Value = WorksheetFunction.Proper(cell.Value)
6. Test the program.
Result:
Instr
Simple Instr Function | Start Position | Zero | Instr and If | Case-insensitive Search
Use Instr in Excel VBA to find the position of a substring in a string.
The Instr function is quite versatile.
Place a command button on your worksheet and add the code lines below.
To execute the code lines, click the command button on the sheet.
Simple Instr Function
By default, the Instr function starts searching at the beginning of the string (position 1).
Code:
Dim state As String
state = "Virginia"
MsgBox InStr(state, "gin")
Result:
Note: string "gin" found at position 4.
Start Position
The second Instr function below starts searching at position 7.
Code:
Dim state As String
state = "South Carolina"
MsgBox InStr(state, "o")
MsgBox InStr(7, state, "o")
Result:
Explanation: the first Instr function finds the string "o" at position 2. The second Instr function starts searching at position 7 and finds the string "o" at position 10.
Zero
The Instr function returns 0 if the string is not found (important as we will see next).
Code:
Dim state As String
state = "Florida"
MsgBox InStr(state, "us")
Result:
Conclusion: string "us" not found.
Instr and If
Let's create a simple VBA program that uses the Instr function.
Code:
Dim state As String, substring As String
state = Range("A2").Value
substring = Range("B2").Value
If InStr(state, substring) > 0 Then
Range("C2").Value = "Found"
Else
Range("C2").Value = "Not Found"End If
Result when you click the command button on the sheet:
Explanation: string "outh" found at position 2. The Instr function returns 2. As a result, Excel VBA places the string "Found" into cell C2.
Case-insensitive Search
By default, the Instr function performs a case-sensitive search.
Enter the string "dakota" into cell B2 and click the command button on the sheet.
Explanation: string "dakota" not found (first letter not capitalized).
The Instr function returns 0. As a result, Excel VBA places the string "Not Found" into cell C2.
To perform a case-insensitive search, update the code as follows:
Dim state As String, substring As String
state = Range("A2").Value
substring = Range("B2").Value
If InStr(1, state, substring, vbTextCompare) > 0 Then
Range("C2").Value = "Found"
Else
Range("C2").Value = "Not Found"End If
Result when you click the command button on the sheet:
Explanation: the Instr function shown above has 4 arguments.
To perform a case-insensitive search, always specify a start position (first argument) and use vbTextCompare (fourth argument).
Count Words
Below we will look at a program in Excel VBA that counts the number of words in a selected range.
One or more spaces are assumed to separate words.
Situation:
1. First, we declare two Range objects and three variables.
We call the Range objects rng and cell.
One Integer variable we call cellWords, one Integer variable we call totalWords, and one String variable we call content.
Dim rng As Range, cell As Range
Dim cellWords As Integer, totalWords As Integer, content As String
2. We initialize the Range object rng with the selected range and the two variables of type Integer with value 0.
Set rng = Selection
cellWords = 0
totalWords = 0
3. We want to check each cell in a randomly selected range (this range can be of any size).
In Excel VBA, you can use the For Each Next loop for this.
Add the following code lines:
For Each cell In rngNext cell
Note: rng and cell are randomly chosen here, you can use any names.
Remember to refer to these names in the rest of your code.
4. Next, we determine for each cell in this range how many words it contains.
To ignore a cell that contains a formula, add the following code line between For Each and Next (only if cell.HasFormula is false we continue).
If Not cell.HasFormula Then
End If
5. First, we write the content of the cell to the variable content.
Next, we remove the spaces at the beginning and the end (if there are any).
In Excel VBA, you can use the Trim function for this.
For example, " excel vba" will be converted to "excel vba".Add the following code lines in your If statement.
content = cell.Value
content = Trim(content)
Note: the trim function in Excel VBA does not remove extra spaces between words, but that's OK in this example.
6. At this point, a cell can still be empty.
If the cell is empty, we assign the value 0 to the variable cellWords.
If not, it contains at least one word and we assign the value 1 to the variable cellWords.
Add the following code lines in your If statement.
If content = "" Then
cellWords = 0
Else
cellWords = 1End If
A cell can contain more than one word of course.
That's exactly what we want to find out now.
As an example we take: "excel vba".
If a cell contains at least one space at this stage, it contains at least one more word.
You can use the Instr function in Excel VBA to look for a space.
Instr(content, " ") finds the position of the first space in content.
7. We will make use of the Do While Loop structure.
Code placed between these words (at step 8, 9 and 10) will be repeated as long as the part after Do While is true.
We want to repeat these steps as long as Instr(content, " ") > 0 is true (as long as content contains a space and thus more words).
Add the Do While Loop in your If statement.
Do While InStr(content, " ") > 0
Loop
8. Next, we take the part of content starting at the position of the first space.
We use the Mid function for this.
content = Mid(content, InStr(content, " "))
For example: Mid("excel vba", InStr("excel vba", " ")) will give " vba".
9. We trim the string again.
content = Trim(content)
Result: "vba"
10. We increment cellWords by 1.
cellWords = cellWords + 1
This Do While Loop will be repeated as long as content contains a space and thus more words.
In our example, we exit the Do While Loop since "vba" does not contain a space anymore! Result: this cell contains 2 words.
11. After having checked one cell, we add cellWords to the variable totalWords.
This code line should be placed outside the Do While Loop but in the If statement.
totalWords = totalWords + cellWords
The whole process starts again for the next cell until all cells have been checked.
12. Finally, we display the value of totalWords using a msgbox.
This code line should be placed outside the For Each Next loop.
MsgBox totalWords & " words found in the selected range."
13. Test the program.
Result:
Compare Dates and Times
This example teaches you how to compare dates and times in Excel VBA.
Dates and times are stored as numbers in Excel and count the number of days since January 0, 1900. What you see depends on the number format.
1. Enter some numbers in column A.
2. These numbers are dates.
This is a perfect way to enter some dates without worrying about the Date format.
Change the format to Date (Right click on the column A header, Format Cells and choose Date).
Result:
Note: Dates are in US Format.
Months first, Days Second.
This type of format depends on your windows regional settings.
Place a command button on your worksheet and add the following code lines:
3. Declare the variable i of type Integer.
Dim i As Integer
4. Add a For Next loop.
For i = 1 To 5Next i
5. The Date function returns the current date without the time.
Add the following code line to the loop, to highlight all the cells containing the current date (3/13/2020).
If Cells(i, 1).Value = Date Then Cells(i, 1).Font.Color = vbRed
Result:
6. Add the following code line to the loop, to highlight all the dates earlier than 04/19/2019.
If Cells(i, 1).Value < DateValue("April 19, 2019") Then Cells(i, 1).Font.Color = vbRed
Result:
7. But what about times, we hear you say.
They are the decimals.
Switch back to General format and change the numbers to decimal numbers.
8. Now change the format to 'Date and Time' format.
Result:
9. If you want to highlight all cells containing the current date, we cannot use the code line at 5 anymore.
Why not? Because the numbers in column A are decimal numbers now.
Comparing it with Date (a whole number) would not give any match.
(It would only give a match with 3/13/2020 at midnight exactly!) The following code line does work:
If Int(Cells(i, 1).Value) = Date Then Cells(i, 1).Font.Color = vbRed
Explanation: we simply use the Int function.
The Int function rounds a number down to the nearest integer.
This way we can get the dates without the times and compare these dates with Date.
Result:
10. Add the following code line to highlight all the cells containing times in the morning.
If (Cells(i, 1).Value - Int(Cells(i, 1).Value)) < 0.5 Then Cells(i, 1).Font.Color = vbRed
Explanation: we only need the decimals so therefore we subtract the integer part.
Noon (halfway through the day) is represented as 0.5. Decimals lower than 0.5 are the times in the morning.
Result:
DateDiff Function
Dates | Times
The DateDiff function in Excel VBA can be used to get the number of days, weeks, months or years between two dates.
You can also use the DateDiff function to calculate the time difference between two times.
Dates
Place a command button on your worksheet and add the following code lines:
Dim firstDate As Date, secondDate As Date, n As Integer
firstDate = DateValue("Jan 19, 2020")
secondDate = DateValue("Feb 25, 2020")
n = DateDiff("d", firstDate, secondDate)
MsgBox n
Explanation: first, we declare two dates.
Next, we initialize the two dates using the DateValue function.
The DateDiff function has three arguments.
Fill in "d" for the first argument to get the number of days between two dates.
Finally, we use a MsgBox to display the number of days between the two dates.
Result when you click the command button on the sheet:
Note: use "ww" to get the number of weeks between two dates.
Use "m" to get the number of months between two dates.
Use "yyyy" to get the number of years between two dates.
Times
Place a command button on your worksheet and add the following code lines:
Dim firstTime As Date, secondTime As Date, x As Integer
firstTime = TimeValue("2:15:00 pm")
secondTime = TimeValue("5:15:00 pm")
x = DateDiff("h", firstTime, secondTime)
MsgBox x
Explanation: first, we declare two times (times are declared as dates).
Next, we initialize the two times using the TimeValue function.
The DateDiff function has three arguments.
Fill in "h" for the first argument to calculate the number of hours between two times.
Finally, we use a MsgBox to display the number of hours between the two times.
Result when you click the command button on the sheet:
Note: use "n" to calculate the number of minutes between two times.
Use "s" to calculate the number of seconds between two times.
Place your cursor on DateDiff in the Visual Basic Editor and click F1 for help on the other interval specifiers.
Weekdays
Below we will look at a program in Excel VBA that calculates the number of weekdays between two dates.
Weekdays are: Monday, Tuesday, Wednesday, Thursday and Friday.
Situation:
Note: Dates are in US Format.
Months first, Days Second.
This type of format depends on your windows regional settings.
1. First, we declare five variables.
date1 of type Date, date2 of type Date, dateToCheck of type Date, daysBetween of type Integer, weekdays of type Integer and i of type Integer.
Dim date1 As Date, date2 As
Date, dateToCheck As Date
Dim daysBetween As Integer, weekdays As Integer, i As Integer
2. We initialize four variables.
We use the DateDiff function to initialize the variable daysBetween.
This function has three arguments.
We fill in "d" for the first argument since we want the number of days between date1 and date2.
weekdays = 0
date1 = Range("B2")
date2 = Range("B3")
daysBetween = DateDiff("d", date1, date2)
3. We need to check for each date between date1 and date2 (including date1 and date2) whether the date is a weekday or not.
If yes, we increment weekdays by 1. We will use a For Next loop.
For i = 0 To daysBetween
4. We use the DateAdd function to get each date we need to check.
This function has three arguments.
We fill in "d" for the first argument since we want to add days, i for the second argument, and date1 for the third argument since we want to add i days to date1. This way Excel VBA can check each date between date1 and date2 starting with date1. Add the following code line:
dateToCheck = DateAdd("d", i, date1)
Example: for i = 3, Excel VBA checks date1 + 3 days.
5. Next, we use the Weekday function (build in function) to check whether dateToCheck is a weekday or not.
The Weekday function returns 1 for a Sunday and 7 for a Saturday.
Therefore, we only increment the variable weekdays if Weekday(dateToCheck) is not equal to 1 and not equal to 7 (<> means not equal to).
The following code lines get the job done.
If (Weekday(dateToCheck) <> 1 And Weekday(dateToCheck) <> 7) Then
weekdays = weekdays + 1End If
6. Don't forget to close the loop.Next i
7. Finally, we display the number of weekdays using a MsgBox.
We use the & operator to concatenate (join) two strings.
Although weekdays is not a string it works here.
MsgBox weekdays & " weekdays between these two dates"
8. Place your macro in a command button and test it.
Result:
Delay a Macro
To execute a sub in Excel VBA after a specific time, use onTime, Now and the TimeValue function.
First, place a sub into a module.
1. Open the Visual Basic Editor and click Insert, Module.
2. Add the following sub with name reminder:
Sub reminder()
MsgBox "Don't forget your meeting at 14.30"
End Sub
We want Excel VBA to execute this sub 5 seconds after a command button is clicked.
2. Place a command button on your worksheet and add the following code line:
Application.OnTime Now() + TimeValue("00:00:05"), "reminder"
3. Click the command button on the worksheet.
Result 5 seconds later:
4. If you want to execute this sub at a specific time, simply use the following code line:
Application.OnTime TimeValue("14:00:00 am"), "reminder"
5. Click the command button on the worksheet and wait until 14:00 AM to see your sub being executed.
Note: you will probably not use Excel VBA to remind yourself of an important meeting, but if you do want, it's best to put a macro like this in a Workbook Open Event.
By doing this, you will automatically receive a reminder at 14:00 AM (you don't have to click a command button to activate the macro).
Of course, you will only receive the reminder when you leave your workbook open.
Year Occurrences
Below we will look at a program in Excel VBA that counts the number of year occurrences.
Situation:
Note: Dates are in US Format.
Months first, Days second.
This type of format depends on your windows regional settings.
1. First, we declare three variables of type Integer.
One variable we call yearCount, one variable we call yearAsk, and one variable we call i.
Dim yearCount As Integer, yearAsk As Integer, i As Integer
2. We initialize yearCount with the value 0 and yearAsk with the value of cell C4.
yearCount = 0
yearAsk = Range("C4").Value
3. We start a For Next loop.
For i = 1 To 16
4. We now check each date and only if the year of the date equals the entered year in cell C4, we increment yearCount by 1. We use the Year function to get the year of a date.
If Year(Cells(i, 1).Value) = yearAsk Then
yearCount = yearCount + 1End If
5. Don't forget to close the loop.Next i
6. Finally, we display the total year occurrences.
We use the & operator to concatenate (join) two strings.
MsgBox yearCount & " occurrences in year " & yearAsk
7. Place your macro in a command button and test it.
Result:
Note: because we made yearAsk variable, you can simply count the number of year occurrences of another year by entering another year in cell C4, and clicking on the command button again.
Tasks on Schedule
Below we will look at a program in Excel VBA that sets the background color of tasks that are on schedule to green, and sets the background color of tasks that are behind schedule to red.
Situation:
On Sheet1 we have three tasks (X, Y, Z).
A "1" indicates that a task has been completed.
A task is on schedule if a "1" exist in every column up to and including today's date.
Today it's 6-Jun.
Tasks X and Y are on schedule.
Task Z is behind schedule (no "1" in cell E8).
Create a Worksheet Change Event.
Code added to the Worksheet Change Event will be executed by Excel VBA when you change a cell on a worksheet.
1. Open the Visual Basic Editor.
2. Double click on Sheet1 (Sheet1) in the Project Explorer.
3. Choose Worksheet from the left drop-down list.
Choose Change from the right drop-down list.
Add the following code lines to the Worksheet Change Event:
4. Declare two variables of type Integer.
Dim i As Integer, j As Integer
5. Add a Do While Loop.
Do While Cells(6 + i, 1).Value <> ""
i = i + 1Loop
Explanation: For i = 0, Excel VBA checks task X, for i = 1, task Y, etc.
Excel VBA leaves the Do While loop when Cells(6 + i, 1).Value is empty (no more tasks to check).
Add the following code lines (at 6, 7 and 8) to the Do While Loop.
6. Initialize the variable j with value 0.
j = 0
7. Set the background color of a task to green assuming that a task is on schedule (this is not necessarily true of course).
Cells(6 + i, 1).Interior.ColorIndex = 4
8. Add another Do While Loop.
Do While Cells(4, 2 + j).Value <= Date
If Cells(6 + i, 2 + j).Value = 0 Then Cells(6 + i, 1).Interior.ColorIndex = 3
j = j + 1Loop
Note: the Date function returns today's date.
Explanation: For i = 0, j = 0, Excel VBA checks cell B6. For i = 0, j = 1, Excel VBA checks cell C6, etc.
A task is on schedule if a "1" exists in every column up to and including today's date.
If Excel VBA finds a "0", it sets the background color of the task to red.
9. Test the program.
For example, indicate that task Z on 6-Jun has been completed.As a result, task Z will automatically turn green.
Sort Birthdays
Below we will look at a program in Excel VBA that sorts birthdays by months first and days second (so we ignore years).
We want the birthday with the lowest month number at the first position.
If there are birthdays with equal month numbers, we want the birthday with the lowest day number first.
Are you ready?
Situation:
Note: Dates are in US Format.
Months first, Days second.
This type of format depends on your windows regional settings.
1. First, we declare eight variables.
One Date variable we call tempDate, one String variable we call tempName.
The other six variables are Integer variables with names monthToCheck, dayToCheck, monthNext, dayNext, i and j.
Dim tempDate As Date, tempName As String
Dim monthToCheck As Integer, dayToCheck As Integer, monthNext As Integer, dayNext As Integer, i As Integer, j As Integer
2. We start two For Next loops.
For i = 2 To 13
For j = i + 1 To 13Example: for i = 2, j = 3, 4, ...
, 12 and 13 are checked.
3. We initialize four Integer variables.
We use the Month function to get the month of a date and the Day function to get the day of a date.
monthToCheck = month(Cells(i, 2).Value)
dayToCheck = day(Cells(i, 2).Value)
monthNext = month(Cells(j, 2).Value)
dayNext = day(Cells(j, 2).Value)
For example: at the start, for i = 2; the date of Bregje, and j = i + 1 = 2 + 1 = 3; the date of Niels will be chosen.
4. To sort the dates properly, we compare the first date (monthToCheck and dayToCheck) with the next date (monthNext and dayNext).
If the next date is 'lower', we swap the dates and names.
Add the following If Then statement.
If (monthNext < monthToCheck) Or (monthNext = monthToCheck And dayNext < dayToCheck) Then
End If
If the above statement is true, we swap the dates and names.
For example: for i = 2 and j = 3, the date of Bregje and Niels are checked.MonthNext = 6, monthToCheck = 2. The above statement is not true since monthNext is higher than monthToCheck.
Excel VBA increments j by 1 and repeats the code lines for i = 2 and j = 4. You can easily see that Joost (j = 4) has a higher month number than Bregje, so we go to the next one.
We get the same result for j = 5 and j = 6. When we arrive at j = 7, we have the following variables: monthNext = 2 and dayNext = 9. MonthToCheck = 2 and dayToCheck = 12. Now the above statement is true since monthNext = monthToCheck and dayNext (9) is lower than dayToCheck (12).
5. We swap the dates.
We temporarily store one date to tempDate, so that Excel VBA can swap the dates properly.
Add the following code lines in the If statement.
'swap dates
tempDate = Cells(i, 2).Value
Cells(i, 2).Value = Cells(j, 2).Value
Cells(j, 2).Value = tempDate
6. We do the same with the names.
Add the following code lines in the If statement.
'swap names
tempName = Cells(i, 1).Value
Cells(i, 1).Value = Cells(j, 1).Value
Cells(j, 1).Value = tempName
7. We close the second For Next loop (Outside the If statement).Next j
For i = 2 and j = 7, Excel VBA swapped the dates and names.That means we get Richard at the first position and Bregje at position 7. That also means we get a new monthToCheck and dayToCheck at the start of our next iteration (for i = 2 and j = 8).
We will now compare Richard with Dineke (j = 8).
You can easily see that there is no need to replace those dates and names because Richard has a 'lower' date.
As a matter of fact, there is no need to replace Richard (i = 2) with Jan (j = 9), Wendy (j = 10), Jeroen (j = 11), John ( j= 12) and Debby (j = 13).
That is because Richard has the 'lowest' date.
This way Excel VBA will get (for i = 2) the 'lowest' date at the first position.
To get the second 'lowest' date at the second position, Excel VBA repeats the exact same steps for i = 3. To get the third 'lowest' date at the third position, Excel VBA repeats the exact same steps for i = 4, etc.
8. Close the first For Next loop (Outside the If statement).Next i
9. Test your program.
Result:
BeforeDoubleClick Event
Code added to the Worksheet BeforeDoubleClick Event will be executed by Excel VBA when you double click a cell on a worksheet.
1. Open the Visual Basic Editor.
2. Double click on a sheet (for example Sheet1) in the Project Explorer.
3. Choose Worksheet from the left drop-down list.
Choose BeforeDoubleClick from the right drop-down list.
Note: the '_' symbol is used to continue the statement on a new line (in order to show you the complete code).
Add the following code lines to the Worksheet BeforeDoubleClick Event:
4. The code line below colors the active cell red.
Target.Font.Color = vbRed
5. Set the Cancel argument to true if you don't want the default double click action (cell edit mode) to occur.
Cancel = True
6. Test the program by double clicking a cell on Sheet1.
Result:
Highlight Active Cell
Below we will look at a program in Excel VBA that highlights the row and column of the Active Cell (selected cell).
This program will amaze and impress your boss.
Situation:
Each time we change the Active Cell on Sheet1, a macro needs to be executed.
You can achieve this by creating a Worksheet SelectionChange Event.
1. Open the Visual Basic Editor.
2. Double click on Sheet1 (Sheet1) in the Project Explorer.
3. Choose Worksheet from the left drop-down list.
Choose SelectionChange from the right drop-down list.
Add the following code lines to the Worksheet SelectionChange Event:
4. We declare four variables of type Integer.
One named rowNumberValue, one named columnNumberValue, one named i and one named j.
Dim rowNumberValue As Integer, columnNumberValue As Integer, i As Integer, j As Integer
5. First, we add the line which changes the background color of all cells to 'No Fill'.
Cells.Interior.ColorIndex = 0
6. We initialize the variable rowNumberValue with the row number of the Active Cell and the variable columnNumberValue with the column number of the Active Cell.
rowNumberValue = ActiveCell.row
columnNumberValue = ActiveCell.column
7. We highlight the column blue.
That is: all the cells with row number smaller or equal to rowNumberValue and column number equal to columnNumberValue
For i = 1 To rowNumberValue
Cells(i, columnNumberValue).Interior.ColorIndex = 37Next i
Explanation: for this example (see picture above), rowNumberValue equals 12 and columnNumberValue equals 8. The code lines between For and Next will be executed twelve times.
For i = 1, Excel VBA colors the cell at the intersection of row 1 and column 8. For i = 2, Excel VBA colors the cell at the intersection of row 2 and column 8, etc.Note: instead of ColorIndex number 37 (blue), you can use any ColorIndex number.
8. In a similar way, we highlight the row blue.
That is: all the cells with row number equal to rowNumberValue and column number smaller or equal to columnNumberValue.
For j = 1 To columnNumberValue
Cells(rowNumberValue, j).Interior.ColorIndex = 37Next j
9. Now it's time to test the program.
Download the Excel file and see how the row and column of the Active Cell are highlighted each time you change the Active Cell.
Create a Footer Before Printing
Below we will look at a program in Excel VBA that creates a footer before printing a workbook.
Create a Workbook BeforePrint Event.
Code added to the Workbook BeforePrint Event will be executed by Excel VBA before you print a workbook.
1. Open the Visual Basic Editor.
2. Double click on This Workbook in the Project Explorer.
3. Choose Workbook from the left drop-down list.
Choose BeforePrint from the right drop-down list.
4. To create a footer, add the following code line to the Workbook BeforePrint Event:
ActiveSheet.PageSetup.LeftFooter = ActiveWorkbook.FullName
Note: The PageSetup object contains all page setup attributes (left footer, bottom margin, paper size, left margin, and so on) as properties.
5. Test the program by printing your workbook.
Result:
Bills and Coins
Below we will look at a program in Excel VBA that splits an amount of money into bills and coins.
Situation:
Create a Worksheet Change Event.
Code added to the Worksheet Change Event will be executed by Excel VBA when you change a cell on a worksheet.
1. Open the Visual Basic Editor.
2. Double click on Sheet1 (Sheet1) in the Project Explorer.
3. Choose Worksheet from the left drop-down list.
Choose Change from the right drop-down list.
Add the following code lines to the Worksheet Change Event:
4. Declare a variable called amount of type Double and a variable i of type Integer.
Dim amount As Double, i As Integer
5. The Worksheet Change Event listens to all changes on Sheet1. We only want Excel VBA to do something if something changes in cell B2. To achieve this, add the following code line:
If Target.Address = "$B$2" Then
6. We initialize the variable amount with the value of cell B2.
amount = Range("B2").Value
7. We empty the range with the frequencies.
Range("B5:B16").Value = ""
8. Now it's time to split the entered amount of money.
We start a For Next loop.
For i = 5 To 16
9. We will make use of the Do While Loop structure.
Code placed between these words will be repeated as long as the part after Do While is true.
We want Excel VBA to repeat the code lines at step 10 as long as amount is larger or equal to Cells(i,1).value.
Do While amount >= Cells(i, 1).Value
Loop
10. Add the following code lines to the Do While Loop.
Cells(i, 2).Value = Cells(i, 2).Value + 1
amount = amount - Cells(i, 1).Value
Explanation: as long as amount is larger or equal to Cells(i,1).value, the amount contains bills/coins of this value.
As a result, Excel VBA increments the frequency of this bill/coin (first line) and subtracts the value of the bill/coin from amount (second line).
This process will be repeated until amount becomes smaller than Cells(i,1).value.
Next, Excel VBA increments i and goes to the next bill/coin to see how many times this bill/coin fits in the amount left.
This way the amount of money will be split into bills and coins until there is no money left to split anymore.
11. Close the For Next loop and don't forget to close the if statement (both outside the Do While Loop).
Next iEnd if
12. Test the program.
Result:
Note: of course the entered amount does not necessarily contains every bill/coin.
If amount does not contain a certain bill/coin, the part after Do While never becomes true for this bill/coin and Excel VBA goes directly to the next bill/coin.
Rolling Average Table
Below we will look at a program in Excel VBA that creates a rolling average table.
Place a command button on your worksheet and add the the following code line:
Range("B3").Value = WorksheetFunction.RandBetween(0, 100)
This code line enters a random number between 0 and 100 into cell B3. We want Excel VBA to take the new stock value and place it at the first position of the rolling average table.
All other values should move down one place and the last value should be deleted.
Create a Worksheet Change Event.
Code added to the Worksheet Change Event will be executed by Excel VBA when you change a cell on a worksheet.
1. Open the Visual Basic Editor.
2. Double click on Sheet1 (Sheet1) in the Project Explorer.
3. Choose Worksheet from the left drop-down list.
Choose Change from the right drop-down list.
Add the following code lines to the Worksheet Change Event:
4. Declare a variable called newvalue of type Integer and two ranges (firstfourvalues and lastfourvalues).
Dim newvalue As Integer, firstfourvalues As Range, lastfourvalues As Range
5. The Worksheet Change Event listens to all changes on Sheet1. We only want Excel VBA to do something if something changes in cell B3. To achieve this, add the following code line:
If Target.Address = "$B$3" Then
6. We initialize newvalue with the value of cell B3, firstfourvalues with Range("D3:D6") and lastfourvalues with Range("D4:D7").
newvalue = Range("B3").Value
Set firstfourvalues = Range("D3:D6")
Set lastfourvalues = Range("D4:D7")
7. Now comes the simple trick.
We want to update the rolling average table.
You can achieve this by replacing the last four values with the first four values of the table and placing the new stock value at the first position.
lastfourvalues.Value = firstfourvalues.Value
Range("D3").Value = newvalue
8. Don't forget to close the if statement.End if
9. Finally, enter the formula =AVERAGE(D3:D7) into cell D8.
10. Test the program by clicking on the command button.
Dynamic Array
If the size of your array increases and you don't want to fix the size of the array, you can use the ReDim keyword.
Excel VBA then changes the size of the array automatically.
Add some numbers to column A.
Place a command button on your worksheet and add the following code lines:
1. First, we declare the array named numbers.
Also declare two variables of type Integer.
One named size and one named i.
Dim numbers() As Integer, size As Integer, i As Integer
Note: the array has no size yet.
numbers, size and i are randomly chosen here, you can use any names.
Remember to refer to these names in the rest of your code.
2. Next, we determine the size of the array and store it into the variable size.
You can use the worksheet function CountA for this.
Add the following code line:
size = WorksheetFunction.CountA(Worksheets(1).Columns(1))
3. We now know the size of the array and we can redimension it.
Add the following code line:
ReDim numbers(size)
4. Next, we initialize each element of the array.
We use a loop.
For i = 1 To size
numbers(i) = Cells(i, 1).ValueNext i
5. We display the last element of the array using a MsgBox.
MsgBox numbers(size)
6. Exit the Visual Basic Editor and click the command button on the sheet.
Result:
7. Now to clearly see why this is called a dynamic array, add a number to column A.
8. Click the command button again.
Conclusion: Excel VBA has automatically changed the size of this dynamic array.
9. When you use the ReDim keyword, you erase any existing data currently stored in the array.
For example, add the following code lines to the previously created code:ReDim numbers(3)
MsgBox numbers(1)
Result:
The array is empty.
10. When you want to preserve the data in the existing array when you redimension it, use the Preserve keyword.
ReDim Preserve numbers(3)
MsgBox numbers(1)
Result:
Array Function
The Array function in Excel VBA can be used to quickly and easily initialize an array.
Place a command button on your worksheet and add the following code lines:
1. First, create a variable named departments of type Variant.
Dim departments As Variant
2. Use the Array Function to assign an array to the variable departments.
Add the following code line:
departments = Array("Sales", "Production", "Logistics")
3. To show the element with index 1, add the following code line:
MsgBox departments(1)
Result:
By default, the element's index of the array starts from 0.
4. Add Option Base 1 to the General Declarations section if you want the index to start from 1.
Result when you click the command button again.
For a practical example of the Array function, see our example program Month Names.Month Names
Below we will look at a program in Excel VBA which creates a User Defined Function that uses the Array function to return the names of the months.
User defined functions need to be placed into a module.
1. Open the Visual Basic Editor and click Insert, Module.
2. Add the following code line:
Function MONTHNAMES()
The name of our Function is MONTHNAMES.
The empty part between the brackets means we give Excel VBA nothing as input.
3. The Array function allows us to assign values to a Variant array in one line of code.
MONTHNAMES = Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")
4. Don't forget to end the function.
End Function
5. Now you can use this function, just like any other Excel function, to return the names of the months.
Select twelve horizontal cells, enter the function =MONTHNAMES() and press CTRL + SHIFT + ENTER.
Result:
Note: you cannot delete a single month.
To delete the months, select the range A1:L1 and press Delete.
This function is only available in this workbook.
6. If you have Excel 365 or Excel 2021, simply select cell A1, enter the function =MONTHNAMES() and press Enter.
Bye bye curly braces.
Note: the MONTHNAMES function, entered into cell A1, fills multiple cells.
Wow! This behavior in Excel 365/2021 is called spilling.
Size of an Array
To get the size of an array in Excel VBA, you can use the UBound and LBound functions.
Place a command button on your worksheet and add the following code lines:
1. First, we need to declare the array.
Our array has two dimensions.
It consists of 5 rows and 2 columns.
Also declare two variables of type Integer.
Dim Films(1 To 5, 1 To 2) As String, x As Integer, y As Integer
The array may look like this.
2. Next, we get the size of the array.
Add the following code lines:
x = UBound(Films, 1) - LBound(Films, 1) + 1
y = UBound(Films, 2) - LBound(Films, 2) + 1
UBound(Films, 1) gives the upper limit of the first dimension, which is 5.
LBound(Films, 1) gives the lower limit of the first dimension, which is 1.
UBound(Films, 2) gives the upper limit of the second dimension, which is 2.
LBound(Films, 2) gives the lower limit of the second dimension, which is 1.
As a result, x equals 5 and y equals 2.
3. We use a MsgBox to display the number of elements of the array.
MsgBox "This array consists of " & x * y & " elements"
Result:
User Defined Function
Below we will look at a program in Excel VBA that creates a User Defined Function.
Excel has a large collection of functions.
In most situations those functions are sufficient to get the job done.
If not, you can create your own function called User Defined Function or custom Excel function.
You can access a User Defined Function just like any other Excel function.
We want to create a function called SUMEVENNUMBERS that finds the sum of the even numbers of a randomly selected range.
Situation:
User defined functions need to be placed into a module.
1. Open the Visual Basic Editor and click Insert, Module.
2. Add the following code line:
Function SUMEVENNUMBERS(rng As Range)
The name of our Function is SUMEVENNUMBERS.
The part between the brackets means we give Excel VBA a range as input.
We name our range rng, but you can use any name.
3. Next, we declare a Range object and call it cell.
Dim cell As Range
4. We want to check each cell in a randomly selected range (this range can be of any size).
In Excel VBA, you can use the For Each Next loop for this.
Add the following code lines:
For Each cell In rngNext cell
Note: cell is randomly chosen here, you can use any name.
5. Next, we check for each value in this range whether it is even or not.
We use the Mod operator for this.
The Mod operator gives the remainder of a division.
For example, 7 mod 2 = 1 because 7 divided by 2 equals 3 with a remainder of 1. Having said this, it is easy to check whether a number is even or not.Only if the remainder of a number divided by 2 is 0, the number is even.
For example, 8 mod 2 = 0 because 8 divided by 2 equals 4 with a remainder of 0. Add the following If statement to the For Each Next loop.If cell.Value Mod 2 = 0 Then
End If
6. Only if this statement is true, we add the value to SUMEVENNUMBERS.
Add the following code line in the If statement.
SUMEVENNUMBERS = SUMEVENNUMBERS + cell.Value
7. Don't forget to end the function (outside the loop).
End Function
8. Now you can use this function, just like any other Excel function, to find the sum of the even numbers of a randomly selected range.
Result:
Well done! That's how easy User Defined Functions in Excel VBA are.
Note: this function is only available in this workbook.
Custom Average Function
Below we will look at a program in Excel VBA which creates a User Defined Function that calculates the average of a randomly selected range excluding one or more values that are outliers and shouldn't be averaged.
Situation:
User defined functions need to be placed into a module.
1. Open the Visual Basic Editor and click Insert, Module.
2. Add the following code line:
Function CUSTOMAVERAGE(rng As Range, lower As Integer, upper As Integer)
The name of our Function is CUSTOMAVERAGE.
The part between the brackets means we give Excel VBA a range and two Integer variables as input.
We name our range rng, one Integer variable we call lower, and one Integer variable we call upper, but you can use any names.
3. Next, we declare a Range object and two variables of type Integer.
We call the Range object cell.
One Integer variable we call total and one Integer variable we call count.
Dim cell As Range, total As Integer, count As Integer
4. We want to check each cell in a randomly selected range (this range can be of any size).
In Excel VBA, you can use the For Each Next loop for this.
Add the following code lines:
For Each cell In rngNext cell
Note: rng and cell are randomly chosen here, you can use any names.
Remember to refer to these names in the rest of your code.
5. Next, we check for each value in this range if it falls between the two values (lower and upper).
If true, we increment total by the value of the cell and we increment count by 1. Add the following code lines to the loop.
If cell.Value >= lower And cell.Value <= upper Then
total = total + cell.Value
count = count + 1End If
6. To return the result of this function (the desired average), add the following code line outside the loop.
CUSTOMAVERAGE = total / count
7. Don't forget to end the function.
Add the line:
End Function
8. Now you can use this function just like any other Excel function to calculate the average of numbers that fall between two values.
Result:
As a check, you can delete all values that are lower than 10 and higher than 30 and use the standard Average function in Excel to see if Excel calculates the same average as our custom average function.
Our custom average function works! Note: this function is only available in this workbook.
Volatile Functions
By default, UDF's (User Defined Functions) in Excel VBA are not volatile.
They are only recalculated when any of the function's arguments change.
A volatile function will be recalculated whenever calculation occurs in any cells on the worksheet.
Let's take a look at an easy example to explain this a bit more.
1. Open the Visual Basic Editor and click Insert, Module.
Create a function called MYFUNCTION which returns the sum of the selected cell and the cell below this cell.
2. Add the following code lines:
Function MYFUNCTION(cell As Range)
MYFUNCTION = cell.Value + cell.Offset(1, 0).Value
End Function
3. Now you can use this function, just like any other Excel function.
4. This is a non-volatile function.
Non-volatile functions are only recalculated when any of the function's arguments change.
Change the value of cell B2 to 8.
5. Now change the value of cell B3 to 11.
Explanation: the non-volatile function is not recalculated when any other cell on the sheet changes.
6. Update the function as follows to make the function volatile:
Function MYFUNCTION(cell As Range)
Application.Volatile
MYFUNCTION = cell.Value + cell.Offset(1, 0).Value
End Function
7. Change the value of cell B3 to 12.
Result:
Note: you need to enter the function again to make it volatile (or refresh it by placing your cursor in the formula bar and pressing enter).
ByRef and ByVal
You can pass arguments to a procedure (function or sub) by reference or by value.
By default, Excel VBA passes arguments by reference.
As always, we will use an easy example to make things more clear.
Place a command button on your worksheet and add the following code lines:
Dim x As Integer
x = 10
MsgBox Triple(x)
MsgBox x
The code calls the function Triple.
It's the result of the second MsgBox we are interested in.
Functions need to be placed into a module.
1. Open the Visual Basic Editor and click Insert, Module.
2. Add the following code lines:
Function Triple(ByRef x As Integer) As Integer
x = x * 3
Triple = x
End Function
Result when you click the command button on the sheet:
3. Replace ByRef with ByVal.
Function Triple(ByVal x As Integer) As Integer
x = x * 3
Triple = x
End Function
Result when you click the command button on the sheet:
Explanation: When passing arguments by reference we are referencing the original value.
The value of x (the original value) is changed in the function.
As a result the second MsgBox displays a value of 30. When passing arguments by value we are passing a copy to the function.
The original value is not changed.
As a result the second MsgBox displays a value of 10 (the original value).
StatusBar
The StatusBar property of the Application object in Excel VBA can be used to indicate the progress of a lengthy macro.
This way, you can let the user know that a macro is still running.
Situation:
The macro we are going to create fills Range("A1:E20") with random numbers.
Add the following code lines to the command button:
1. First, we declare three variables of type Integer, named i, j and pctCompl.
Dim i As Integer, j As Integer, pctCompl As Integer
2. Add a Double Loop.
For i = 1 To 20
For j = 1 To 5Next jNext i
Add the following code lines (at 3, 4 and 5) to the loop.
3. Use the RandBetween function to import a random number between 20 and 100.
Cells(i, j).Value = WorksheetFunction.RandBetween(20, 100)
4. Initialize the variable pctCompl.
The second code line writes the value of the variable pctCompl and some descriptive text in the status bar.
pctCompl = (i - 1) * 5 + (j * 1)
Application.StatusBar = "Importing Data..
" & pctCompl & "% Completed"
Example: For i = 3, j = 1, (3 - 1) * 5 + (1 * 1) = 11% has been completed.
5. We use the Wait method of the Application object to simulate a lengthy macro.
Application.Wait Now + TimeValue("00:00:01")
6. To restore the default status bar text, set the StatusBar property to False (outside the loop).
Application.StatusBar = False
Result when you click the command button on the sheet:
Note: You can interrupt a macro at any time by pressing Esc or Ctrl + Break.
For a more visual approach, see our Progress Indicator program.Read Data from Text File
Below we will look at a program in Excel VBA that reads data from a text file.
This file contains some geographical coordinates we want to import into Excel.
Situation:
1. First, download the text file and add it to "C:\test\"
Place a command button on your worksheet and add the following code lines:
2. We declare four variables.
myFile of type String, text of type String, textline of type String, posLat of type Integer, and posLong of type Integer.
Dim myFile As String, text As String, textline As String, posLat As Integer, posLong As Integer
3. We need to initialize the variable myFile with the full path and the filename.
myFile = "C:\test\geographical-coordinates.txt"
or
use the GetOpenFilename method of the Application object to display the standard Open dialog box and select the file (without actually opening the file).
myFile = Application.GetOpenFilename()
Note: the empty part between the brackets means we give Excel VBA nothing as input.
Place your cursor on GetOpenFilename in the Visual Basic Editor and click F1 for help on the arguments.
4. Add the following code line:
Open myFile For Input As #1
Note: this statement allows the file to be read.
We can refer to the file as #1 during the rest of our code.
5. Add the following code lines:
Do Until EOF(1)
Line Input #1, textline
text = text & textlineLoop
Note: until the end of the file (EOF), Excel VBA reads a single line from the file and assigns it to textline.
We use the & operator to concatenate (join) all the single lines and store it in the variable text.
6. Close the file.
Close #1
7. Next, we search for the position of the words latitude and longitude in the variable text.
We use the Instr function.
posLat = InStr(text, "latitude")
posLong = InStr(text, "longitude")
8. We use these positions and the Mid function to extract the coordinates from the variable text and write the coordinates to cell A1 and cell A2.
Range("A1").Value = Mid(text, posLat + 10, 5)
Range("A2").Value = Mid(text, posLong + 11, 5)
9. Test the program.
Result:
Write Data to Text File
Below we will look at a program in Excel VBA that writes an Excel range to a CSV (comma-separated-value) text file.
Situation:
Place a command button on your worksheet and add the following code lines:
1. First, we declare a variable called myFile of type String, an object called rng of type Range, a variable called cellValue of type Variant, a variable called i of type Integer, and a variable called j of type Integer.
We use a Variant variable here because a Variant variable can hold any type of value.
Dim myFile As String, rng As Range, cellValue As Variant, i As Integer, j As Integer
2. We need to specify the full path and the filename of the file.
myFile = Application.DefaultFilePath & "\sales.csv"
Note: the DefaultFilePath property returns the default file path.
To change the default file location, on the File tab, click Options, Save.
3. We initialize the range object rng with the selected range.
Set rng = Selection
4. Add the following code line:
Open myFile For Output As #1
Note: this statement allows the file to be written to.
We can refer to the file as #1 during the rest of our code.
If the file already exists, it will be deleted and a new file with the same name will be created.
5. Start a Double Loop.
For i = 1 To rng.Rows.Count
For j = 1 To rng.Columns.CountNote: rng.Rows.Count returns the number of rows (17 in this example) and rng.Columns.Count returns the number of columns (4 in this example).
6. Excel VBA writes the value of a cell to the variable cellValue.
cellValue = rng.Cells(i, j).Value
7. Add the following code lines to write the value of cellValue to the text file.
If j = rng.Columns.Count Then
Write #1, cellValue
Else
Write #1, cellValue,End If
Explanation: due to the If Then Else statement, Excel VBA only starts a new line (Write #1, cellValue) when j equals the number of columns (last value in a row).
To separate the values with a comma, use Write #1, cellValue, (with a comma).
8. Don't forget to close both loops.
Next jNext i
9. Close the file.
Close #1
10. Select the data and click the command button on the sheet.
Result:
Vlookup
Use the WorksheetFunction property in Excel VBA to access the VLOOKUP function.
All you need is a single code line.
Situation:
1. Place a command button on your worksheet and add the following code line:
Range("H3").Value = WorksheetFunction.VLookup(Range("H2"), Range("B3:E9"), 4, False)
When you click the command button on the worksheet, Excel VBA uses the VLOOKUP function to lookup the salary of ID 53 and places the result into cell H3.
Note: visit our page about the VLOOKUP function to learn more about this Excel function.
If the VLOOKUP function cannot find a match, Excel VBA returns the "Unable to get the VLookup property of the WorksheetFunction class" error.
2. For example, enter the value 28 into cell H2.
Result when you click the command button on the sheet:
3. To replace this error with a friendly message, update the code as follows.
On Error GoTo InvalidValue:
Range("H3").Value = WorksheetFunction.VLookup(Range("H2"), Range("B3:E9"), 4, False)
Exit Sub
InvalidValue: Range("H3").Value = "Not Found"
Result when you click the command button on the sheet:
Note: visit our page about error handling to learn more about this topic.
Text Box
A text box is an empty field where a user can fill in a piece of text.
To create a text box in Excel VBA, execute the following steps.
1. On the Developer tab, click Insert.
2. In the ActiveX Controls group, click Text Box.
3. Drag a command button and a text box on your worksheet.
4. Right click the command button (make sure Design Mode is selected).
5. Click View Code.
Note: you can change the caption and name of a control by right clicking on the control (make sure Design Mode is selected) and then clicking on Properties.
Change the caption of the command button to Import Data.
For now, we will leave TextBox1 as the name of the text box.
6. Add the following code line:
TextBox1.Text = "Data imported successfully"
7. Click the command button on the sheet (make sure Design Mode is deselected).
Result:
8. To clear a text box, use the following code line:
TextBox1.Value = ""
Note: although in some situations it can be useful to directly place a text box on your worksheet, a text box is particularly useful when placed on a Userform.
List Box
A list box is a list from where a user can select an item.
To create a list box in Excel VBA, execute the following steps.
1. On the Developer tab, click Insert.
2. In the ActiveX Controls group, click List Box.
3. Drag a list box on your worksheet.
Note: you can change the name of a control by right clicking on the control (make sure Design Mode is selected) and then clicking on Properties.
For now, we will leave ListBox1 as the name of the list box.Create a Workbook Open Event.
Code added to the Workbook Open Event will be executed by Excel VBA when you open the workbook.
4. Open the Visual Basic Editor.
5. Double click on This Workbook in the Project Explorer.
6. Choose Workbook from the left drop-down list and choose Open from the right drop-down list.
7. To add items to the list box, add the following code lines to the Workbook Open Event:
With Sheet1.ListBox1
.AddItem "Paris"
.AddItem "New York"
.AddItem "London"
End With
Note: use Sheet2 if your list box is located on the second worksheet, Sheet3 if your list box is located on the third worksheet, etc.
If you use these code lines outside the Workbook Open event, you might want to add the following code line before these code lines.
This code line clears the list box.
This way your items won't be added multiple times if you execute your code more than once.
ListBox1.Clear
8. To link this list box to a cell, right click on the list box (make sure design mode is selected) and click on Properties.
Fill in D3 for LinkedCell.
Note: also see the ListFillRange property to fill a list box with a range of cells.
9. Save, close and reopen the Excel file.
Result:
Although in some situations it can be useful to directly place a list box on your worksheet, a list box is particularly useful when placed on a Userform.
Combo Box
A combo box is a drop-down list from where a user can select an item or fill in his/her own choice.
To create a combo box in Excel VBA, execute the following steps.
1. On the Developer tab, click Insert.
2. In the ActiveX Controls group, click Combo Box.
3. Drag a combo box on your worksheet.
Note: you can change the name of a control by right clicking on the control (make sure Design Mode is selected) and then clicking on Properties.
For now, we will leave ComboBox1 as the name of the combo box.Create a Workbook Open Event.
Code added to the Workbook Open Event will be executed by Excel VBA when you open the workbook.
4. Open the Visual Basic Editor.
5. Double click on This Workbook in the Project Explorer.
6. Choose Workbook from the left drop-down list and choose Open from the right drop-down list.
7. To add items to the combo box, add the following code lines to the Workbook Open Event:
With Sheet1.ComboBox1
.AddItem "Paris"
.AddItem "New York"
.AddItem "London"
End With
Note: use Sheet2 if your combo box is located on the second worksheet, Sheet3 if your combo box is located on the third worksheet, etc.
If you use these code lines outside the Workbook Open event, you might want to add the code lines below before these code lines.
The first code line clears the combo box.
This way your items won't be added multiple times if you execute your code more than once.
The second code line clears your own choice.
ComboBox1.Clear
ComboBox1.Value = ""
8. To link this combo box to a cell, right click on the combo box (make sure design mode is selected) and click on Properties.
Fill in D2 for LinkedCell.
Note: also see the ListFillRange property to fill a combo box with a range of cells.
9. Save, close and reopen the Excel file.
Result:
Although in some situations it can be useful to directly place a combo box on your worksheet, a combo box is particularly useful when placed on a Userform.
Check Box
A check box is a field which can be checked to store information.
To create a check box in Excel VBA, execute the following steps.
1. On the Developer tab, click Insert.
2. In the ActiveX Controls group, click Check Box.
3. Drag a check box on your worksheet.
4. Right click the check box (make sure Design Mode is selected).
5. Click View Code.
Note: you can change the caption and name of a control by right clicking on the control (make sure Design Mode is selected) and then clicking on Properties.
Change the caption of the check box to MyCheckBox.
For now, we will leave CheckBox1 as the name of the check box.
6. Add the following code lines:
If CheckBox1.Value = True Then Range("D2").Value = 1
If CheckBox1.Value = False Then Range("D2").Value = 0
7. Click the check box on the sheet (make sure Design Mode is deselected).
Result:
Although in some situations it can be useful to directly place a check box on your worksheet, a check box is particularly useful when placed on a Userform.
Option Buttons
If you have more than one option button, only one of the option buttons can be selected.
To create option buttons in Excel VBA, execute the following steps.
1. On the Developer tab, click Insert.
2. In the ActiveX Controls group, click Option Button.
3. Drag two option buttons on your worksheet.
4. Right click the first option button (make sure Design Mode is selected).
5. Click View Code.
Note: you can change the caption and name of a control by right clicking on the control (make sure Design Mode is selected) and then clicking on Properties.
Change the captions of the option buttons to Female and Male.
For now, we will leave OptionButton1 and OptionButton2 as the names of the option buttons.
6. Add the following code line:
If OptionButton1.Value = True Then Range("D3").Value = 10
7. Right click the second option button (make sure Design Mode is selected).
8. Click View Code.
9. Add the following code line:
If OptionButton2.Value = True Then Range("D3").Value = 20
10. Click the option buttons on the sheet (make sure Design Mode is deselected).
Result:
Although in some situations it can be useful to directly place option buttons on your worksheet, option buttons are particularly useful when placed on a Userform.
Spin Button
A spin button can be used to increment a number in a cell.
To create a spin button in Excel VBA, execute the following steps.
1. On the Developer tab, click Insert.
2. In the ActiveX Controls group, click Spin Button.
3. Drag a spin button on your worksheet.
4. Right click the spin button (make sure Design Mode is selected).
5. Click View Code.
Note: you can change the name of a control by right clicking on the control (make sure Design Mode is selected) and then clicking on Properties.
For now, we will leave SpinButton1 as the name of the spin button.
6. To link this spin button to a cell, add the following code line.
Range("C3").Value = SpinButton1.Value
7. You can set a maximum and minimum by adding the following code lines.
SpinButton1.Max = 100
SpinButton1.Min = 0
8. To change the incremental value, use the SmallChange property.
SpinButton1.SmallChange = 2
9. Click the arrows of the spin button (make sure Design Mode is deselected).
Result:
Note: instead of changing the properties of the spin button at runtime, you can also change the properties at design-time.
To achieve this, right click on the spin button (make sure Design Mode is selected) and click on properties.
Loan Calculator
This page teaches you how to create a simple loan calculator in Excel VBA.
The worksheet contains the following ActiveX controls: two scrollbars and two option buttons.
Note: the instructions below do not teach you how to format the worksheet.
We assume that you know how to change font types, insert rows and columns, add borders, change background colors, etc.
Execute the following steps to create the loan calculator:
1. Add the two scrollbar controls.
Click on Insert from the Developer tab and then click on Scroll Bar in the ActiveX Controls section.
2. Add the two option buttons.
Click on Insert from the Developer tab and then click on Option Button in the ActiveX Controls section.
Change the following properties of the scrollbar controls (make sure Design Mode is selected).
3. Right mouse click on the first scrollbar control, and then click on Properties.
Set Min to 0, Max to 20, SmallChange to 0 and LargeChange to 2.
4. Right mouse click on the second scrollbar control, and then click on Properties.
Set Min to 5, Max to 30, SmallChange to 1, LargeChange to 5, and LinkedCell to F8.
Explanation: when you click on the arrow, the scrollbar value goes up or down by SmallChange.
When you click between the slider and the arrow, the scrollbar value goes up or down by LargeChange.
Create a Worksheet Change Event.
Code added to the Worksheet Change Event will be executed by Excel VBA when you change a cell on a worksheet.
5. Open the Visual Basic Editor.
6. Double click on Sheet1 (Sheet1) in the Project Explorer.
7. Choose Worksheet from the left drop-down list and choose Change from the right drop-down list.
8. The Worksheet Change Event listens to all changes on Sheet1. We only want Excel VBA to run the Calculate sub if something changes in cell D4. To achieve this, add the following code line to the Worksheet Change Event (more about the Calculate sub later on).
If Target.Address = "$D$4" Then Application.Run "Calculate"
9. Get the right percentage in cell F6 (change the format of cell F6 to percentage).
Right mouse click on the first scrollbar control, and then click on View Code.
Add the following code lines:
Private Sub ScrollBar1_Change()
Range("F6").Value = ScrollBar1.Value / 100
Application.Run "Calculate"
End Sub
10. Right mouse click on the second scrollbar control, and then click on View Code.
Add the following code line:
Private Sub ScrollBar2_Change()
Application.Run "Calculate"
End Sub
11. Right mouse click on the first option button control, and then click on View Code.
Add the following code line:
Private Sub OptionButton1_Click()
If OptionButton1.Value = True Then Range("C12").Value = "Monthly Payment"
Application.Run "Calculate"
End Sub
12. Right mouse click on the second option button control, and then click on View Code.
Add the following code line:
Private Sub OptionButton2_Click()
If OptionButton2.Value = True Then Range("C12").Value = "Yearly Payment"
Application.Run "Calculate"
End Sub
13. Time to create the sub.
You can go through our Function and Sub chapter to learn more about subs.
If you are in a hurry, simply place the sub named Calculate into a module (In the Visual Basic Editor, click Insert, Module).
Sub Calculate()
Dim loan As Long, rate As Double, nper As Integer
loan = Range("D4").Value
rate = Range("F6").Value
nper = Range("F8").Value
If Sheet1.OptionButton1.Value = True Then
rate = rate / 12
nper = nper * 12End If
Range("D12").Value = -1 * WorksheetFunction.Pmt(rate, nper, loan)
End Sub
Explanation: the sub gets the right parameters for the worksheet function Pmt.
The PMT function in Excel calculates the payments for a loan based on constant payments and a constant interest rate.
If you make monthly payments (Sheet1.OptionButton1.Value = True), Excel VBA uses rate / 12 for rate and nper *12 for nper (total number of payments).
The result is a negative number, because payments are considered a debit.
Multiplying the result by -1 gives a positive result.
Userform and Ranges
You can use a RefEdit control in Excel VBA to get a range from a user.
The Userform we are going to create colors the minimum value of the range stored in the RefEdit control.
To create this Userform, execute the following steps.
1. Open the Visual Basic Editor.
If the Project Explorer is not visible, click View, Project Explorer.
2. Click Insert, Userform.
If the Toolbox does not appear automatically, click View, Toolbox.
Your screen should be set up as below.
3. Add the label, RefEdit control and command buttons.
Once this has been completed, the result should be consistent with the picture of the Userform shown earlier.
For example, create a RefEdit control by clicking on RefEdit from the Toolbox.Next, you can drag a RefEdit control on the Userform.
Note: If your toolbox does not have a RefEdit control, set a reference to RefEdit control.
Click Tools, References, and check Ref Edit Control.
4. You can change the names and the captions of the controls.
Names are used in the Excel VBA code.
Captions are those that appear on your screen.
It is good practice to change the names of the controls, but it is not necessary here because we only have a few controls in this example.
To change the caption of the Userform, label and command buttons, click View, Properties Window and click on each control.
5. To show the Userform, place a command button on your worksheet and add the following code line:
Private Sub CommandButton1_Click()
UserForm1.Show
End Sub
We are now going to create the Sub UserForm_Initialize.
When you use the Show method for the Userform, this sub will automatically be executed.
6. Open the Visual Basic Editor.
7. In the Project Explorer, right click on UserForm1 and then click View Code.
8. Choose Userform from the left drop-down list.
Choose Initialize from the right drop-down list.
9. Add the following code lines:
Private Sub UserForm_Initialize()
Sheet1.Cells.Font.Color = vbBlack
UserForm1.RefEdit1.Text = Selection.Address
End Sub
Explanation: the first code line changes the font color of all the cells on sheet1 to black.
The second code line obtains the address of the current selection and displays it in the RefEdit control.
We have now created the first part of the Userform.
Although it looks neat already, nothing will happen yet when we click the command buttons on the Userform.
10. In the Project Explorer, double click on UserForm1.
11. Double click on the Go button.
12. Add the following code lines:
Private Sub CommandButton1_Click()
Dim addr As String, rng, cell As Range, minimum
As Double
addr = RefEdit1.Value
Set rng = Range(addr)
minimum = WorksheetFunction.Min(rng)
For Each cell In rng
If cell.Value = minimum Then cell.Font.Color = vbRedNext cell
End Sub
Explanation: first, we get the address from the RefEdit control and store it into the String variable addr.
Next, we set rng to the range specified in the RefEdit control.
Next, we use the worksheet function Min to find the minimum value in the range.
Finally, we color the minimum value(s) using a loop.
13. Double click on the Cancel button.
14. Add the following code line:
Private Sub CommandButton2_Click()
Unload Me
End Sub
Explanation: this code line closes the Userform when you click on the Cancel button.
15. Test the Userform.
Result:
Currency Converter
Below we will look at a program in Excel VBA which creates a Userform that converts any amount from one currency into another.
The Userform we are going to create looks as follows:
To create this Userform, execute the following steps.
1. Open the Visual Basic Editor.
If the Project Explorer is not visible, click View, Project Explorer.
2. Click Insert, Userform.
If the Toolbox does not appear automatically, click View, Toolbox.
Your screen should be set up as below.
3. Add the labels, list boxes (first at the left, the second at the right), text boxes (first at the left, the second at the right) and command button.
Once this has been completed, the result should be consistent with the picture of the Userform shown earlier.
For example, create a list box control by clicking on ListBox from the Toolbox.Next, you can drag a list box on the Userform.
4. You can change the names and the captions of the controls.
Names are used in the Excel VBA code.
Captions are those that appear on your screen.
It is good practice to change the names of the controls, but it is not necessary here because we only have a few controls in this example.
To change the caption of the Userform, command button and labels, click View, Properties Window and click on each control.
5. To show the Userform, place a command button on your worksheet and add the following code line:
Private Sub CommandButton1_Click()
UserForm1.Show
End Sub
We are now going to create the Sub UserForm_Initialize.
When you use the Show method for the Userform, this sub will automatically be executed.
6. Open the Visual Basic Editor.
7. In the Project Explorer, right click on UserForm1 and then click View Code.
8. Choose Userform from the left drop-down list.
Choose Initialize from the right drop-down list.
9. Add the following code lines:
Private Sub UserForm_Initialize()
With ListBox1
.AddItem "Euro"
.AddItem "Us Dollar"
.AddItem "British Pound"
End With
With ListBox2
.AddItem "Euro"
.AddItem "Us Dollar"
.AddItem "British Pound"
End With
ListBox1.ListIndex = 1
ListBox2.ListIndex = 0
TextBox1.Value = 1
TextBox2.Value = 0.722152
End Sub
Explanation: first, the two list boxes are filled.
Next, The US Dollar currency is set as default in the first list box and the EURO currencyis set as default in the second list box.
Finally, the value 1 is entered in the first text box and the value 0.722152 is entered in the second text box.
We have now created the first part of the Userform.
Although it looks neat already, nothing will happen yet when we click on the Go button.
10. In the Project Explorer, double click on UserForm1.
11. Double click on the Go button.
12. Add the following code lines:
Private Sub CommandButton1_Click()
Dim rates(0 To 2, 0 To 2) As Double, i As Integer, j As Integer
rates(0, 0) = 1
rates(0, 1) = 1.38475
rates(0, 2) = 0.87452
rates(1, 0) = 0.722152
rates(1, 1) = 1
rates(1, 2) = 0.63161
rates(2, 0) = 1.143484
rates(2, 1) = 1.583255
rates(2, 2) = 1
For i = 0 To 2
For j = 0 To 2
If ListBox1.ListIndex = i And ListBox2.ListIndex = j Then TextBox2.Value = TextBox1.Value * rates(i, j)
Next jNext i
End Sub
Explanation: first, we declare an array.
The array has two dimensions.
It consists of 3 rows and 3 columns.
Next, we initialize each element of the array.
For example, rates(1,0) is the currency rate from US Dollar to EURO.Next, we start a double loop.
Depending on the selected currencies in the list boxes, Excel VBA converts the amount entered in the first text box and displays the result in the second text box.
Example: if i = 2 and j = 1 and we enter the value 2 in the first text box, Excel VBA places the value 2 * rates(2,1) = 2 * 1.583255= 3.16651 in the second text box.
13. Test the Userform.
Result:
Progress Indicator
Below we will look at a program in Excel VBA that creates a progress indicator.
We've kept the progress indicator as simple as possible, yet it looks professional.
Are you ready?
The Userform we are going to create looks as follows:
To create this Userform, execute the following steps.
1. Open the Visual Basic Editor.
If the Project Explorer is not visible, click View, Project Explorer.
2. Click Insert, Userform.
If the Toolbox does not appear automatically, click View, Toolbox.
Your screen should be set up as below.
This Userform only consists of three controls.
A frame control and two label controls.
3. Add the frame control.
You can do this by clicking on Frame from the Toolbox.
Next, you can drag a frame control on the Userform.
You need to change some properties of this frame control.
Right mouse click on the frame control, and then click on Properties.
Empty the Caption field, set the Height to 24 and Width to 204.
4. Add the first label control and place it in the Frame control.
Right mouse click on the label control, and then click on Properties.
Change the name to Bar, BackColor to Highlight, empty the Caption field, set the Height to 20 and Width to 10.
5. Add the second label control and place it above the Frame control.
Right mouse click on the label control, and then click on Properties.
Change the name to Text and change the Caption to '0% Completed'.
6. Change the caption of the Userform to Progress Indicator.
Once this has been completed, the result should be consistent with the picture of the Userform shown earlier.
7. Place a command button on your worksheet and add the following code line to show the Userform:
Private Sub CommandButton1_Click()
UserForm1.Show
End Sub
If you have gone through the other Userform examples on this site, you know that this is the time to create the Sub UserForm_Initialize.
This Sub runs automatically whenever the Userform is loaded.
Thus, when you use the Show method for the Userform, the code will automatically be executed.
Instead of the Sub UserForm_Initialize, we create the Sub UserForm_Activate.
By using this sub, Excel VBA can update the Userform to show the progress of the macro.
8. Open the Visual Basic Editor.
9. In the Project Explorer, right click on UserForm1 and then click View Code.
10. Choose Userform from the left drop-down list.
Choose Activate from the right drop-down list.
11. Add the following code line:
Private Sub UserForm_Activate()
code
End Sub
Explanation: this sub calls another sub named code we are going to create in a minute.
Confused? You can go through our Function and Sub chapter to learn more about subs.
If you are in a hurry, just execute the following steps and you will be fine.
12. Place the sub named code into a module (In the Visual Basic Editor, click Insert, Module).
This is just an example.
This is THE place to add your own code when you want to use this progress indicator for your own macro.
The code looks as follows.
Sub code()
Dim i As Integer, j As Integer, pctCompl As Single
Sheet1.Cells.Clear
For i = 1 To 100
For j = 1 To 1000
Cells(i, 1).Value = j
Next j
pctCompl = i
progress pctComplNext i
End Sub
Explanation: first, we initialize some variables.
Next, we clear sheet1. We use a double loop to show the values from 1 to 1000 in the first 100 rows of the worksheet.
This will keep Excel VBA busy for a while and gives us the opportunity to see the progress of the macro.
The variable pctCompl (abbreviation for percentageCompleted) measures the progress of the macro.
Finally, we call another sub named progress and pass the value of the variable pctCompl to update the Userform.
This way we can see the progress of the macro!
13. Add another sub named progress.
The code looks as follows:
Sub progress(pctCompl As Single)
UserForm1.Text.Caption = pctCompl & "% Completed"
UserForm1.Bar.Width = pctCompl * 2
DoEvents
End Sub
Explanation: the first code line changes the caption of the first label control.
The second code line changes the width of the second label control.
Add DoEvents to update the Userform.
14. Exit the Visual Basic Editor and click the command button on the sheet:
Result:
Note: for this macro, we used the variable i to measure the progress.
For example, at row 11, 10% is completed.This may be different for your macro.
The technique of passing the value of the variable pctCompl to the sub progress to update the Userform remains the same.
Multiple List Box Selections
The MultiSelect property in Excel VBA allows a user to select multiple items in a list box.
The Userform we are going to create looks as follows:
To create this Userform, execute the following steps.
1. Open the Visual Basic Editor.
If the Project Explorer is not visible, click View, Project Explorer.
2. Click Insert, Userform.
If the Toolbox does not appear automatically, click View, Toolbox.
Your screen should be set up as below.
3. Add the list boxes (first at the left, the second at the right), command buttons, check boxes (first at the left, the second at the right), frame and option buttons (first at the top, the second below the first, and so on).
Once this has been completed, the result should be consistent with the picture of the Userform shown earlier.
For example, create a list box control by clicking on ListBox from the Toolbox.Next, you can drag a list box on the Userform.
When you arrive at the 'Select Type' frame, remember to draw this frame first before you place the three option buttons in it.
4. You can change the names and the captions of the controls.
Names are used in the Excel VBA code.
Captions are those that appear on your screen.
It is good practice to change the names of the controls, but it is not necessary here because we only have a few controls in this example.
To change the caption of the Userform, command buttons, check boxes, frame and option buttons, click View, Properties Window and click on each control.
5. To show the Userform, place a command button on your worksheet and add the following code line:
Private Sub CommandButton1_Click()
UserForm1.Show
End Sub
We are now going to create the Sub UserForm_Initialize.
When you use the Show method for the Userform, this sub will automatically be executed.
6. Open the Visual Basic Editor.
7. In the Project Explorer, right click on UserForm1 and then click View Code.
8. First, declare the variable i of type Integer.
Declare the variable in the General Declarations section (at the top of the code).
This way you only have to declare the variable once and you can use them in multiple subs.
Dim i As Integer
9. Choose Userform from the left drop-down list.
Choose Initialize from the right drop-down list.
10. Add the following code lines:
Private Sub UserForm_Initialize()
With ListBox1
.AddItem "Sales"
.AddItem "Production"
.AddItem "Logistics"
.AddItem "Human Resources"
End With
OptionButton3.Value = True
End Sub
Explanation: the first list box will be filled and the third option button is set as default.
We have now created the first part of the Userform.
Although it looks neat already, nothing will happen yet when we click the command buttons or the other controls.
11. In the Project Explorer, double click on UserForm1.
12. Double click on the Add button.
13. Add the following code lines:
Private Sub CommandButton1_Click()
For i = 0 To ListBox1.ListCount - 1
If ListBox1.Selected(i) = True Then ListBox2.AddItem ListBox1.List(i)Next i
End Sub
Explanation: Excel VBA loops through the first list box (list index number of zero (0) for the first item in the list) and, if selected, adds the item to the second list box.
14. Double click on the Remove button.
15. Add the following code lines:
Private Sub CommandButton2_Click()
Dim counter As Integer
counter = 0
For i = 0 To ListBox2.ListCount - 1
If ListBox2.Selected(i - counter) Then
ListBox2.RemoveItem (i - counter)
counter = counter + 1
End IfNext i
CheckBox2.Value = False
End Sub
Explanation: Excel VBA loops through the second list box and, if selected, removes the item.
The counter variable holds track of the number of removed items.
16. Double click on the first option button.
17. Add the following code lines:
Private Sub OptionButton1_Click()
ListBox1.MultiSelect = 0
ListBox2.MultiSelect = 0
End Sub
18. Double click on the second option button.
19. Add the following code lines:
Private Sub OptionButton2_Click()
ListBox1.MultiSelect = 1
ListBox2.MultiSelect = 1
End Sub
20. Double click on the third option button.
21. Add the following code lines:
Private Sub OptionButton3_Click()
ListBox1.MultiSelect = 2
ListBox2.MultiSelect = 2
End Sub
Explanation: the 'Select Type' setting can be chosen by clicking on the option buttons.
The picture of the Userform shown earlier gives a description of each setting.
Instead of configuring this setting at runtime, you can also configure this setting at design time.
To achieve this, right mouse click on a list box control, and then click on Properties.
Set the MultiSelect property to 0 - fmMultiSelectSingle, 1 - fmMultiSelectMulti or 2 - fmMultiSelectExtented.
22. Double click on the first check box.
23. Add the following code lines:
Private Sub CheckBox1_Click()
If CheckBox1.Value = True Then
For i = 0 To ListBox1.ListCount - 1
ListBox1.Selected(i) = True
Next iEnd If
If CheckBox1.Value = False Then
For i = 0 To ListBox1.ListCount - 1
ListBox1.Selected(i) = False
Next iEnd If
End Sub
Explanation: by checking the first check box, all the items of the first list box can be selected / deselected.
24. Double click on the second check box to add the same code lines.
Only replace CheckBox1 with CheckBox2 and ListBox1 with ListBox2.
Multicolumn Combo Box
Below we will look at a program in Excel VBA which creates a Userform that contains a multicolumn combo box.
The Userform we are going to create looks as follows:
To create this Userform, execute the following steps.
1. Open the Visual Basic Editor.
If the Project Explorer is not visible, click View, Project Explorer.
2. Click Insert, Userform.
If the Toolbox does not appear automatically, click View, Toolbox.
Your screen should be set up as below.
3. Add the label, combo box and command buttons.
Once this has been completed, the result should be consistent with the picture of the Userform shown earlier.
For example, create a combo box control by clicking on ComboBox from the Toolbox.Next, you can drag a combo box on the Userform.
4. You can change the names and the captions of the controls.
Names are used in the Excel VBA code.
Captions are those that appear on your screen.
It is good practice to change the names of the controls, but it is not necessary here because we only have a few controls in this example.
To change the caption of the Userform, label and command buttons, click View, Properties Window and click on each control.
5. To show the Userform, place a command button on your worksheet and add the following code line:
Private Sub CommandButton1_Click()
UserForm1.Show
End Sub
We are now going to create the Sub UserForm_Initialize.
When you use the Show method for the Userform, this sub will automatically be executed.
6. Open the Visual Basic Editor.
7. In the Project Explorer, right click on UserForm1 and then click View Code.
8. Choose Userform from the left drop-down list.
Choose Initialize from the right drop-down list.
9. Add the following code lines:
Private Sub UserForm_Initialize()
ComboBox1.ColumnCount = 2
Dim Films(1 To 5, 1 To 2) As String
Dim i As Integer, j As Integer
Films(1, 1) = "Lord of the Rings"
Films(2, 1) = "Speed"
Films(3, 1) = "Star Wars"
Films(4, 1) = "The Godfather"
Films(5, 1) = "Pulp Fiction"
Films(1, 2) = "Adventure"
Films(2, 2) = "Action"
Films(3, 2) = "Sci-Fi"
Films(4, 2) = "Crime"
Films(5, 2) = "Drama"
ComboBox1.List = Films
End Sub
Explanation: The first code line sets the number of columns of the combo box to 2. Instead of setting the number of columns at runtime, you can also configure this setting at design time.
To achieve this, right mouse click on the combo box control, click Properties and set the ColumnCount property to 2. Next, we declare and initialize a two-dimensional array.
The last code line assigns the array to the combo box.
We have now created the first part of the Userform.
Although it looks neat already, nothing will happen yet when we click the command buttons on the Userform.
10. In the Project Explorer, double click on UserForm1.
11. Double click on the OK button.
12. Add the following code lines:
Private Sub CommandButton1_Click()
Unload Me
MsgBox "You selected " & ComboBox1.Value
On Error Resume Next
MsgBox "You like " & ComboBox1.Column(1) & " movies"
End Sub
Note: these code lines close the Excel VBA Userform and display the selected item and genre.
The 'On Error Resume Next' statement ignores the error when the user fills in his/her own movie (in this case there is no genre available).
13. Double click on the Cancel button.
14. Add the following code line:
Private Sub CommandButton2_Click()
Unload Me
End Sub
Result when you select Speed and click OK.
Dependent Combo Boxes
Below we will look at a program in Excel VBA which creates a Userform that contains dependent combo boxes.
The Userform we are going to create looks as follows:
The user selects Animals from a drop-down list.
As a result, the user can select an animal from a second drop-down list.
The user selects Sports from a drop-down list.
As a result, the user can select a sport from a second drop-down list.
To create this Userform, execute the following steps.
1. Open the Visual Basic Editor.
If the Project Explorer is not visible, click View, Project Explorer.
2. Click Insert, Userform.
If the Toolbox does not appear automatically, click View, Toolbox.
Your screen should be set up as below.
3. Add the combo boxes (first at the left, the second at the right) and command button.
Once this has been completed, the result should be consistent with the picture of the Userform shown earlier.
For example, create a combo box control by clicking on ComboBox from the Toolbox.Next, you can drag a combo box on the Userform.
4. You can change the names and the captions of the controls.
Names are used in the Excel VBA code.
Captions are those that appear on your screen.
It is good practice to change the names of the controls, but it is not necessary here because we only have a few controls in this example.
To change the caption of the Userform and command button, click View, Properties Window and click on each control.
5. To show the Userform, place a command button on your worksheet and add the following code line:
Private Sub CommandButton1_Click()
UserForm1.Show
End Sub
We are now going to create the Sub UserForm_Initialize.
When you use the Show method for the Userform, this sub will automatically be executed.
6. Open the Visual Basic Editor.
7. In the Project Explorer, right click on UserForm1 and then click View Code.
8. Choose Userform from the left drop-down list.
Choose Initialize from the right drop-down list.
9. Add the following code lines:
Private Sub UserForm_Initialize()
With ComboBox1
.AddItem "Animals"
.AddItem "Sports"
.AddItem "Food"
End With
End Sub
Explanation: These code lines fill the first combo box.
We have now created the first part of the Userform.
Although it looks neat already, nothing will happen yet when we select an item from the first combo box.
10. In the Project Explorer, double click on UserForm1.
11. Double click on the first combo box.
12. Add the following code lines:
Private Sub ComboBox1_Change()
Dim index As Integer
index = ComboBox1.ListIndex
ComboBox2.Clear
Select Case index
Case Is = 0
With ComboBox2
.AddItem "Dog"
.AddItem "Cat"
.AddItem "Horse"
End With
Case Is = 1
With ComboBox2
.AddItem "Tennis"
.AddItem "Swimming"
.AddItem "Basketball"
End With
Case Is = 2
With ComboBox2
.AddItem "Pancakes"
.AddItem "Pizza"
.AddItem "Chinese"
End With
End Select
End Sub
Explanation: Excel VBA uses the value of the variable index to test each subsequent Case statement to see with which items the second combo box should be filled.
Go through our Select Case program to learn more about the Select Case structure.
13. Double click on the Import button.
14. Add the following code line:
Private Sub CommandButton1_Click()
Range("A1").Value = ComboBox2.Value
End Sub
Result:
Loop through Controls
With just a few lines of code, we can easily loop through controls on an Excel VBA Userform.
The Userform we are going to create looks as follows:
To create this Userform, execute the following steps.
1. Open the Visual Basic Editor.
If the Project Explorer is not visible, click View, Project Explorer.
2. Click Insert, Userform.
If the Toolbox does not appear automatically, click View, Toolbox.
Your screen should be set up as below.
3. Add the label, check boxes (first at the top, the second below the first, and so on) and command button.
Once this has been completed, the result should be consistent with the picture of the Userform shown earlier.
For example, create a check box control by clicking on CheckBox from the Toolbox.Next, you can drag a check box on the Userform.
4. You can change the names and the captions of the controls.
Names are used in the Excel VBA code.
Captions are those that appear on your screen.
It is good practice to change the names of the controls, but it is not necessary here because we only have a few controls in this example.
To change the caption of the Userform, label, check boxes and command button, click View, Properties Window and click on each control.
5. To show the Userform, place a command button on your worksheet and add the following code line:
Private Sub CommandButton1_Click()
UserForm1.Show
End Sub
We have now created the first part of the Userform.
Although it looks neat already, nothing will happen yet when we click on the Clear button.
6. Open the Visual Basic Editor.
7. In the Project Explorer, double click on UserForm1.
8. Double click on the Clear button.
9. Add the following code lines:
Private Sub CommandButton1_Click()
Dim contr As control
For Each contr In UserForm1.Controls
If TypeName(contr) = "CheckBox" Then
contr.Value = False
End If
Next
End Sub
Explanation: Excel VBA loops through all controls on the Userform.
The TypeName function is used to filter out the check box controls.
If a check box control, Excel VBA unchecks the check box.
contr is randomly chosen here, you can use any name.
Remember to refer to this name in the rest of your code.
Result when you click the Clear button:
Controls Collection
When creating Userforms in Excel VBA, you can use the Controls collection to easily loop through controls and set a property of each control to a specific value.
The Userform we are going to create looks as follows:
To create this Userform, execute the following steps:
1. Open the Visual Basic Editor.
If the Project Explorer is not visible, click View, Project Explorer.
2. Click Insert, Userform.
If the Toolbox does not appear automatically, click View, Toolbox.
Your screen should be set up as below.
3. Add the label, text boxes (first at the top, the second below the first, and so on) and command button.
Once this has been completed, the result should be consistent with the picture of the Userform shown earlier.
For example, create a text box control by clicking on TextBox from the Toolbox.Next, you can drag a text box on the Userform.
4. To change the caption of the Userform, label and command button, click View, Properties Window and click on each control.
5. To show the Userform, place a command button on your worksheet and add the following code line:
Private Sub CommandButton1_Click()
UserForm1.Show vbModeless
End Sub
Explanation: by adding vbModeless, you can use the Userform and work in your worksheet at the same time.
We have now created the first part of the Userform.
Although it looks neat already, nothing will happen yet when we click the command button on the Userform.
6. Open the Visual Basic Editor.
7. In the Project Explorer, double click on UserForm1.
8. Double click on the command button.
9. Add the following code lines:
Private Sub CommandButton1_Click()
Dim i As Integer
For i = 1 To 10
Controls("TextBox" & i).Value = Cells(i + 1, 1).ValueNext i
End Sub
Explanation: With just a few lines of code, we can fill the text boxes with the phone numbers from the sheet.
We used the & operator to concatenate (join) the elements.
These code lines work because we didn't change the names of the text box controls (TextBox1, TextBox2, TextBox3, etc).
To change the names of the controls, click View, Properties Window and click on each control.
Result when you click the command button on the sheet:
Userform with Multiple Pages
Below we will look at a program in Excel VBA which creates a Userform that contains multiple pages.
This userform also contains images.
The Multipage Control contains two pages.
At page 1, the user can fill in his/her personal information.
At page 2, the user can indicate which painting he/she likes the most.
To create this Userform, execute the following steps.
1. Open the Visual Basic Editor.
If the Project Explorer is not visible, click View, Project Explorer.
2. Click Insert, Userform.
If the Toolbox does not appear automatically, click View, Toolbox.
Your screen should be set up as below.
3. Add the Multipage control, labels, text boxes (first at the top, the second below the first), frame, option buttons (first at the left, the second at the right), list box, Image control and command button.
Once this has been completed, the result should be consistent with the empty version of the Userform shown earlier.
For example, create a Multipage control by clicking on Multipage from the Toolbox.Next, you can drag a Multipage control on the Userform.
When you arrive at the Gender frame, remember to draw this frame first before you place the two option buttons in it.
4. You can change the names and the captions of the controls.
Names are used in the Excel VBA code.
Captions are those that appear on your screen.
It is good practice to change the names of the controls, but it is not necessary here because we only have a few controls in this example.
To change the caption of the Userform, Multipage tabs, labels, frame, option buttons and command button, click View, Properties Window and click on each control.
5. To show the Userform, place a command button on your worksheet and add the following code line:
Private Sub CommandButton1_Click()
UserForm1.Show
End Sub
We are now going to create the Sub UserForm_Initialize.
When you use the Show method for the Userform, this sub will automatically be executed.
6. Open the Visual Basic Editor.
7. In the Project Explorer, right click on UserForm1 and then click View Code.
8. Choose Userform from the left drop-down list.
Choose Initialize from the right drop-down list.
9. Add the following code lines:
Private Sub UserForm_Initialize()
With ListBox1
.AddItem "Mountains"
.AddItem "Sunset"
.AddItem "Beach"
.AddItem "Winter"
End With
End Sub
Explanation: the list box on page 2 will be filled.
We have now created the first part of the Userform.
Although it looks neat already, nothing will happen yet when we select an item from the list box or when we click on the OK button.
10. Download the images (right side of this page) and add them to "C:\test\"
11. In the Project Explorer, double click on UserForm1.
12. Double click on the list box.
13. Add the following code lines:
Private Sub ListBox1_Click()
If ListBox1.ListIndex = 0 Then
Image1.Picture = LoadPicture("C:\test\Mountains.jpg")End If
If ListBox1.ListIndex = 1 Then
Image1.Picture = LoadPicture("C:\test\Sunset.jpg")End If
If ListBox1.ListIndex = 2 Then
Image1.Picture = LoadPicture("C:\test\Beach.jpg")End If
If ListBox1.ListIndex = 3 Then
Image1.Picture = LoadPicture("C:\test\Winter.jpg")End If
End Sub
Explanation: these code lines load a picture depending on the selected item in the list box.
14. Double click on the OK button.
15. Add the following code lines:
Private Sub CommandButton1_Click()
Dim emptyRow As Long
'Make Sheet1 active
Sheet1.Activate
'Determine emptyRow
emptyRow = WorksheetFunction.CountA(Range("A:A")) + 1
'Transfer information
Cells(emptyRow, 1).Value = TextBox1.Value
Cells(emptyRow, 2).Value = TextBox2.Value
If OptionButton1.Value = True Then
Cells(emptyRow, 3).Value = "Male"
Else
Cells(emptyRow, 3).Value = "Female"End If
Cells(emptyRow, 4).Value = ListBox1.Value
'Close Userform
Unload Me
End Sub
Explanation: first, we activate Sheet1. Next, we determine emptyRow.
The variable emptyRow is the first empty row and increases every time a record is added.
Next, we transfer the information from the Userform to the specific columns of emptyRow.
Finally, we close the Userform.
16. Exit the Visual Basic Editor, enter the labels shown below into row 1 and test the Userform.
Result:
Interactive Userform
Below we will look at a program in Excel VBA that creates an interactive Userform.
The Userform we are going to create looks as follows:
Explanation: whenever you enter a value in the ID text box, Excel VBA loads the corresponding record.
When you click the Edit / Add button, Excel VBA edits the record on the sheet or adds the record when the ID does not yet exist.
The Clear button clears all the text boxes.
The Close button closes the Userform.
To create this Userform, execute the following steps.
1. Open the Visual Basic Editor.
If the Project Explorer is not visible, click View, Project Explorer.
2. Click Insert, Userform.
If the Toolbox does not appear automatically, click View, Toolbox.
Your screen should be set up as below.
3. Add the labels, text boxes (first at the top, the second below the first, and so on) and command buttons.
Once this has been completed, the result should be consistent with the picture of the Userform shown earlier.
For example, create a text box control by clicking on TextBox from the Toolbox.Next, you can drag a text box on the Userform.
4. You can change the names and the captions of the controls.
Names are used in the Excel VBA code.
Captions are those that appear on your screen.
It is good practice to change the names of the controls, but it is not necessary here because we only have a few controls in this example.
To change the caption of the labels, text boxes and command buttons, click View, Properties Window and click on each control.
5. To show the Userform, place a command button on your worksheet and add the following code line:
Private Sub CommandButton1_Click()
UserForm1.Show
End Sub
We are now going to create the Sub UserForm_Initialize.
When you use the Show method for the Userform, this sub will automatically be executed.
6. Open the Visual Basic Editor.
7. In the Project Explorer, right click on UserForm1 and then click View Code.
8. Choose Userform from the left drop-down list.
Choose Initialize from the right drop-down list.
9. Add the following code line:
Private Sub UserForm_Initialize()
TextBox1.SetFocus
End Sub
Explanation: this code line sets the focus on the first text box as this is where we want to start when the Userform is loaded.
We have now created the first part of the Userform.
Although it looks neat already, nothing will happen yet when we enter a value in the ID text box or when we click one of the command buttons.
10. In the Project Explorer, right click on UserForm1 and then click View Code.
11. Choose TextBox1 from the left drop-down list.
Choose Change from the right drop-down list.
12. Add the following code line:
Private Sub TextBox1_Change()
GetData
End Sub
13. In the Project Explorer, double click on UserForm1.
14. Double click on the Edit / Add command button.
15. Add the following code line:
Private Sub CommandButton1_Click()
EditAdd
End Sub
16. Double click on the Clear command button.
17. Add the following code line:
Private Sub CommandButton2_Click()
ClearForm
End Sub
Explanation: these subs call other subs we are going to create in a second.
18. Double click on the Close command button.
19. Add the following code line:
Private Sub CommandButton3_Click()
Unload Me
End Sub
Explanation: this code line closes the Userform.
Time to create the subs.
You can go through our Function and Sub chapter to learn more about subs.
If you are in a hurry, simply place the following subs into a module (In the Visual Basic Editor, click Insert, Module).
20. First, declare three variables of type Integer and one variable of type Boolean.
Declare the variables in the General Declarations section (at the top of the module).
This way you only have to declare the variables once and you can use them in multiple subs.
Dim id As Integer, i As Integer, j As Integer, flag As Boolean
21. Add the GetData sub.
Sub GetData()
If IsNumeric(UserForm1.TextBox1.Value) Then
flag = False
i = 0
id = UserForm1.TextBox1.Value
Do While Cells(i + 1, 1).Value <> ""
If Cells(i + 1, 1).Value = id Then
flag = True
For j = 2 To 3
UserForm1.Controls("TextBox" & j).Value = Cells(i + 1, j).Value
Next j
End If
i = i + 1
Loop
If flag = False Then
For j = 2 To 3
UserForm1.Controls("TextBox" & j).Value = ""
Next j
End If
Else
ClearFormEnd If
End Sub
Explanation: If the ID text box contains a numeric value, Excel VBA searches for the ID and loads the corresponding record.
We use the Controls Collection to easily loop through text boxes.
If Excel VBA cannot find the ID (flag is still False), it empties the second and third text box.
If the ID text box does not contain a numeric value, Excel VBA calls the ClearForm sub.
22. Add the ClearForm sub.
Sub ClearForm()
For j = 1 To 3
UserForm1.Controls("TextBox" & j).Value = ""Next j
End Sub
Explanation: Excel VBA clears all the text boxes.
23. Add the EditAdd sub.
Sub EditAdd()
Dim emptyRow As Long
If UserForm1.TextBox1.Value <> "" Then
flag = False
i = 0
id = UserForm1.TextBox1.Value
emptyRow = WorksheetFunction.CountA(Range("A:A")) + 1
Do While Cells(i + 1, 1).Value <> ""
If Cells(i + 1, 1).Value = id Then
flag = True
For j = 2 To 3
Cells(i + 1, j).Value = UserForm1.Controls("TextBox" & j).Value
Next j
End If
i = i + 1
Loop
If flag = False Then
For j = 1 To 3
Cells(emptyRow, j).Value = UserForm1.Controls("TextBox" & j).Value
Next j
End If
End If
End Sub
Explanation: If the ID text box is not empty, Excel VBA edits the record on the sheet (the opposite of loading a record as we have seen earlier).
If Excel VBA cannot find the ID (flag is still False), it adds the record to the next empty row.
The variable emptyRow is the first empty row and increases every time a record is added.
24. Exit the Visual Basic Editor, enter the labels shown below into row 1 and test the Userform.