0% found this document useful (0 votes)
5 views

Excel VBA (4)

The document provides an introduction to Excel VBA, detailing its workspace, macro creation, and various programming concepts. It covers topics such as recording macros, using dot notation, event procedures, and referencing cells with properties like Offset and Resize. The document serves as a comprehensive guide for industrial engineers to automate tasks and enhance productivity in Excel using VBA.

Uploaded by

kkirbiyik7
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Excel VBA (4)

The document provides an introduction to Excel VBA, detailing its workspace, macro creation, and various programming concepts. It covers topics such as recording macros, using dot notation, event procedures, and referencing cells with properties like Offset and Resize. The document serves as a comprehensive guide for industrial engineers to automate tasks and enhance productivity in Excel using VBA.

Uploaded by

kkirbiyik7
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

MS Excel VBA

INE 214 – Programming Tools for Industrial Engineers


Excel Visual Basic for Applications

Table of Contents
1 Introduction to Excel VBA...................................................................................................................... 2
1.1 Excel VBA Workspace .................................................................................................................... 2
2 Creating Macros .................................................................................................................................... 3
2.1 Recording Macros.......................................................................................................................... 4
2.2 The Dot Notation of VBA Code ...................................................................................................... 5
2.3 The With Construct ....................................................................................................................... 7
2.4 Event Procedures........................................................................................................................... 7
2.5 Creating Buttons to Activate Sub Procedures or Event Procedures .............................................. 8
2.6 Referencing Cells with Offset and Resize Properties ..................................................................... 8
2.7 Referencing and Naming Ranges ................................................................................................... 9
2.8 Conditional Formatting using VBA............................................................................................... 10
2.9 Message Box and Input Box ........................................................................................................ 10
2.10 Variables and Data Types ............................................................................................................ 11
2.11 Public and Private Variables ........................................................................................................ 12
3 Functions in VBA.................................................................................................................................. 12
3.1 Using Built-in Excel Functions and Formulas in VBA.................................................................... 12
3.2 Using VBA Math Functions .......................................................................................................... 13
3.3 Using Conversion and String Functions ....................................................................................... 13
4 Sub Procedures and Function Procedures........................................................................................... 14
4.1 Sub Procedures ............................................................................................................................ 14
4.2 Function Procedures.................................................................................................................... 14
4.3 Public and Private Procedures ..................................................................................................... 14
5 Programming Structures ..................................................................................................................... 15
5.1 If, Then......................................................................................................................................... 15
5.2 Select, Case.................................................................................................................................. 16
5.3 For Loops ..................................................................................................................................... 17
5.4 Do Loops ...................................................................................................................................... 17
6 Arrays .................................................................................................................................................. 17

1
MS Excel VBA

1 INTRODUCTION TO EXCEL VBA


Excel VBA (Visual Basic for Applications) is a powerful tool that allows users to automate repetitive
tasks, create custom functions, and enhance Excel's capabilities. Excel VBA allows the user to be more
productive by automating time consuming tasks that are frequently performed while analyzing data,
creating charts, or reporting results. The pieces of VBA code that perform specific tasks are called macros.

The following instructions are based on the Excel 2013 version (v15.0); however, the concepts
explained are very similar in earlier versions. More information specific to earlier versions can be found
in the Excel Help files. Excel files created using earlier versions can be converted to the latest version by
selecting the Convert command at the File tab>>Info page.

Recall that Excel workbooks that are macro-enabled are saved as *.xlsm files.

1.1 EXCEL VBA WORKSPACE


First of all, to use VBA, you need to enable the Developer tab by going to the File
tab>>Options>>Customize Ribbon and select the Developer tab to show in the ribbon. In Excel 2007, click
the Office button>>Excel Options>>Popular and check the box for “Show Developer tab in the Ribbon”.
With the Developer tab, you can view the VBA Editor, run macros, record macros, or insert form objects
on your spreadsheets.

To view the VBA Editor, where all macros are written and saved, you can select View Code from the
Developer tab>>Controls group or press Alt+F11. You will see a screen as in Figure 1.

Figure 1. VBA Editor

On the left of the VBA Editor screen, there is a Project Explorer area named Project - VBA Project
where all the objects in your project are listed. There is an object for each sheet on your workbook (named

2
MS Excel VBA

Sheet1, Sheet2, Sheet3, etc.) and an object for the current workbook (named ThisWorkbook). Another
object that is not initially visible before you create any macros is the Personal Macro Workbook. You will
start seeing this object in the list as soon as you record a macro and the Personal Workbook can be used
to store all macros that you use frequently so that these macros are available globally for all workbooks
that you will open. However, the macros recorded on any other workbook would be specific to that
workbook. Below the Project Explorer, you will see the Properties window with detailed information
about the selected project part.

The main blank area is where the coding screens will be opened and VBA code will be written on
these coding sheets. If you double click on an object from the list on the left, the coding screen for that
object will be opened on the grey area. Any macros written on a white screen for an object will only
affect the corresponding worksheet.

2 CREATING MACROS
As a classic beginner example, let us first greet the world using Excel VBA as shown in Figure 2! Let
us understand the syntax of this code:

• Sub is used to indicate a Subroutine which is a piece of code that performs a specific task. For
every Sub, there should be an End Sub to indicate where the Subroutine ends. (Note that VBA
automatically adds End Sub when you type the first line to create a Sub and press Enter.)
• Every Sub has a name followed by a pair of parentheses. There is a space between the Sub
declaration and the name. Macro names must start with a letter and cannot contain any spaces,
any periods (.), or any of the characters #, $, %, &, ! in them. You can use underscore (_) instead
of spaces such as Sub Hello_World().
• The code for your macro is added in between the Sub and End Sub. In this example, we are
displaying a message box (indicated by MsgBox) that displays the text “Hello VBA World!”.
• Once you add your code, you can run it by clicking the green triangle at the
toolbar on top of the editor or by selecting the Run Sub/User Form at the Run menu or by
pressing F5. You will see a screen as the one on the right below.

Figure 2. HelloWorld

Next, we will describe how macros can be recorded and run.

3
MS Excel VBA

2.1 RECORDING MACROS


You can watch Excel record macros as you perform the tasks on the worksheets. It is best to
display the Excel sheet and the VBA Editor side by side to see how a macro is recorded.

Let us create a list of letter grades and the numeric grades that correspond to each letter grade.
To record a macro that will repeat this task:

• Click Record Macro button at the Developer tab>>Code


group.

• Type the name of the macro and select Store macro in


Personal Macro Workbook.

• Type the letter grades and the


numeric grades in cell range A1:B8.

• Click Stop Recording button at the Developer tab>>Code


group.

• You can view the macro in the VBA Editor in a module created for the Personal Workbook.
Modules are containers of procedures.

Note that the cell selected is called ActiveCell in VBA and each time a new cell or a range of cells
is selected, a statement like Range(“B1”).Select appears.

The recorded macros usually have too much code, most of which can be unnecessary since they
generally represent default settings that you do not want to change. Therefore, your own macro codes
would be shorter if you type only the necessary manipulations.

Next, we discuss the dot notation used in Excel VBA.

4
MS Excel VBA

2.2 THE DOT NOTATION OF VBA CODE


Excel VBA uses the hierarchical dot notation to represent objects, properties, methods, and arguments
(or parameters).

• Properties are descriptions of an object.


• Values are descriptions of a particular property.
• Methods are actions performed on an object.
• Arguments are elements of a method statement.

The notation usually starts with an object and a property of the object follows after a dot.

Example: ActiveCell.Font.Bold = True


Active Cell is an object, Font is its property, Bold is the property of Font and it is set to value
True to make the contents of the ActiveCell bold.

Example: Worksheets(1).Range(“A1”)
Worksheets(1) is an object that refers to the worksheet 1 in the current workbook, Range is a
property of the Worksheets object, and Range property refers to cell A1.

Example: Range(“A1:B8”)
Range property refers to the cell range A1:B8.

Example: Worksheets.Add After := Worksheets(2)


Worksheets is an object, Add is a method, After is a parameter of the Add method separated
by a space, and the value of the parameter After is set to be Worksheets(2) which indicates
worksheet 2 in the current workbook.
Example: Worksheets(2).Range(“A1:B8”).Select
Select method is used to select the cell range A1:B8 in worksheet 2.

The hierarchy of Excel objects can be summarized as follows:

Application Workbook Worksheet Range


In order to find appropriate methods and properties for each object, the library of VBA and Excel can be
used. The Object Browser lists all properties and methods in VBA and can be viewed by selecting the
Object Browser from the View tab. In the Object Browser, the following terms are used. (In VBA window,
View > Object Browser)

• Libraries are collections of VBA and Excel object classes.


• Classes are groups of related objects.
• Members are properties, methods, and constants of a selected class of objects.

5
MS Excel VBA

More examples of the objects, properties, methods, and arguments:

VBA code Object Property Method Arguments


Workbooks(“WorkbookName”).Activate
Workbooks(“WorkbookName”) Activate
Worksheets(“WorksheetName”).Visible = True
Worksheets(“WorksheetName”) Visible (True or
False)
Selection.AutoFilter Field:=5, Criteria1:=“FilterCriteria”
Selection AutoFilter Field
Criteria
Selection.Sort Key1:=Range(“C2”), Order1:=xlAscending
Selection Sort Key
Order
Worksheets(“WorksheetName”).Name = “NewWorksheetName”
Worksheets(“WorksheetName”) Name
Range(“A1:C10”).Copy
Range(“A1:C10”) Copy
Range(“A1:C10”).PasteSpecial xlPasteAll
Range(“A1:C10”) PasteSpecial xlPasteAll
xlPasteFormats
xlPasteValues
Range(“A1:C10”).Cut Destination:=Range(“A3”)
Range(“A1:C10”). Cut Destination
Range(“A1:C10”).Select
Range(“A1:C10”) Select
Range(“A1:C10”).Interior.Color = vbRed
Range(“A1:C10”) Interior
Sub property:
Color
Range(“A1:C10”).Interior.ColorIndex = 3
Range(“A1:C10”) Interior
Sub property:
ColorIndex
Range(“A1:C10”).Interior.Pattern= xlChecker
Range(“A1:C10”) Interior
Sub property:
Pattern
Range(“A1:C10”).Font.Color = RGB(0, 255, 255)
Range(“A1:C10”) Font
Sub property:
Color
Range(“A1:C10”).BorderAround LineStyle:=xlSolid, Weight:=xlThick, Color:=vbBlue
Range(“A1:C10”) BorderAround LineStyle
Weight
Color

6
MS Excel VBA

2.3 THE WITH CONSTRUCT


Instead of repeating the object name when you change several properties of that object, you can use
the simple With construct to list all properties. The With construct is used as follows.

With ObjectName
.property or
.method
End With

Initially you may have several lines of code such as:

Range(“A1:C8”).Interior.Color = vbRed
Range(“A1:C8”).Font.Bold = True
Range(“A1:C8”).Font.Name = “Arial” To apply that please do not forget:
Range(“A1:C8”).Borders(xlEdgeBottom).LineStyle = xlDash -To fix quotation marks with "
-To write your code
You can simplify your code as: between Sub ()
....
With Range(“A1:C8”) End Sub
.Interior.Color = vbRed
.Font.Bold = True
.Font.Name = “Arial”
.Borders(xlEdgeBottom).LineStyle = xlDash
End With

2.4 EVENT PROCEDURES


Events are actions that occur in the Excel window and are linked to a set of actions in VBA code. Event
Procedures are used to connect events to code. Event procedures include Open, Click, Change, and
Activate. For each Excel object in the Project Explorer, there is a list of associated objects in a dropdown
menu in the upper-left hand corner of the Code Window. When an object from this list is selected, you
can see corresponding events in the drop-down menu in the upper right hand corner of the Code Window.
Each object in Excel has its own corresponding list of event procedures as shown for the Worksheet object
in Figure 3.

Figure 3. Event procedures for the Worksheet object

7
MS Excel VBA

2.5 CREATING BUTTONS TO ACTIVATE SUB PROCEDURES OR EVENT PROCEDURES


For ease of use, we can add buttons to Excel sheets that will run a macro. To create a button:

• Go to the Developer tab>>Controls group>>Insert


button and select the Button control.
• Select the area to place the rectangular button on the
spreadsheet.
• Assign Macro dialog box appears, choose a macro from
the list.
• The button will be created at the specified location on
the sheet. You can rename the button by right clicking
and selecting Edit Text.

2.6 REFERENCING CELLS WITH OFFSET AND RESIZE PROPERTIES


To reference cells, Offset can be used with Range to change the range selection. Offset can move the
selection in all four directions by setting the number of rows and the number of columns to shift the
initial selection.

Statement Range reference


Range(“A1”).Offset(RowOffSet:=1, ColumnOffset:=1) B2
Range(“A1”).Offset(1, 0) A2
Range(“A1”).Offset(0, 1) B1
Range(“B2”).Offset(-1, 0) B1
Range(“B2”).Offset(0, -1) A2
Range(“B2”).Offset(-1, -1) A1
Range(“A1:C3”).Offset(1, 1) B2:D4
Range(Range(“A1”).Offset(1,2), Range(“A1”).Offset(5,4)) C2:E6

The Resize property changes the size of the selected range by keeping the given starting position.

Statement Range reference


Range("A1”).Resize(RowSize:=2, ColumnSize:=2) A1:B2
Range(“A1”).Resize(3) A1:A3
Range(“A1”).Resize(, 3) A1:C1
Range(“A1:A3”).Resize(, 2) A1:B3
Range(“D1”).Offset(, -1).Resize(, 3) C1:E1

8
MS Excel VBA

2.7 REFERENCING AND NAMING RANGES


Cells property can be used to reference cells like the Offset property, but the specified range is considered
to be in the (1, 1) position instead of (0, 0). Therefore the following two references to cell A3 are
equivalent:

Range(“A1”).Offset(2, 0)

Range(“A1”).Cells(3,1)

Columns property takes an index value to select the numbered column based on the selected range. The
following refers to the cell range D2:D5 that is the 4th column of the selected range.

Range(“A2:G5”).Columns(4)

Rows property takes an index value to select the numbered row based on the selected range. The
following refers to A3:G3 which is the 2nd row of the selected range.

Range(“A2:G5”).Rows(2)

Hidden is a sub property of Columns and Rows properties that can be used to hide or unhide
rows and columns.

Range(“A1:C10”).Columns.Hidden = True or False

Range(“A1:C10”).Rows.Hidden = True or False

EntireColumn and EntireRow are properties used to modify all the columns and rows, respectively.

Range(“A2:G5”).EntireColumn.Borders.Weight = xlThick

Range(“A2:G4”).EntireRow.Font.Italic = True

End property is used to find the end of a row or column or a range of cells, especially when the size of
the range is not known. It can take values xlDown and xlUp for columns, xlToRight and xlToLeft for rows.

Range(“A2”, Range(“A2”).End(xlDown)).Copy

Name property is used to assign names to objects and ranges can also be named for easier referencing
by name rather than selecting the range of cells.

Range(“A2”, Range(“A2”).End(xlDown)).Name = “Customers”

Then, the range name can be used whenever the specified range of cells are needed.

Range(“Customers”).Font.Size = 14

9
MS Excel VBA

2.8 CONDITIONAL FORMATTING USING VBA


The FormatConditions object associated with the Range object adds conditional formatting on selected
range of cells.

• You can use the Add method to add conditional formatting (at most three conditional formats
can be added to a specific range of cells):

Range(CellRange).FormatConditions.Add(Type, Operator, Formula)

Example: Range(“A1:A10”).FormatConditions.Add Type:=xlCellValue, Operator:=xlGreaterEqual,


Formula1:=5

o Once a conditional format is added, the properties of the FormatConditions object


(Interior, Font, Borders) should be used:

Range(CellRange).FormatConditions(Index).Property.SubProperty = Value

Example: Range(“A1:A10”). FormatConditions(1).Interior.Color = vbGreen

• You can use the Modify method to change an already defined conditional format:
Range(CellRange).FormatConditions(Index).Modify(Type, Operator, Formula)

• You can use the Delete method to delete an already defined conditional format:

Range(CellRange).FormatConditions.Delete

2.9 MESSAGE BOX AND INPUT BOX


MsgBox prints information to a dialog box to communicate with the user.

MsgBox “Text to be displayed.”

MsgBox VariableName

MsgBox “The variable value is “ & VariableName & “.”

You can add text on a new line by using vbCrLf. MsgBox “Hello World!!!”

MsgBox “The variable value ” & vbCrLf & “is “ & VariableName & “.”

MsgBox can also be used as a function:

MsgBox(prompt, [buttons], [title], [helpfile, context])

where the prompt argument is the string or variable to be


displayed, the optional buttons argument can take one of the VB
Constant values among vbOKOnly, vbOKCancel, vbYesNoCancel,
and vbYesNo (that specify which buttons to display), title is the
optional title of the MsgBox, and helpfile and context arguments
are used to guide the user.

MsgBox(“Hello World!!! Can you see me?”, vbYesNo, “Hello Message”)

10
MS Excel VBA

InputBox ask the user to enter values for variables, therefore an InputBox is always assigned to a variable,
and it has an OK and a Cancel button.

VariableName = InputBox(prompt, [title], [default], [xpos], [ypos], [helpfile, context])

The prompt and title arguments are the same as MsgBox arguments. The default argument allows you
to display a default value to the user which will be used for the associated variable if no value is entered
by the user. The xpos and ypos arguments define the position of the InputBox relative to the left and top
edges of the InputBox screen.

Dim inputResponse As Variant

inputResponse = InputBox("What is your name?",


"Name Query")

2.10 VARIABLES AND DATA TYPES


Variables are declared by using the Dim command, which stands for declaration in memory. There are
several data types that determine the values to be assigned to a variable. Multiple variables can be defined
in a single line that starts with Dim as follows.

Dim VariableName As DataType

Multiple variables can be declared in a single line separated by commas.

Dim VariableName1 As DataType1, VariableName2 As DataType2

If no data type is given for a variable, it will be assumed as a Variant which is the type of data that takes
on the last value assigned to it.

VBA is case-sensitive, therefore, the variables var1 and Var1 are treated as different variables. The usual
variable naming convention is using upper-case letters for the first letters of each word in the variable
name such as VariableName.

Data Type Properties


Variant The last value assigned
Integer Non-decimal numbers in interval [-32,768, 32,767]
Double Non-integer numbers in intervals [-1.79769E308, -4.94065E-324]
and [4.94065E-324, 1.79769E308]
String A piece of text
Boolean True or False
Used in logical statements, If-Then statements, loops
Range Value is defined by Set declaration:
Dim RangeVar As Range
Set RangeVar=Range(“A1”)
Worksheets Defines a worksheet object
Object Any object in Excel (drawing object, range, worksheet, etc.)

11
MS Excel VBA

2.11 PUBLIC AND PRIVATE VARIABLES


Public variables are accessible from any sub Private variables are accessible only in the sub
procedure in any module. procedure or module in which they are defined.

Public variables are declared using the Public Private variables are declared using the Dim
statement. statement.

Public i As Integer Dim i As Integer

3 FUNCTIONS IN VBA

3.1 USING BUILT-IN EXCEL FUNCTIONS AND FORMULAS IN VBA


The built-in Excel formulas can be used in VBA via the Range object or the Application object.

Using the Range object

Formula property of the Range object allows us to enter formulas as if we enter them in the cell starting
with an equal sign (=).

Range(“B5”).Formula = “=SUMPRODUCT(A1:A4, B1:B4)”

Formula can be applied to a range of cells as well since the formula is automatically modified for each
relative row or column of data.

Range(“B5:D5”).Formula = “=SUM(B1:B4)”

FormulaR1C1 property can also be used to enter formulas using the R1C1 notation. The following are
equivalent to the above two Formula examples.

Range(“B5”).FormulaR1C1 = “=SUMPRODUCT(R[-4]C[-1]:R[-1]C[-1], R[-4]C:R[-1]C)”

Range(“B5:D5”).FormulaR1C1 = “=SUM(R[-4]C:R[-1]C)”

Instead of applying formulas to a range of cells in the same line, AutoFill method can be used. AutoFill
method has the arguments Destination and Type. Destination is the range where you will paste the
values and Type is the kind of information you want to copy and paste (such as format, series, values).
The following copies the summation formula to cell range B5:D5.

Range(“B5”).Formula = “=SUM(B1:B4)”

Range(“B5”).AutoFill Destination:=Range(“B5:D5”), Type:=xlFillDefault

Using the Application object

The Application object’s WorksheetFunction property has subproperties such as Max, Min, Average,
and Round. These can be used as follows.

Range(“B5”).Value = Application.WorksheetFunction.Max(Range(“B1:B4”))

Range(“B6”).Value = Application.WorksheetFunction.Min(Range(“B1:B4”))

12
MS Excel VBA

Range(“B7”).Value = Application.WorksheetFunction.Average(Range(“B1:B4”))

Range(“B8”).Value = Application.WorksheetFunction.Round(Range(“B7”).Value, 2)

where the second input of the Round sub property is the number of decimal places.

3.2 USING VBA MATH FUNCTIONS


In addition to the built-in Excel functions, there are math and trigonometric functions available in VBA.
The most popular examples are listed here. Many more functions can be derived by using these available
functions.

VBA Function Description


Abs(X) absolute value of the input number
Exp(X) raise the constant e to the input power
Int(X) remove the decimal part of the double input variable and return the integer part
Log(X) calculate the natural log of the input number
Rand(X) generate a random number (of type double) between 0 and 1
Sqrt(X) calculate the square root of the input number
Sin(X) sine of the input angle in radians (always between -1 and 1)
Cos(X) cosine of the input angle in radians (always between -1 and 1)
Tan(X) tangent of the input angle in radians
Atn(X) arctangent of the input ratio (result is an angle in radians)

3.3 USING CONVERSION AND STRING FUNCTIONS


A data type can be converted to another using the conversion functions as below.

Conversion Function Description


Int(X) converts a variable to an Integer data type
CInt(2.68) = 2 (decimal number is rounded down)
CInt(“VBA 101”) = 101 (number within string is extracted)
CDbl(X) converts a variable to a Double data type
Val(X) extracts numerical value from a string
CStr(X) converts a number to a string
CStr(2.68) = “2.68”
CDate(X) converts the input to Date data type
Asc(X) converts letters to numbers using ASCII (American Standard Code for
Information Interchange) list
Asc(“a”) = 97
Chr(X) converts numbers to letters using the ASCII list
Chr(97) = “a”

String functions can be used to modify or get information about strings of text.

Upper() or Lower() converts the input string to all uppercase or to all lowercase
Len(X) determines the length of the input string

13
MS Excel VBA

4 SUB PROCEDURES AND FUNCTION PROCEDURES

4.1 SUB PROCEDURES


An entire list of actions can be divided into smaller parts using sub procedures to improve the efficiency
of the program. A hierarchy of sub procedures can be obtained by calling other subs that perform parts
of the actions from a main sub procedure. The Call command is used to call (run) the sub procedures and
parentheses are not needed after the sub procedure names.

Sub Main()
Call GetData
Call CalculateStatistics
Call DisplayResults
End Sub
If the task performed by a sub procedure depends on variable values, we can pass variables to a sub
procedure by adding the variable names in parentheses when calling a sub procedure.

Dim NewRange As Range, NewColor As String


Call FormatRanges(NewRange, NewColor) Or
Sub FormatRange(r,c) Sub FormatRange(NewRange ByVal, NewColor ByVal)
r.Interior.Color = c NewRange.Interior.Color = NewColor
End Sub End Sub

4.2 FUNCTION PROCEDURES


Function procedures are sub procedures that can pass variables and return values. When calling function
procedures, the variables used as input need to be specified.

Call FunctionName(A,B) Or x=FunctionName(A,B)


Function FunctionName(a,b)
…actions…
FunctionName=value
End Function
The Exit Sub and Exit Function statements can be used to stop executing the sub procedure or the
function procedure.

4.3 PUBLIC AND PRIVATE PROCEDURES


Public procedures can be called from any other Private procedures can be called from only the
sub procedure in any module. other sub procedures in the same module. They
do not appear in the macro list either.
Public procedures can be declared with or Private procedures are declared using the
without the Public statement. Private statement.
Public Sub Sort() Private Sub SortSpecial()
… …
End Sub End Sub

14
MS Excel VBA

5 PROGRAMMING STRUCTURES
We can control how our programs will run by using appropriate programming structures.

5.1 IF, THEN


Similar to the IF function of Excel, when If, Then statement is used, a set of actions is performed if the
specified condition is met and another set of actions are performed otherwise.

If condition Then If condition Then


…actions… …actions…
End If Else
…actions2…
End If
For nested if statements, Elseif statement is used.

If Age < 18 Then


MsgBox “You need to wait until you are 18 to get a driver’s license!”
ElseIf Age <= 30 Then
MsgBox “You are at least 18 and at most 30 years old, best time to get a driver’s license!”
ElseIf Age <=50 Then
MsgBox ”You are at least 31 and at most 50 years old, but it’s not too late to get a driver’s license.”
Else
MsgBox ”You are above 50, please check with your doctor before you get a driver’s license.”
End If

Multiple conditions can be checked by using the logical operators And and Or.

If condition1 And condition2 And condition3 Then If condition1 Or condition2 Or condition3 Then
…actions… …actions…
Else Else
…actions2… …actions2…
End If End If

If Age < 18 Or Age > 70 Then


MsgBox “Sorry we do not issue driver’s license at your age.”
ElseIf Age > 50 And Age <= 70 Then
MsgBox “You need to bring your health record for a driver’s license to be issued.”
Else
MsgBox “You do not need to bring any additional documents.”
End If

15
MS Excel VBA

5.2 SELECT, CASE


The Select, Case statement lists possible situations and the corresponding actions to be performed.

Select Case Age


Case 0 To 17
MsgBox “You need to wait until you are 18 to get a driver’s license!”
Case 18 To 30
MsgBox “You are at least 18 and at most 30 years old, best time to get a driver’s license!”
Case 31 To 50
MsgBox ”You are at least 31 and at most 50 years old, but it’s not too late to get a driver’s
license.”
Case Else
MsgBox ”You are above 50, please check with your doctor before you get a driver’s license.”
End Select

Select Player1
Case “Rock”
If Player2 = “Rock”
MsgBox “It’s a tie.”
ElseIf Player2 = “Paper”
MsgBox “You lose.”
Else
MsgBox “You win!”
End If
Case “Paper”
If Player2 = “Rock”
MsgBox “You win!”
ElseIf Player2 = “Paper”
MsgBox “It’s a tie.”
Else
MsgBox “You lose”
End If
Case “Scissors”
If Player2 = “Rock”
MsgBox “You lose.”
ElseIf Player2 = “Paper”
MsgBox “You win!”
Else
MsgBox “It’s a tie.”
End If
End Select

16
MS Excel VBA

5.3 FOR LOOPS


We can use the For, Next and For Each, Next loops to repeat the same actions for a set of different values.
By default, the index used is incremented by 1 in each iteration, however, the increments can be defined
using the Step parameter.

For i = 1 to N For i = 1 to N Step 2


…actions… …actions…
Next i Next i
i = 1, 2, 3, 4, …, N i = 1, 3, 5, 7, …, N-N(mod2)

For Each ws In ActiveWorkbook.Worksheets

count = count +1

Next

5.4 DO LOOPS
We can use the Do, While and Do, Until loops to repeat a set of actions while or until a condition is met.
The order of checking the conditions and performing the actions depends on whether the While and Until
statements are typed before or after the actions.

Do While count <= 5 Do Until count = 5


…actions… …actions…
count = count +1 count = count +1
Loop Loop

Do Do
…actions… …actions…
count = count +1 count = count +1
Loop While count <= 5 Loop Until count = 5

If the initial value of count is 0 before entering the loops, the Do, While loop above ends with count = 6,
but the Do, Until loop above ends with count = 5.

The Exit For and Exit Do statements can be used to stop executing the corresponding For or Do loop.

6 ARRAYS
If series of data needs to be stored, Arrays should be used instead of an individual variable to be defined
for each item. An array stores values of the same data type and each item in the array is referred to by
using its elements. Much like variables, arrays are defined using the Dim, Public, or Private declarations.
The size of the array is specified in parentheses that follows the array name. Note that the default indexing
of array elements starts from 0 instead of 1, therefore, 1 less than the actual size of the array is input in

17
MS Excel VBA

parentheses for defining the array or you can specify the index range in parentheses as (1 To N). If you
type Option Base 1 at the top of your module, the indexing will start at 1.

Dim Seasons(3) As String Dim Seasons(1 to 4) As String


Seasons = Array(“Fall”, “Winter”, “Spring”,
Or
“Summer”)
Seasons(1) is “Winter” Option Base 1
Dim Seasons(4) As String
Seasons = Array(“Fall”, “Winter”, “Spring”,
“Summer”)
Seasons(2) is “Winter”

For entering data into arrays, For, Next loop can be used as follows.

For i = 1 to 5
ArrayName(i) = 2^i
Next i

Multi-dimensional arrays are defined by specifying the size of the array in each dimension in parentheses.
If there are three newspapers for which there is demand data on each day of the week, you can define an
array of demand values as follows.

Dim WeeklyDemand(3, 7) As Integer

If the size of the array is not definite, it can be defined without the size information and once a temporary
size is known, ReDim statement is used to set the array size. Then, items can be added to the array.

Dim UserInput() As Currency


UserInputSize = InputBox(“How many prices will you enter as input?”)
ReDim UserInput(1 to UserInputSize) As Currency
For i = 1 to UserInputSize
UserInput(i) = InputBox(“Enter the price for item ” & i)
Next i

If additional data will be entered ReDim Preserve statement can be used to keep all previously entered
data and then new ones can be added to the end of the array.

NewUserInputSize = InputBox(“How many more prices will you enter as input?”)


ReDim Preserve UserInput(1 to UserInputSize+NewUserInputSize) As Currency
For i = UserInputSize 1 to UserInputSize+NewUserInputSize
UserInput(i) = InputBox(“Enter the price for item ” & i)
Next i

18

You might also like