Mastering Conditional Logic in Excel VBA: If-Then-Else Statements

Introduction:

Excel VBA (Visual Basic for Applications) is a powerful tool for automating tasks and processes in Microsoft Excel. It allows you to create complex scripts to manipulate data, perform calculations, and make decisions. Conditional logic is a fundamental part of programming, and in this comprehensive guide, we’ll delve into If-Then-Else statements in Excel VBA.

The Power of Conditional Logic:

Conditional logic in Excel VBA enables you to make your code smarter by allowing it to respond to specific conditions. If-Then-Else statements provide a way to execute different code blocks based on whether a particular condition is met. These statements are essential for creating dynamic, responsive, and intelligent Excel applications.

The If-Then Statement:

The If-Then statement is the building block of conditional logic. It allows you to execute code lines when a specified condition is true. Here’s a more detailed look at how to use If-Then in Excel VBA:

Code:

Dim score As Integer, result As String
score = Range("A1").Value

If score >= 60 Then
result = "Pass"
End If

Range("B1").Value = result

Excel VBA If Then Statement

In this example:

  • We declare two variables, score and result, and retrieve the value in cell A1.
  • The If statement checks if the score is greater than or equal to 60.
  • If the condition is true, it assigns “Pass” to the result variable.
  • The result is then displayed in cell B1.

This basic If-Then structure sets the stage for more advanced decision-making processes.

The If-Then-Else Statement:

The If-Then-Else statement extends conditional logic to provide two different outcomes based on whether a condition is true or false. Here’s how it works:

Code:

Dim score As Integer, result As String
score = Range("A1").Value

If score >= 60 Then
result = "Pass"
Else
result = "Fail"
End If

Range("B1").Value = result

Excel VBA Else Statement

In this example:

  • We use the If-Then-Else structure to determine whether the score is above or below 60.
  • If the score is greater than or equal to 60, the result is set to “Pass.”
  • If not, the result is assigned “Fail.”

This more advanced logic allows you to create applications that respond dynamically to various scenarios.

Conclusion:

Conditional logic is an indispensable part of Excel VBA programming, enabling you to build intelligent, automated solutions. If-Then-Else statements provide the tools you need to create applications that respond to specific conditions, making your work in Excel more efficient and dynamic. With this knowledge, you can take your Excel skills to the next level.

Excel VBA Mastery – Formatting Your Data with Fonts and Colors

Introduction:

Unlocking the power of formatting in Excel VBA is essential for creating professional and visually appealing spreadsheets. This guide will walk you through using fonts and colors to make your data stand out and convey information more effectively.

Mastering Font Properties:

In Excel VBA, the Font property of the Range object is your gateway to a range of formatting options. The Font object offers properties like Color and Bold, allowing you to take control of your text.

Color Property:

To change the text color in your Excel range, employ the Font property, and then the Color property of the Font object:

Code:

Range("A1").Font.Color = RGB(255, 0, 0) ' Set the text color to pure Red

Excel VBA provides built-in constants like vbRed for common colors:

Code:

Range("A1").Font.Color = vbRed ' Set the text color to Red

Bold Property:

You can easily make text bold with Excel VBA:

Code:

Range("A1").Font.Bold = True ' Make the text bold

Font and Bold Property in Excel VBA

To unbold text, simply use the False keyword.

Changing Background Colors:

Manipulating background colors in VBA is straightforward. Use the Interior property to return an Interior object. Then, adjust the background color with the ColorIndex property:

Set the background color of cell A1 to light blue:

Code:

Range("A1").Interior.ColorIndex = 37

Background Color in Excel VBA

Clear the background color (set it to ‘No Fill’):

Code:

Range("A1").Interior.ColorIndex = 0

No Fill

If you need to determine the ColorIndex number of a color, Excel VBA can provide the answer:

Code:

MsgBox Selection.Interior.ColorIndex

Get ColorIndex Number

Utilize the Color property and the RGB function for more extensive color customization. RGB stands for Red, Green, and Blue, offering a full spectrum of colors. For example, RGB(255, 0, 0) results in pure Red.

Mastering Range Objects in Excel VBA

Mastering Range Objects in Excel VBA

The Range object is a powerhouse in Excel VBA, and understanding its properties and methods is essential for effective VBA programming. In this comprehensive guide, we’ll delve into the versatility of Range objects and how they can be harnessed to perform a variety of tasks in Excel.

Range Object Basics

The Range object is the representation of a cell or cells on your worksheet and is the cornerstone of Excel VBA. Let’s explore its properties and methods, which are crucial for manipulating data.

Examples of Range Usage:

  • Setting values to a specific cell:

Code:

Range("B3").Value = 2

Excel VBA Range Example

  • Setting values to a range of cells:

Code:

Range("A1:A4").Value = 5

Range Example

  • Setting values to non-contiguous ranges:

Code:

Range("A1:A2,B3:C4").Value = 10

Range Example

Working with Cells

While the Range object is powerful, you can also achieve specific cell interactions using the Cells property.

  • Set the value of a specific cell:

Code:

Cells(3, 2).Value = 2

Cells in Excel VBA

  • Copy data from one range to another:

Code:

Range("C3:C4").Value = Range("A1:A2").Value

Declaring a Range Object

In Excel VBA, declaring a Range object is a common practice for efficient coding.

Code:

Dim example As Range

Set example = Range("A1:C4")

example.Value = 8

Declare a Range Object in Excel VBA

Selecting Ranges

The Select method is useful for interacting with specific ranges in your code.

Code:

Dim example As Range

Set example = Range("A1:C4")

example.Select

Select Method

Rows and Columns

You can work with entire rows and columns with Excel VBA, simplifying your tasks.

  • Selecting the second column:

Code:

Columns(2).Select

  • Selecting the seventh row:

Code:

Rows(7).Select

Copying and Clearing Ranges

Copying and clearing data can be done using the Copy, Paste, Clear, and ClearContents methods.

  • Copying and pasting data:

Code:

Range("A1:A2").Select

Selection.Copy

Range("C3").Select

ActiveSheet.Paste

  • Clearing content from a cell:

Code:

Range("A1").ClearContents

Understanding CurrentRegion

The CurrentRegion property defines a range bounded by any combination of blank rows and columns.

  • Find the CurrentRegion of cell A1:

Code:

Range("A1").CurrentRegion.Select

Current region of cell A1

  • Find the CurrentRegion of cell B3:

Code:

Range("B3").CurrentRegion.Select

Current region of cell B3

Dynamic Range and Coloring Max Value

This code snippet demonstrates coloring the maximum value in a dynamic range.

Code:

' Insert your dynamic range
Dim rng As Range
Set rng = Range("A1:A10")

' Find the maximum value in the range
maximum = WorksheetFunction.Max(rng)

' Color the maximum value
For Each cell In rng
If cell.Value = maximum Then cell.Interior.ColorIndex = 22
Next cell

Dynamic Range Result

Resizing Ranges with Resize

The Resize property allows you to make a range larger or smaller by specifying the number of rows and columns.

Code:

Range("A1:C4").Resize(3, 2).Select

Excel VBA Resize Property Result

Code:

Range("A1:C4").Resize(, 1).Select

Excel VBA Resize Property Result

Union and Intersect Methods

The Union and Intersect methods enable you to work with multiple ranges at once.

  • Union of two ranges:

Code:

Union(Range("B2:C7"), Range("C6:F8")).Select

Union Of Two Ranges

  • Intersect of two ranges:

Code:

Intersect(Range("B2:C7"), Range("C6:F8")).Select

Union Of Two Ranges

Testing a Selection

You can test a selection in Excel VBA using Count, IsNumeric, IsEmpty, and Intersect.

Test a Selection in Excel VBA

Working with the Areas Collection:

Counting Areas:To determine the number of areas within a given range, use the Areas.Count property.

Code:

Dim rangeToUse As Range
Set rangeToUse = Range("B2:C3,C5:E5")
MsgBox rangeToUse.Areas.Count

Areas Collection in Excel VBA

  • Result: This code will display the count of areas within the specified range.

Count Areas

Accessing Specific Areas:You can access specific areas within a range by using index values. The following code counts the number of cells in the first area.

Code:

MsgBox rangeToUse.Areas(1).Count

  • Result: This code displays the count of cells in the first area of the range.

Count Cells, First Area

Looping Through Areas:To process each area in a range and count the cells in each area, you can use a loop. The following code does just that:

Code:

Dim singleArea As Range
For Each singleArea In rangeToUse.Areas
MsgBox singleArea.Count
Next singleArea

  • Result: This code will display the count of cells in each area of the range.

Count Cells, First Area

Count Cells, Second Area

Comparing Ranges:

Scenario:You have randomly selected ranges, and you want to highlight cells that contain unique values. This code will help identify values that only appear once across all selected ranges.

Code:

Dim rangeToUse As Range, singleArea As Range, cell1 As Range, cell2 As Range, i As Integer, j As Integer

Set rangeToUse = Selection
Cells.Interior.ColorIndex = 0
Cells.Borders.LineStyle = xlNone

If Selection.Areas.Count <= 1 Then
MsgBox "Please select more than one area."
Else
rangeToUse.Interior.ColorIndex = 38
For Each singleArea In rangeToUse.Areas
singleArea.BorderAround ColorIndex:=1, Weight:=xlThin
Next singleArea
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 j
Next i
End If

Compare Ranges in Excel VBA

  • Result: This code will highlight unique values in the selected ranges while removing the highlighting for non-unique values.

Compare Ranges Result

Mastering Offset Property:

The Offset property is a powerful tool in Excel VBA, enabling you to navigate to specific cells relative to a starting point. Let’s explore its applications:

Moving Relative to a Range:

Code:

Dim example As Range
Set example = Range("A1:A2")
example.Offset(3, 2).Select

Excel VBA Offset Property Result

Result: These code lines select the range that is 3 rows below and 2 columns to the right of Range(“A1:A2”). Remember that Offset always takes the top left cell of a range as the starting point.

From Active Cell to Last Entry:

The End property is a valuable asset in Excel VBA, especially when you need to find the last entry in a column. Let’s see how it works:

Selecting the Last Entry in a Column:

Code:

Range("A5").End(xlDown).Select

Last Entry

Note: You can use various starting points such as Range(“A1”) or Range(“A2”). This code line is equivalent to pressing the END+DOWN ARROW.

Result: The last entry in the column is selected.

Selecting a Range to the Last Entry:

Code:

Range(Range("A5"), Range("A5").End(xlDown)).Select

From Cell A5 to Last Entry

Result: This code line selects the range from cell A5 to the last entry in the column.

Selecting from the Active Cell to the Last Entry:

Code:

ange(ActiveCell, ActiveCell.End(xlDown)).Select 

From Active Cell to Last Entry Result

Result: When you select any cell, this code line chooses the range from the active cell down to the last entry in the column.

You’re not limited to moving down; you can use constants like xlUp, xlToRight, and xlToLeft to navigate in other directions, allowing for versatile and precise selections.

Final Thoughts

Mastering Range objects is crucial for proficient Excel VBA programming. These objects empower you to manipulate data with precision and flexibility, making your Excel tasks more efficient and automated. These skills are invaluable for handling complex data analysis tasks with ease.

Mastering VBA Variables: – A Comprehensive Guide

Welcome to a comprehensive guide on mastering VBA (Visual Basic for Applications) variables. In this combined edition, we’ll explore the intricacies of variables in VBA, covering essential concepts from our beginner’s guide.

Declaring Variables Part 1

In this section, we delved into the world of declaring, initializing, and displaying variables in Excel VBA. Here’s a glimpse of what you learned:

1. Integer Variables

Integer variables are designed to store whole numbers. You declared an Integer variable, initialized it, and displayed its value in Cell A1.

Code:

Dim x As Integer
x = 6
Range("A1").Value = x

The first code line declares a variable with name x of type Integer. We initialize x with value 6. So we write the value of x to cell A1.

2. String Variables

String variables, your gateway to storing text, were explored. You declared a String variable, initialized it, and wrote the text to Cell A1.

Code:

Dim book As String
book = "bible"
Range("A1").Value = book

The first code line declares a variable with name book of type String. We initialize book with the text bible. Always use apostrophes to initialize String variables. We write the text of the variable book to cell A1.

3. Double Variables

Double variables, offering higher precision, were introduced. We emphasized the importance of choosing the correct variable type for your needs.

Code:

Dim x As Double
x = 5.5
MsgBox "value is " & x

Long variables have even larger capacity. Always use variables of the right type. As a result, errors are easier to find and your code will run faster.

4. Boolean Variables

Boolean variables, capable of holding True or False values, were explained. You used a Boolean variable to trigger a MsgBox based on the value held.

Code:

Dim continue As Boolean
continue = True

If continue = True Then MsgBox "Boolean variables are cool"

The first code line declares a variable with name continue of type Boolean. We initialize continue with the value True. We use the Boolean variable to only display a MsgBox if the variable holds the value True.

Declaring Variables Part 2 – Option Explicit

In this section, we discussed the vital importance of Option Explicit in your VBA code. Here’s a summary of what you discovered:

Option Explicit

We strongly recommended using Option Explicit at the beginning of your Excel VBA code. It enforces variable declaration and helps identify issues related to variables. We demonstrated how missing or incorrectly declared variables can lead to errors.

Absolutely, here are improved steps for instructing Excel VBA to automatically add Option Explicit:

  1. Open the Visual Basic Editor by going to the “Developer” tab and clicking “Visual Basic” or by using the shortcut Alt + F11.
  2. In the Visual Basic Editor, go to the “Tools” menu.
  3. Select “Options” from the Tools menu.
  4. In the Options dialog box, under the “Editor” tab, ensure that “Require Variable Declaration” is checked.
  5. Click “OK” to save your preferences.

By following these steps, you’ll have Option Explicit automatically added to your Excel VBA code, helping you avoid common programming errors.

Require Variable Declaration

Automating Option Explicit

We also showed you how to instruct Excel VBA to automatically add Option Explicit to your code, saving you from unnecessary debugging and errors.

By combining the knowledge from these sections, you’re well on your way to becoming a proficient VBA programmer. Stay tuned for more chapters, where we’ll explore advanced topics and practical applications of VBA in Excel.

Unveiling the World of VBA Macros: A Beginner’s Guide

Welcome to Chapter 1 of our journey into the world of VBA (Visual Basic for Applications) Macros, the programming language that empowers Excel and various Office programs. In this introductory chapter, we’ll explore the basics and key abbreviations you need to kickstart your VBA learning adventure.

Chapter 1: Navigating the VBA Universe

VBA stands for Visual Basic for Applications, and it serves as the bridge between you and the power of automation. Let’s delve into the essential points you’ll encounter on your VBA/Macros journey:

1. Creating Macros with VBA

VBA is your gateway to automating tasks through the creation of macros. With VBA, you can script out sequences of actions to make Excel work for you, streamlining your workflow.

2. The MsgBox Function

The MsgBox, short for message box, is your tool for communicating with users. You can use it to provide information, warnings, or gather input from users within your VBA applications.

3. Understanding Workbook and Worksheet Objects

In the VBA world, workbooks and worksheets are objects you’ll frequently interact with. Learning the ins and outs of these objects is fundamental for VBA coding.

4. Exploring the Range Object

The Range object is your window into manipulating cells and data on your Excel worksheet. Understanding how to work with this object is essential for any VBA developer.

5. Mastering Variables

In this chapter, you’ll get to grips with variables. Learn how to declare, initialize, and display variables in VBA, a crucial skill for data manipulation.

6. The Power of If-Then Statements

Conditional logic is a fundamental building block in programming. Discover how to use the If-Then statement to execute specific code lines when specific conditions are met.

7. Unleashing the Potential of Loops

Loops are a programming powerhouse, allowing you to iterate through sets of data or perform repetitive tasks with minimal code. You’ll learn how to harness loops in VBA.

8. Handling Macro Errors

Every programmer faces errors. This chapter equips you with the skills to tackle and manage errors that may occur in your VBA code.

9. String Manipulation

Manipulating strings is essential in VBA. You’ll discover critical string functions to enhance your text-processing capabilities.

10. Working with Dates and Times

Date and time operations are vital in many applications. You’ll become proficient in managing dates and times within your VBA programs.

11. Understanding Events

Events are the triggers that initiate VBA code execution. Learn how user actions can activate your VBA macros.

12. Grasping Arrays

Arrays allow you to group variables. This chapter shows you how to work with arrays, accessing specific elements by using the array name and index number.

13. Functions and Subs in VBA

Explore the difference between functions and subs in VBA. Functions can return values, while subs perform actions without returning values.

14. The Application Object

The Application object is the master of all objects in Excel. It grants access to a multitude of Excel-related options. Get ready to unlock its potential.

15. Creating ActiveX Controls

Learn how to create ActiveX controls, including command buttons, text boxes, and list boxes, to enhance your VBA applications.

16. Building a VBA Userform

Discover the art of creating a VBA Userform, a valuable tool for enhancing the user experience in your VBA applications.

Our journey into the world of VBA Macros has just begun. Stay tuned for an exciting and informative series that will guide you through the ins and outs of VBA programming in Excel and beyond.

Creating Your First Macro

we ventured into the practical aspects of VBA Macros. Here are the essential learnings:

Creating Macros with VBA

VBA empowers you to automate tasks in Excel. Chapter 2 focused on creating a simple macro that executes after clicking a command button.

Turning on the Developer Tab

We initiated our practical journey by enabling the Developer tab, a critical step in working with VBA.

Turn on the Developer Tab

Adding a Command Button

You learned how to insert a command button, a pivotal tool for triggering VBA macros.

View Code

Assigning a Macro

The chapter guided you through the process of assigning a macro to a command button, setting your VBA macro in motion.

Visual Basic Editor

Creating Your First Macro

With practical steps, you created your first macro in Excel, typing “Hello” into Cell A1.

Our comprehensive guide to VBA Macros has just begun. Stay tuned for upcoming chapters where we’ll explore range selection, formatting, copy/paste techniques, and much more in Excel.

Basics of VBA / Macros Chapter – 82 (Userform Part-3)

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:

Currency Converter in Excel VBA

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.

Userform Screen Setup in Excel VBA

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

First, the two list boxes are filled. Next, The US Dollar currency is set as default in the first list box and the EURO currency is 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 j
Next i

End Sub

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.

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:

Currency Converter Result

Basics of VBA / Macros Chapter – 83 (Userform Part-4)

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:

Progress Indicator in Excel VBA

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.

Userform Screen Setup in Excel VBA

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

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 pctCompl
Next i

End Sub

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

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:

Progress Indicator Result

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.

Basics of VBA / Macros Chapter – 84 (Userform Part-5)

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:

Multiple List Box Selections in Excel VBA

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.

Userform Screen Setup in Excel VBA

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

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

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 If
Next i

CheckBox2.Value = False

End Sub

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

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 i
End If

If CheckBox1.Value = False Then
For i = 0 To ListBox1.ListCount – 1
ListBox1.Selected(i) = False
Next i
End If

End Sub

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.

Basics of VBA / Macros Chapter – 85 (Userform Part-6)

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:

Multicolumn Combo Box in Excel VBA

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.

Userform Screen Setup in Excel VBA

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

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

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.

Multicolumn Combo Box Result

Multicolumn Combo Box Result

Basics of VBA / Macros Chapter – 86 (Userform Part-7)

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.

Dependent Combo Boxes in Excel VBA

The user selects Sports from a drop-down list. As a result, the user can select a sport from a second drop-down list.

Dependent Combo Boxes in Excel VBA

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.

Userform Screen Setup in Excel VBA

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

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

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:

Dependent Combo Boxes in Excel VBA