Excel VBA (4)
Excel VBA (4)
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
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.
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.
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
3
MS Excel VBA
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:
• 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.
4
MS Excel VBA
The notation usually starts with an object and a property of the object follows after a dot.
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.
5
MS Excel VBA
6
MS Excel VBA
With ObjectName
.property or
.method
End With
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
7
MS Excel VBA
The Resize property changes the size of the selected range by keeping the given starting position.
8
MS Excel VBA
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.
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.
Then, the range name can be used whenever the specified range of cells are needed.
Range(“Customers”).Font.Size = 14
9
MS Excel VBA
• 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(Index).Property.SubProperty = Value
• 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
MsgBox VariableName
You can add text on a new line by using vbCrLf. MsgBox “Hello World!!!”
MsgBox “The variable value ” & vbCrLf & “is “ & VariableName & “.”
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.
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.
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.
11
MS Excel VBA
Public variables are declared using the Public Private variables are declared using the Dim
statement. statement.
3 FUNCTIONS IN VBA
Formula property of the Range object allows us to enter formulas as if we enter them in the cell starting
with an equal sign (=).
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: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)”
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.
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
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.
14
MS Excel VBA
5 PROGRAMMING STRUCTURES
We can control how our programs will run by using appropriate programming structures.
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
15
MS Excel VBA
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
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 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.
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.
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.
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.
18