Visual Basic Code Examples For Excel

VBA Conditional Statements

  1. Excel Visual Basic Programming Examples
  2. Visual Basic Code Examples For Excel
  3. Visual Basic Code Examples For Excel Free

Step 2: Open the visual basic editor. Now you should see the Developer tab in your Excel ribbon and you can open the visual basic editor (VBE) from the ribbon. Go to the Developer tab. Press the Visual Basic button in the code section. Alternatively, you can open the VBE with the Alt + F11 shortcut. Step 3: Insert a module into the current. VBA excel programming has been distant from the main menus and been transformed into an option to save beginners from being confused or intimidated by it. VBA (Visual Basic for Applications) is a language associated with Visual Basic that can only run through a host application (In our case Excel). Visual Basic Projects, Visual Basic Examples, Visual Basic Source Code Search form Visual Basic is a third-generation event-driven programming language and integrated development environment (IDE) from Microsoft for its COM programming model first released in 1991.

The main Excel VBA Conditional Statements are the If .. Then statement and the Select Case statement. Both of these evaluate one or more conditions and, depending on the result, execute specific sections of code.

The two Conditional Statement types are discussed individually below.


The Visual Basic If .. Then Statement

The If .. Then statement tests a condition and if it evaluates to True, executes a specific section of code. If the condition evaluates to False, a different section of code is executed.

The syntax of the If .. Then statement is:

IfCondition1Then
Code to be executed if Condition1 evaluates to True
ElseIfCondition2Then
Code to be executed if Condition2 evaluates to True
Else
Code to be executed if none of the previous conditions evaluate to True
End If

In the above If statement, you can add as many ElseIf conditions as you require. Alternatively, the ElseIf and the Else parts of the conditional statement can be omitted if desired.

In the example below, an If .. Then statement is used to color the current active cell, depending on the value of the cell contents.

If ActiveCell.Value < 5 Then
ActiveCell.Interior.Color = 65280 ' Color cell interior green
ElseIf ActiveCell.Value < 10 Then
ActiveCell.Interior.Color = 49407 ' Color cell interior orange
Else
ActiveCell.Interior.Color = 255 ' Color cell interior red
End If

Note that, in the above example, the If statement stops once it has satisfied a condition. Therefore, if the ActiveCell value is less than 5, the first condition is satisfied and so the cell is colored green. The If .. Then statement is then exited, without testing any further conditions.


For further information on the VBA If .. Then statement, see the Microsoft Developer Network website.


The Visual Basic Select Case Statement

The Select Case statement is similar to the If .. Then statement, in that it tests an expression, and executes different sections of code, depending on the value of the expression.

Visual Basic Code Examples For Excel

The syntax of the Select Case statement is:

Select CaseExpression
CaseValue1CaseValue2
Actions if Expression matches Value2
Case Else
Actions if expression does not match any of listed cases
End Select

In the above code, the Case Else part of the conditional statement is optional.

In the following example, the Select Case statement is used to color the current active cell, depending on the value of the cell contents:

Select Case ActiveCell.Value
Case Is <= 5
ActiveCell.Interior.Color = 65280 ' Color cell interior green
Case 6, 7, 8, 9
ActiveCell.Interior.Color = 49407 ' Color cell interior orange
Case 10
ActiveCell.Interior.Color = 65535 ' Color cell interior yellow
Case Else
ActiveCell.Interior.Color = 255 ' Color cell interior red
End Select

The above example illustrates different ways of defining the different Cases in the Select Case statement. These are:

Case Is <= 5This is an example of how you can test if your expression satisfies a condition such as <= 5 by using the keyword Case Is
Case 6, 7, 8, 9This is an example of how you can test if your expression evaluates to any one of several values, by separating the possible values by commas
Case 10This is an example of the basic test of whether your expression evaluates to a specific value
Case ElseThis is an example of the 'Else' condition, which is executed if your expression hasn't matched any of the previous cases

Note that as soon as one case in the Select Case statement is matched, and the corresponding code executed, the whole Select Case statement is exited. Therefore, the code will never enter more than one of the listed cases.


For further information on the VBA Select Case statement, see the Microsoft Developer Network website.

Go To Excel VBA Tutorial Part 6 - Loops
Return to the Excel VBA Tutorial Page

If you’ve done a lot of work in Excel, you’ve probably heard about Macros orVBA. Excel VBA can help you do your work much, much faster. It can also help youexpand the true power of Excel in ways you never thought possible. Ranging fromprocessing data in a worksheet all the way to scraping web pages, VBA is quitethe beast. In this post, I’d like to discuss Excel VBA for beginners. We’llcover:

  • What is VBA?
  • When should you use VBA?
  • Getting started with the Visual Basic Editor
  • Your first useful program

What is VBA and why should I care?

VBA stands forVisual Basic for Applications.It is an implementation of Microsoft’sVisual Basic 6 programminglanguage specific to Office applications in order to give you access to eachapplication’s features like cells, charts, and more. Each Office application hasits own VBA Object Model (an Object Model is sort of like a map of the featuresyou have access to with VBA). So while the VBA concepts are the same for eachOffice application, there is still a learning curve for each one.

Ok, enough with the boring stuff. Why should you care about Excel VBA?

Simple: it makes your life easier.

(You laugh - this really happened to me)

You can write programs that will do tasks for you lightning fast - leaving youmore time to do other things that are more important. This is especially usefulfor when you have to do a repetitive, tedious task to perform. For example, youcould use Excel VBA for:

  • Copying and modifying data
  • Apply formatting automatically
  • Finding unique values
  • Data checking before Saving
  • Go beyond Sheet Protection
  • Create forms to control data entry
  • And so much more (seriously, way more)

If this article helps solve your problem, please consider supporting me because it takes a lot of effort (and coffee!) to provide this content.

👇 There's a special gift for you in return for your support.

Enjoy the post!

When Should You Use VBA?

When you have a logical, repeatable process that you do over and over, thenit’s time to consider automating it. However, if you’re just doing a one-offthing that will take you 10 minutes to do and will probably never do it again,it will probably not be worth your time making a macro to get the job done. Justrough through it. Trust me on this.

Excel VBA for Beginners - Start with the Visual Basic Editor

The first place to get started would be the Visual Basic Editor. PressALT+F11. You will have a new window pop up.

This is called the Visual Basic Editor and this is where you’ll be doing allyour magic. Consider this your workbench, or your garage, or your desk -whatever place you get your work done.

I’m sure you’re itching to get some coding done, and we will! But it’s importantto understand where the tools are so you understand your surroundings. So, let’squickly breakdown these components:

Excel VBA Project Window

Located at the top left of the VBE window, the Excel VBA Project window willshow you all the places where your VBA code can potentially live. Think of it asa quick reference like Windows folders in Explorer. In this section, you canfind Worksheet code, Workbook code, Userform code, regular Modules, and ClassModules. Each one of these could be considered a Project Object. All ofthese Project Objects can hold code, but each one has it’s own special uses(which I’ll cover in a later post).

Properties Window

Just below the Project Window is the Properties Window. This window holds theproperties of each Project Object that is currently selected. I haven’t foundmany times where I needed to use this, but feel free to poke around to getfamiliar with changing those properties.

Toolbar

Just your standard toolbar. We’ll dig more into this as we move along withfuture posts.

Okay. Enough of that. Let’s get to the real meat.

Writing Your First Useful Program

Many “intro to programming in X language” articles usually start with a “HelloWorld” program. What that basically means is that the article teaches you how todisplay “Hello World” to the user. But these kinds of intros leave a lot to bedesired. So, let’s forget”Hello, world!” and get someREAL work done.

Before Beginning

DANGER

Visual Basic Code Examples For Excel

Please realize that you cannot Undo any changes that Excel VBA code will maketo your spreadsheet.

Sorry, but there’s no Control+Z’ing your way out of a VBA mistake!

Naruto shinobi striker pc. That said, please Save before moving executing any Excel VBA code in case somethinggoes wrong. I personally suggest that you use a test workbook when learning VBA.

For our first program, let’s delete entire rows of data if column A has aspecific value in it. For example, say we have this data:

We want to delete any row with “Delete” in it and leave the other rows alone.So, we have 4 “Keep” cells to leave alone and to delete 3 “Delete” cells. If youwere to do this, how would you begin?

Your first inclination might be to loop through the cells, search for “Delete”and, if found, delete the entire row. Yes? Cool, let’s try that.

Go to the VBE window and create a new module by right-clicking on the workbookname in the Project Window, hover over Insert, and click on Module, like so:

Add this code to the module (we’ll go over what this means in a minute):

In order to run this code:

  1. Go back to the workbook and select the cells A1:A8 (this is important toremember)
  2. Bring up the Macro Window by pressing ALT+F8
  3. Select “deleteText”

Click Run. Let’s take a look at the data.

…huh. There’s still one cell that says Delete.

C’mon man. How is this a useful program? It didn’t even work right!

Alright, alright. Calm down. This kind of thing is something you’ll always runinto when coding. No matter how good you get, there will always be somethingthat snags you. I figured it was a good idea to get you used to this type ofthing early on. All this means is that we have a bug in the code. So let’s”debug” it.

Debugging Code

There are a lot of debugging features to cover, but this post has already goneon and on pretty long and I want to try to hold your attention for just aliiiittle bit longer. So let’s cover the code step by step to see if we canuncover what went wrong.

The first line of code is just a variable declaration, so there’s nothing wrongwith that. The only other part of this code is the For loop, so let’s see what’sgoing on there.

This line tells VBA to process all the cells in your selection one-by-one. Inorder to do anything with the cell being processed for each time the loop runsits course, we tell VBA to assign each cell to the variable r. This is the waywe access each cell’s information as we loop through all the cells in theselection.

The text inside the cell is what we’re trying to check - and this is how wecheck it. r.Value will return whatever text is within the cell that we’reinvestigating. If the cell’s value is 'Delete' then we will move on to thenext statement, which is:

Visual Basic Code Examples For Excel

So, if the cell’s text reads “Delete” then we want to delete the entire rowthat that cell is in. Simple, right?

Well, not exactly.

When we tell VBA “hey, loop through these cells, please,” it will take thatrange of cells, and store it internally so it can loop through it. The way Exceldoes this is by using a counter to keep track of where it is within the range.So, let’s look at the original data again:

The first row has “Data” in the cell, so we skip this one. The second row has“Delete” in it, so we delete it, along with the entire row. This affects theentire range that we’re working with. So, before we deleted the row, VBA wasat row 2:

Then we delete the row, and VBA is still at row “2” (which was row 3, but isnow row 2).

Excel Visual Basic Programming Examples

What’s next in the code?

This is a way to “close off” the If statement. So only the items inside theIf statement will be executed if the If statement evaluates to True.What’s next?

This tells Excel to move to the next row down, which is row 3. So, technically,it skipped the “Keep” that was in row 3, but is now in row 2.

Confusing? Sometimes that’s just how code is :)

Think you know where the bug is? If you realized that the second “Delete” cellwas skipped because we modified the range while VBA was looping through it, youguessed right.

Ok, so how do we fix this?

Let’s pick something easy. Let’s find the cells that have “Delete” in them, andinstead of deleting the entire row, let’s just make the text blank. We’ll changer.EntireRow.Delete to r.ClearContents.

But that only makes the cells blank, and you want to remove the entire row forall of those. Canon mf3200 printer driver. So we’ll add another line of code:

After all the “Delete” cells have had their text cleared, we do a search on theoriginal selection for blank cells, and delete the entire row for only thosecells. Here’s our new code:

Try running that code again. Notice anything different?

Awesome. Now we have working code.

Visual Basic Code Examples For Excel

Where to Go From Here

There is a lot of power in Excel VBA. When I started learning about it, I wantedto automate everything - and I practically did. I became so good at my job because Iwas getting things done faster than everyone else. This got me noticed, which was good.Then I started sharing the tools I created with my teammates and then we became fasteras a team. This got me a raise, which was better.

Excel visual basic function example

Visual Basic Code Examples For Excel Free

If you continue on learning how to harness the power of VBA, it will help you outtremendously. So what are you waiting for? Let’s move on to the next item: