Visual Basic Code Samples For Excel

This will open up Visual Basic. You can also press Alt + F11 to open up VBA. Step 2: Add the Solver reference in visual basic (Tools References., then make sure that SOLVER is checked). The VBA code for the Solver macro that was recorded for Example 2 is shown below. VBA code can be defined as the code that inputs in the visual basic window to perform a set of instructions or actions in excel and provide results. With the help of VBA code, we can reduce the time to perform a repetitive task, there will not be required much human intervention except to run the program. The example code in this article is not well factored. It would be better to pull out the code inside Sub Main and use a formal parameter of the file name. Also, it would be better to extract the code inside the For-loop into a function.

In Excel VBA, IF Then Else statement allows you to check for a condition, and perform an action accordingly.

This is extremely valuable in many situations as we will see in the examples later in this tutorial.

To give you a simple example, suppose you have a list of grades in Excel and you want to highlight all those students who have scored an A. Now, if I ask you to do this manually, you will check each student’s grade and if it’s an A, you’ll highlight it, and if it isn’t, then you’ll leave it as is.

The same logic can be built in VBA using the If Then Else statement as well (and of course do a lot more than just highlighting grades).

In this tutorial, I’ll show you different ways the ‘If Then Else’ construct can be used in Excel VBA, and some practical examples in action.

But before I get into the specifics, let me give you the syntax of the ‘IF Then Else’ statement.

If you’re interested in learning VBA the easy way, check out my Online Excel VBA Training.

Syntax – IF Then Else

Below is the generic syntax of If Then Else construct in VBA

Or

Note that the Else part of this statement is optional.

Now if you’re wondering what’s the difference between the two syntaxes, let me clarify.

The first syntax is a simple one-line IF THEN ELSE statement where you don’t need to use the END IF statement.

However, in the second syntax, the true_code part is in the second line. This is helpful when the code that you need to run in case the IF condition is true is long and consists of multiple lines.

When you split the IF statement into multiple lines, you need to tell VBA where the IF Then construct ends.

For

Hence you need to use the End IF statement.

In case you don’t use End IF when required, VBA will show you an error – “Block IF without END IF”

Examples of Using IF Then Statement in VBA

To give you an idea of how the IF-THEN statement works in VBA, let me start with some basic examples (some practical and more useful examples are covered later in this tutorial).

Suppose you have a student’s score in cell A1 and you want to check whether the student passed the exam or not (passing marks threshold being 35).

Then you can use the following code:

The above code has a single line of IF statement that checks the value in cell A1.

If it’s more than 35, it shows the message – “Pass”.

If it’s less than 35, nothing happens.

But what if you want to show a message in both the cases, whether a student passed or failed the exam.

The below code would do this:

The above code uses the IF as well as the ELSE statement to execute two different conditions. When the score is more than (or equal to) 35, the IF condition is true, and the code right below it gets executed (everything before the Else statement).

But when the IF condition is FALSE, the code jumps to the Else part and executes the code block in it.

Note that when we use a single line of IF Then statement, we don’t need to use End IF. But when we split it into more than one line, we need to use the End If statement.

Nested IF Then (Multiple IF Then statements)

So far we have used a single IF Then statement.

In case you have multiple conditions to check, you can use:

  • Multiple IF conditions
  • If Then Else statement
  • IF Then ElseIf Else construct

Let me show you how these differ and how to use this in Excel VBA.

Multiple IF Then Statements

Let’s take the same example of using a student’s score.

If the student scores less than 35, the message to display is ‘Fail’, if the score is more than or equal to 35, the message to display is ‘Pass’.

We can use the below code to get this done:

You can use multiple IF Then statement as shown above. While this works, it’s not an example of good coding (as you will see the alternatives below).

In case you decide to use this, remember that these statements should either be independent or mutually exclusive. The important thing to know here is that in the above construct, all the IF statements are evaluated and the ones where the condition is true, the code is executed.

So even if the first IF statement is correct, the second would still be evaluated.

IF Then Else Statement

Suppose this time, instead of just displaying the message Pass/Fail, we have one more condition.

If the student scores less than 35, the message to display is ‘Fail’, if the score is more than or equal to 35, the message to display is ‘Pass’, and if the score is more than 80, the message to display is ‘Pass, with Distinction’.

We can use the below code to get this done:

In the above code, we have used multiple IF statements (nested IF Then) with the help of Else.

So there is an ‘IF Then Else’ construct within an ‘IF Then Else’ construct. This type of nesting allows you to check for multiple conditions and run the relevant block of code.

IF Then ElseIf Else Statement

The above code (that we saw in the previous section) can be further optimized by using the ElseIf statement.

Here is what we’re trying to do – If the student scores less than 35, the message to display is ‘Fail’, if the score is more than or equal to 35, the message to display is ‘Pass’, and if the score is more than 80, the message to display is ‘Pass, with Distinction’.

The above code uses ElseIf, which allows us to keep all the conditions within one single IF Then statement.

Using AND and OR in IF Then Else

So far in this tutorial, we have only checked for a single condition at a time.

However, when you have multiple dependent conditions, you can use the AND or OR statement with the IF conditions.

Below is the syntax of using AND/OR condition with the IF Then statement.

In the above code, only when both Condition1 and Condition2 are met, the true_code is executed. Even if one of the conditions is false, it will execute the false_code.

With OR, even if one of the conditions are true, it will execute the true_code. Only when all the conditions are false, it executes the false_code.

Now let’s see how AND and OR statement work with the IF Then Else construct.

Suppose you have the scores for two subjects instead of one, and you want to check for the following conditions:

  • Fail – When the score is less than 35 in any of the subjects.
  • Pass – When the score is more than or equal to 35, but less than 80 in both the subjects.
  • Pass, with Distinction – When the score is more than 35 in both the subjects and is more than or equal to 80 in one or both the subjects.

Here is the code that will do this:

The above code uses both OR and AND statements.

You can also write this same code with a slight change (using OR instead of AND).

Both the above VBA codes will give you the same result. Personally, I prefer the first one as it has a logical flow of checking the scores (but that’s just me).

Using Not Equal to in If Then

In all the examples above, we have used the conditions that check whether a value equal to a specified value or not.

You can also use similar codes when checking when the value is not equal to a specified value in the VBA code. Not equal to represented by <> the Excel VBA.

To see a practical example of using <>, have a look at Example 1 below.

Using If Then Else with Loops in VBA

So far, we have been going through some examples that are good to understand how the ‘IF-THEN’ statements work in VBA, however, are not useful in the practical world.

If I need to grade students, I can easily do that using Excel functions.

So let’s have a look at some useful and practical examples that can help you automate some stuff and be more efficient.

Example 1 – Save and Close All Workbooks Except The Active Workbook

If you have a lot of workbooks open and you quickly want to close all, except the active workbook, you can use the below code,

The above code would save and close all the workbooks (except the active one).

It uses the For Next loop to go through the collection of all the open workbooks and checks the name using the IF condition.

If the name is not the same as that of the Active workbook, it saves and closes it.

In case there is a VBA code in any of the workbooks and you haven’t saved it as .xls or .xlsm, you will see a warning (as the vba codes are lost when you save it in .xlsx format).

Example 2 – Highlight Cells with Negative Values

Suppose that you have a column full of numbers and you want to quickly highlight all the cells with negative values in red, you can do that using the below code.

The above code uses the For Each loop and checks each cell in the selection that you have made. If the cell has a value that is negative, it’s highlighted in red with white font color.

Example 3 – Hide All the Worksheet Except the Current Worksheet

In case you want to quickly hide all the worksheets except the active one, you can use the below code:

The above code uses the For Each loop to go through a collection of worksheets. It checks the name of each worksheet and hides it if it’s not the active worksheet.

Example 4 – Extract the Numeric Part from an Alphanumeric String

If you have alphanumeric strings in cells and you want to extract the numeric part from it, you can do that using the below code:

This code will create a custom function in Excel that can use within the worksheet (just like a regular function).

Excel

Where to Put the VBA Code?

Wondering where the VBA code goes in your Excel workbook?

Excel has a VBA backend called the VB editor. You need to copy and paste the code in the VB Editor module code window.

Here are the steps to do this:

  1. Go to the Developer tab.
  2. Click on Visual Basic option. This will open the VB editor in the backend.
  3. In the Project Explorer pane in the VB Editor, right-click on any object for the workbook in which you want to insert the code. If you don’t see the Project Explorer go to the View tab and click on Project Explorer.
  4. Go to Insert and click on Module. This will insert a module object for your workbook.
  5. Copy and paste the code in the module window.

You May Also Like the Following Excel Tutorials:

  • How to Record a Macro in Excel.
  • Working with Cells and Ranges in Excel VBA.
  • Working with Worksheets in Excel VBA.
  • Working with Workbooks in Excel VBA.
  • Creating a Custom Function in Excel Using VBA.
  • Excel VBA Events – An Easy (and Complete) Guide.
  • How to Run a Macro in Excel.
  • How to Create and Use an Excel Add-in.
  • How to Use Excel VBA InStr Function (with practical EXAMPLES).

Get 51 Excel Tips Ebook to skyrocket your productivity and get work done faster

Posted on Wednesday, October 9th, 2013 at 8:42 am by Ty Anderson.

We’ve covered how to write code that automates Excel base objects. Today, I want to focus on the Excel workbook file and its worksheets. Let’s take a look at how to perform some useful tasks with these two objects.

Working with Excel workbooks

Microsoft Excel Visual Basic Reference

When you take control of Excel workbooks via code (aka “code against them”), you typically need to know various things about the workbook. Let’s cover the basics by looking at code samples.

ActiveWorkbook object

When the user clicks a button or otherwise initiates a command they almost always want to act upon the active spreadsheet. Excel has an object for this called the ActiveWorkbook and the following function returns it.

You don’t really need this function. Sometimes, creating examples makes for silly code. But the sample does its job. It shows that a call to ExcelApp.ActiveWorkbook serves up the current spreadsheet for you to do whatever it is you need to do to it.

Get the file path to the active workbook

If you have an ActiveWorkbook, you’re going to want to know things about it. For example its folder path and file name.

The FullName properties gives you both.

Get the folder path

Now, what do you do if you don’t want both folder path and file name? What if you want just the folder path? Easy…

Just grab the Path property.

Get the workbook name

How about if you only want the Excel workbook’s file name? The Name property of a Workbook object provides the spreadsheet’s filename.

All fair and good.

Visual basic code for beginners

Save a workbook & get the file format

In baseball the basic skills are throwing and catching. In Excel development, saving files and dealing with different file formats is basic skill. In this sample, the method checks the file format of the passed workbook file and branches based on what it discovers.

If the file is not an XML-based file (i.e. an .XLS file), the code saves it in normal format. Normal is now the Open XML format. Notice how the call makes effective use of the FullName property.

Visual Basic Code Samples For Excel Templates

Add a workbook to the Favorites folder

The files utilized by your Excel add-in stand a decent chance of being a user’s favorite…at least for a small period of time. You can make it easy for the user to open these files by creating shortcuts to them in the Windows favorites folder.

Protect a workbook

All well-built Excel spreadsheet is worth protecting… especially so if you are automating the spreadsheet in any way. The last thing a developer needs is a user thinking they can edit any-old-cell. They can’t and we don’t need to let them. Here’s how to keep those pesky users in-line:

Just call Protect or Unprotect and store that password in a safe place.

Create or edit the default document properties

Document properties contain information about the workbook. In the SharePoint world, this information is known as metadata. There are two kinds of properties, default (or built-in) and custom. We have to deal with them separately because:

  1. They reside in different collections.
  2. You can’t create additional built-in properties.

This method edits a built-in property value.

The code attempts to retrieve the property using the passed propName value. Because I believe in some good coding practices, the method checks to ensure it has a property before continuing. It avoids errors this way.

Create or edit custom properties of a workbook

For custom properties, I’ve combined the edit and create abilities into a single method. It works like the preceding method except with a couple of exceptions.

  1. It loops through all the custom properties looking for one that matches the propName parameter value.
  2. If the method can’t find the property, it assumes it should exist and proceeds to create it and assign a value to it.

In Texas this is what we call a “Twofer“. Twofer is short for “Two for one”.

Working with worksheets

Worksheets are the tabs within an Excel workbook. I tend to think of them as separate spreadsheets but that is probably not the purist view. Anyway, users tend to group data by tab… that is they use different worksheets for different purposes within the workbook file. They are a main character in any Excel custom add-in drama.

Grab the ActiveSheet

Like ActiveWorkbook, the ActiveSheet will typically be the object the user wants to see impacted by any custom action. You can access this object via the ExcelApp object.

This is convenient. I like that I don’t have to call ExcelApp.ActiveWorkbook.ActiveSheet. That’s too many words and requires too much typing.

Get worksheet name

Each Excel worksheet has a name. If you want to know a sheet’s name, just ask it.

The Name property returns the name on the sheet’s tab. Users can change this name, so be careful using it as it is not always reliable.

Get a worksheet code name

If you want a reliable name, use the CodeName property.

CodeName does not change when the user edits the sheet name. The only way to change the code name is through the Visual Basic editor’s property window.

Reference a specific sheet

Each worksheet resides in the Worksheets collection. Thus, you can retrieve a sheet by its index value.

You can also reference a sheet by name by making a call like this one:

Copy or move a worksheet

Just like files, a good worksheet can serve as the template for other worksheets. Invariably, you will need to either copy the worksheet within a workbook or you will need to move a sheet to a new Excel file. This sample handles both tasks.

Free Visual Basic Code Examples

The newWorkbook parameter tells the code which direction to take. The Copy method of the worksheet object completes the task. To make a copy within a workbook, you need to pass a sheet to specify where the copy will reside (before or after). In the sample above, the copy will reside after the original sheet.

Hide a worksheet

Not all worksheets need to be viewed by users. If you need to store some data and then hide it, a worksheet comes in handy. If you do this, you can hide it or you can really hide it.

The xlSheetHidden value will hide the tab but keep it listed in the workbook’s list of worksheets. The xlSheetVeryHidden value hides the tab and does not list the worksheet. Use this option if you want to prevent a user from un-hiding it against your will.

*****

Admittedly, these samples are just Excel workbook and worksheet blocking and tackling. They’ll get you started. But what is fun is to start developing a solution for actual users. The scenarios they dream-up will take your task to higher level.

Available downloads:

This sample Excel add-in was developed using Add-in Express for Office and .net:

Excel add-in development in Visual Studio for beginners: