Excel VBA Course Slides
Excel VBA Course Slides
With Leila Gharani (Microsoft Excel MVP & Udemy bestselling Instructor)
2 Download the Excel files and practice along. Don’t miss the quizzes and the activities at
the end of the sections.
3 Activate the developer tab in Excel by going to Files / Options / Customize Ribbon and
put a tick-mark beside Developer.
Make sure you save your files as macro-enabled files and activate macros when looking
4 at the completed versions of the Workbooks.
5 Please close all other Workbooks when working with the course files.
The Workbooks & tools are created for Excel on Windows only.
2
Setting Expectations
1 I use Excel 2016 – Office 365.
2 The course is designed to help you learn VBA (if you’re a complete beginner) & improve your existing
VBA knowledge (if you already have some familiarity).
3 The tools created inside the course are meant to demonstrate how the different concepts can be
brought together. If you are planning to use these, please fully test and update the VBA code
accordingly.
Even though this is a VBA course, I do use more advanced Excel formulas when creating the
4 Regional sales reporting tool and the invoice generation tool. I share the links to videos that cover
these techniques. I do this to show you the advantages of combining Excel functionality with VBA
code.
Remember: You have life-time access to the course. Go through the lectures at a pace
that’s right for you. Do revisit watched lectures to make sure concepts are clear.
3
COURSE REVIEW & RATING
Ratings are very helpful so that the course can be discovered by other students.
I really appreciate it if you can take a few seconds to leave a rating (whenever you feel the time is right).
1 Select My Courses
4
1 Become familiar with Macros, VBE & the Object Model
How to Reference Ranges, Worksheets & Workbooks
Variables, Data Types
Working with Collections & Making Decisions
Useful VBA Functions
6
How to Record a Macro
1 Do a test run before you press record
2 a)
b)
Click on the record macro button at the bottom left-hand side
Use shortcut key Alt + T + M + R
c) Go to Developer tab – Record macro
d) Go to View tab – Record macro
3 Name your Macro, assign a shortcut key & decide where to store it
(workbook or personal macro workbook)
7
Insert Procedures,
Switch to Activate Editing options from
Visual
Modules & Userforms
Excel View / Toolbars / Edit
from Insert menu
Editor
Code is written here
(VBE)
Workbooks, Sheets
& VBA code view
4 Add the Macro to the Quick Access Toolbar (For active workbook only)
5 Add the Macro to the Ribbon – Recommended for “general” macros that are saved in the
personal macro workbook
6 Insert any shape or image and assign the macro to it (Right-mouse click, Assign Macro)
7 Insert a Form Control button from Developer tab, Insert, Form Controls 9
Change in Comments to Notes
Working with comments & notes
In Office 365 “comments” have been renamed to “notes”.
VBA syntax has not changed except we have new syntax for the new comments feature.
10
The Object Model
Visual Basic Essential: Understanding the “dot” in code
11
Visual Basic for Applications (VBA)
Working with VBA (Macro) code
# These objects have code words so you can easily refer to them
12
VB Basics & Color Guidelines
Most used VBA Procedure is the Sub Procedure
This consists of a set of commands the code should execute
13
VBE Keyboard Shortcuts
Description Key
Indent Code Tab
Remove Indent from Code Shift + Tab
Run project F5
Toggle breakpoint F9
14
The Object Model
# VBA is Object Oriented.
Before you perform any actions you need to specify what object to perform on
Home
District
City
15
Excel’s Object Model
Application
Workbooks (Workbook)
Worksheets (Worksheet)
Range
Examples
Application.Workbooks(“Name”).Worksheets(“WSName”).Range(“A1”)
Application.ThisWorkbook.Worksheets(“WSName”).Range(“A1”)
Worksheets(“WSName”).Range(“A1”) assumes active workbook
17
Property Details
Some Properties don’t have details
Range(“A1”).Address Range(“A1”).Value
18
Property Type: Read-only or Write?
Range(“A10”).Address Read-only
Examples
Range(“A1”).Value = ActiveCell.Address
Range(“A1”).Interior.Color = vbRed
Range(“A1”).Font.Color = vbBlue
19
Methods in VBA
Method is what an object does
An Analogy
20
Methods Can Have Arguments
Range(“A2”).Clear No further arguments
Examples
Range("A2").Delete xlShiftToLeft
Range("A3").Copy Range("B3")
Range("C3").PasteSpecial xlPasteValues
Sheet1.Copy After:=Sheet3
Sheet1.Copy , Sheet2 21
Find the Correct Property & Method
It’s impossible to remember everything…
Use the Macro Recorder to get object names, properties and methods
F1 Press F1 when on an object, property or method to get help for the MSDN
Microsoft Help Site
Use IntelliSense – Let VBA suggest the right properties & methods. Check options
from Tools / Options
Use the Immediate Window to query (e.g. color codes) or test code
2 You don’t need to select objects to manipulate them. The macro recorder “selects” but to
write code, it’s more efficient not to refer directly to objects & properties (exceptions
apply).
3 Objects have specific properties & methods.
6 To find the correct object, property or method you can record macros, use the object library
(F2), use MSDN help (F1), Intellisense, internet & immediate window to query and test code.
23
1 Become familiar with Macros, VBE & the Object Model
How to Reference Ranges, Worksheets & Workbooks
Variables, Data Types
Working with Collections & Making Decisions
Useful VBA Functions
25
Different Methods to Write to Cells
Using Rows, Columns & Range referencing
Range("A4,C4") = "4th"
Range("A5", "C5") = "5th"
Range("A" & 6, "C" & 6) = "6th" Range(Cells(6, 1), Cells(6, 3)).Value = "6th"
Range("A4:C7").Cells(4, 2).Value = "7th"
27
Code Execution Description (Click here for more) Type
Value Show the underlying value in a cell. This is the default property of the range object. Read / Write
Cells Returns a cell or range of cells within a range object Read / Write
Most End Returns the last cell of the range. Similar to Ctrl + ↓ or ↑ or → or ← Read-only
Offset Returns a new range based on offset row & column arguments Read / Write
Useful Count Returns the number of cells in a range. Read-only
Range Column / Row Returns the column / row number of a range. If you select more than one cell, column /
row returns the first occurrence in the range.
Read-only
Properties CurrentRegion Used with other properties such as .address returns the range of data Read-only
EntireColumn / Returns a range object that represents the entire row or column Read-only
EntireRow
As found in my
Resize Changes the size of the range by defining the rows & columns for resizing
projects
Address Shows the range address including the $ signs. Read-only
Font Returns a font object that has other properties (e.g. bold) Read / Write
Interior Used with other properties such as .Color property to set colors Read / Write
Formula Places a formula in a cell. To make sure your VBA code is compatible with other Read / Write
languages of Excel, your VBA formulas should use the English syntax. You can record
these with the macro recorder. The macro recorder uses FormulaR1C1 syntax. If
you’d like to have formulas in your language of Excel, you need to use FormulaLocal.
NumberFormat Define Number format (uses English version) Read / Write
Text Returns the data as string & includes formatting. Read-only
HasFormula Returns True, False or Null if the range has a mix Read-only
28
Code Execution Description (Click here for more) Type
Copy This is a practical method because it has paste destination as its
argument. This means you just need one line of code.
Most Useful PasteSpecial Allows usage of Excel’s Paste Special options. To use more than one
option, repeat the line of code with the new option.
Clear Deletes contents and cell formatting in a specified range.
Range
Delete Delete the cells and shifts the cell around the area to fill up the
Methods deleted range. The delete method uses an argument to define how to
shift the cells. Select XLToLeft or XLUp.
SpecialCells Returns a range that matches the specified cell types. This method
As found in my has 2 arguments. XlCellType is required (such as cells with formulas or
projects comments) and an optional argument to define more detail if constant
and formula cell type is used in the first argument.
Sort Sorts a range of values
PrintOut Also a method of the worksheet object
Select Used by the macro recorder to select a cell but when writing VBA, it is
not necessary to select objects. Code is faster without selecting.
29
4 Methods to Find the Last Row
In these examples the results are written to a cell. Later we will store these in variables.
31
How to Best Reference Worksheets
Use the code name of the sheet (give your own code name in the property window)
shDest.Range("A3").Value
2 advantages
• User can be free to change the tab name
• IntelliSense works perfectly with code names (doesn’t work with ActiveSheet
because ActiveSheet could also be a chart sheet…)
ActiveSheet .Range("A3").Value
32
How to Best Reference Workbooks
Required if more Workbooks need to be referenced
Use the Workbooks collection and use the name of the workbook. The
workbook needs to be open, otherwise you need to use the Open statement first.
Workbooks (“YourWorkBookName.xlsx”)
ActiveWorkBook
Make sure the correct workbook is active
Workbooks (1)
The following is risky as it depends on the order the workbooks have been
opened
33
Key Takeaways: Referencing Ranges
1 Different methods to reference cells
Use Range(“A1”) style to reference a single cell.
Range(“A1”, “C1”) or Range (“A1:C1”) for many cells.
Use the Cells or Offset property
Use the Code Name of the WorkSheets to reference worksheets – alternatively use the
4 worksheet names
5 Use ThisWorkBook property to reference the workbook the macro is in. For other
Workbooks use the workbooks collection.
34
1 Become familiar with Macros, VBE & the Object Model
How to Reference Ranges, Worksheets & Workbooks
Variables, Data Types
Working with Collections & Making Decisions
Useful VBA Functions
36
Role of Assignment
This is an assignment statement:
Range("A1").Value = Date
Equal sign does not mean equality here. It’s used to assign the result of the
right-hand side to the left-hand side.
Variables help memorize the value on the right-hand side for you, and allow you
to re-use them in your code.
37
What are Variables?
# Variables are nick-names that store a value
myTitle = Range(“A1”).value
# Names are assigned with the equal sign
If you change the title to cell “B1”, you just have to update the
myTitle = Range(“A1”).value myTitle reference once in the code instead of every single place the
reference to “A1” is made.
38
Data Types for Variables
Variables can accommodate different data types
2 A group of similar variables that has one name can be declared as an Array
Dim myMonth(1 To 12) As String
3 If you need to refer to a value that never changes, you can use Constants
Const myScenario As String = “Actual” Const ProfitCen As Long = 9999
40
Using Object Variables
Set Statement in VBA
All “usual” VBA assignments are actually done with the LET statement. However
this is an optional keyword. That’s why it’s usually not used. In case you come
across it, you know what it does.
LastRow = Rows.Count– is the same as:
Let LastRow = Rows.Count
41
Variable Scope
Is the variable reusable in other procedures?
2 Pick the data type which uses the least bytes but can still handle the data you want to
store in memory for example
Byte: worksheet numbers, months, column headers (smaller data sets)
Long: To loop through rows
Integer: to loop through smaller data sets – e.g. master data
Double: Decimals, very large numbers and numbers where precision is required
3 Think about the scope of your variables. Procedure, Module or Project? Declare these
accordingly.
Use the SET statement to assign variables to objects. Data type assignments do not need a
4 statement but they could use the optional keyword “LET”.
43
1 Become familiar with Macros, VBE & the Object Model
How to Reference Ranges, Worksheets & Workbooks
Variables, Data Types
Working with Collections & Making Decisions
Useful VBA Functions
45
With…End With for Easier coding
The benefits of the With…End With construct are:
Faster code writing
Easier code maintenance
Faster code execution The less dots you have, the
faster your code will run.
Before
Set myRange = Range("A10", "A" & Cells(Rows.Count, 1).End(xlUp).Row)
myRange.Font .Name = “Arial”
myRange.Font.Size = 12
myRange.Font.Bold = True
After
Set myRange = Range("A10", "A" & Cells(Rows.Count, 1).End(xlUp).Row)
With myRange.Font
.Name = “Arial”
.Size = 12
.Bold = True
End With
46
For…Each to Loop Through Collections
Looping through Worksheets, Ranges etc. in One Go
VBA provides an easy method to loop through a collection of similar objects. For example:
Execute code for all Worksheets in a Workbook
Follow instructions for all Cells inside a Range
Run code for each Comment inside the Worksheet Comments collection
Dim Sh As Worksheet
For Each Sh In ThisWorkbook.Worksheets
Sh.Protect "test“
Next Sh
47
IF…Then Statements for Conditional Outcomes
Decide which way your code should run
IF…Then…ElseIf…Else
Dim Sh As Worksheet
For Each Sh In ThisWorkbook.Worksheets
Simple IF: 1 Line If Sh.Name = "Purpose" Then
If Range("B3").Value <> "" Then Range("C3").Value = Range("B3").Value 'don't allow formatting etc...
Sh.Protect " test"
ElseIf Sh.CodeName = "shWith" Then
'protect without password
Simple IF: More Lines Sh.Protect
Else
If Range("B3").Value <> "" Then
'allow formatting for all other sheets
Range("C3").Value = Range("B3").Value
Sh.Protect "test", , , , , True, True, True
End If
End If
Next Sh
48
Select Case, as Alternative for Many IFs
In case your IF..Then construct gets too complex
49
Goto Statement to Change Program Flow
You can skip code lines with the Goto Statement. Why would you want this?
Mainly for error handling
Execute a different part of code depending on a condition
To use GoTo
Type the name of the label with colon (or number without colon)
You might need to Exit sub before the label if you have a message
box or another VBA statement
Sub Simple_GoTo ()
Range("D3").Value = ""
If IsError(Range("B3")) Then GoTo GetOut Use this mainly for Error
Range("C3").Value = Range("B3").Value
Exit Sub Handling. Otherwise your code
GetOut: can become too confusing to
Range("D3").Value = "You have an error in the cell“
End Sub understand.
50
Key Takeaways: Collections & Decisions
1 Use With … End With Construct
To optimize code writing and execution
51
1 Become familiar with Macros, VBE & the Object Model
How to Reference Ranges, Worksheets & Workbooks
Variables, Data Types
Working with Collections & Making Decisions
Useful VBA Functions
53
VBA & Worksheet Functions
Similar to worksheet formulas…
54
Text handling Description
InStr Returns the position of one string within another
Left Returns the left hand side of a string based on specified number of characters
Right Returns the right hand side of a string based on specified number of characters
Text Handling
(String manipulation) Space Returns a string the contains spaces
Constants Description
VbNewLine Creates a new line in message box
Functions
Minute Returns the minute of a time value
Month Returns the month of a date
MonthName Returns a string for the month of a date (abbreviation possible)
Date Handling
Now Returns the current date and time
Second Returns the seconds portion of time
Time Returns the current system time
Timer Returns the number of seconds since midnight (good for adding a timer
in code)
Weekday Returns a number for the day of the week
WeekdayName Returns a string for the day of the week
Year Returns the year of a date
56
Formatting & Converting Description
CDate Converts expression to Date data type
Functions Format
Str
Shows an expression in the desired format
57
Text files & Dir Description
CurDir Returns the current path
FileLen
Date and time when a file was last modified
Functions FreeFile Returns the next available file number for text files
58
VBA’s MsgBox Function
Easily create info dialog boxes to communicate with the user
& get simple responses such as Ok, Yes, No or Cancel.
The message box is a function, i.e. your macro is paused until the
user provides a response.
You can use the MsgBox function by itself (don’t use brackets) if you don’t need a
response from the user. If you need a response, the message box will return a result
which you can capture in a variable (use brackets).
Input Box always returns a string. If you write the result of the input box to a cell,
Excel will automatically convert the answer to the correct type. For example if you
input a number, it will be recognized as a number in the cell.
If you’d like to use the answer in your code, and the answer should be a number,
you need to convert it to a number with a conversion function. For example the Val
function. To validate if the input is a number, you can use IsNumeric function
Range("A2").Value = Excel.WorksheetFunction.Proper(myInp)
60
Excel’s InputBox Method
3 benefits of using the Input Box Method
1 You can specify the data type for input (not restricted to string)
61
Key Takeaways: Built-in Functions
1 Review the List for Useful VBA Functions
Take some time and review the list and test some of the functions you think could come in
handy for your projects.
2 MsgBox Function
Use the message box to inform the user or get a “Yes”, “No” answer from them.
You can also use the message box for debugging your code.
62
1 Become familiar with Macros, VBE & the Object Model
How to Reference Ranges, Worksheets & Workbooks
Variables, Data Types
Working with Collections & Making Decisions
Useful VBA Functions
64
Methods to Debug Your
To help you Pinpoint Errors… in addition to the MsgBox
Code
1 F8 or select Debug from the menu and then Step Into.
2 Add breakpoints with F9 or Debug menu / Toggle Breakpoint. You can play the code
until a certain place and then you can step in with F8. Add as many as you need.
Use the Immediate Window. Type “Debug.Print” followed by your variable name in
4 the code. This writes the result to the immediate window. You can also type in code
directly in this window. Use the “?” to get the answer. Activate it from the View tab.
5 Use the Locals Window to see the value and characteristics associated with each
variable. Activate it from the View tab.
6 Use the Watch window to keep your eye on certain variables. Right-mouse click on a
variable or statement and “add to watch”. Alternatively drag to the window. You can
change the variable property directly by typing it in. Activate watch from the View
tab. 65
Error Handling: Different Methods
Common error handling examples
1 Sub Jump_to_End()
2 Sub Resume_Then_Normal() 3 Sub Handle_Based_on_Error_Type()
On Error GoTo Leave On Error GoTo ErrorHandle
On Error Resume Next
[code instructions]
[code instructions]
[code instructions]
Exit Sub
Leave:
On Error GoTo 0
End Sub ErrorHandle:
[code instructions] Select Case Err.Number
Case 424
Uses a label to jump End Sub Exit Sub
to the end of the code Case Else
MsgBox "An error has occurred."
the moment an error Suppresses certain End Select
occurs. errors and then resumes End Sub
normal error handling
for the remaining More detailed error handing
instructions. by type. Add “Exit sub” to
leave the macro if error-free.
66
Faster & Efficient
Suppressing Pop-ups & flickering screen
VBA Code
Suppress
With Application
• Use the Status bar to let the user know the macro is
.StatusBar = "Wait“ running
.ScreenUpdating = False • Screen flickering
.Calculation = xlCalculationManual
• Formula calculations
.DisplayAlerts = False
• Excel alerts – for example when deleting worksheets or
End With
closing a workbook.
Restore
With Application
Use this block of code when writing to
.ScreenUpdating = True
cells, working with different
.Calculation = xlCalculationAutomatic
worksheets or workbooks & other
.DisplayAlerts = True
.CutCopyMode = False (In case you used
longer tasks.
PasteSpecial)
.StatusBar = ""
End With 67
Procedure Scope & Passing Arguments
Procedures are Public by Default.
Private Procedures are accessible to other procedures in the same module. They
are also not shown in the Macro list.
To execute one procedure from another procedure you can use the optional keyword CALL.
If Procedures have arguments you need brackets if you use the CALL keyword.
Call myCalc (i, c)
MyCalc i, c
68
Key Takeaways: Debug & Handle Errors
1 Keep the Debug Options List Handy
You might prefer one way over another when debugging. I personally prefer to use F8 to
step through the code → the immediate window for testing results and for more complex
checks → the watch window. I use the Locals window for testing Arrays.
2 Error Handling
Implement some type error handling if you are planning to share your tool with others. Try
to catch what you can from your side but allow others to test your code and provide
feedback.
3 Suppressing Certain Events
For longer codes make sure you suppress screen updating or display of alerts. This
makes your code run smoother and faster.
4 Procedure Scope
Procedures are Public by default. Sub Procedures that are declared as Private do not show
up in the Macros dialog box. They can be used inside Public Sub procedures.
69
1 Become familiar with Macros, VBE & the Object Model
How to Reference Ranges, Worksheets & Workbooks
Variables, Data Types
Working with Collections & Making Decisions
Useful VBA Functions
71
Looping in VBA
Controlling the Flow of Code
72
For Next Counter Loops
Simple Looping construct that’s based on a counter.
Exit For statement leaves the loop.
Sub Simple_For()
Dim i As Long
Dim myValue As Double
LastRow = ActiveSheet.UsedRange.Cells(ActiveSheet.UsedRange.Rows.Count, 1).Row
For i = 4 To LastRow
myValue = Range("F" & i).Value Sub Delete_Hidden_Filtered_Rows()
If myValue > 400 Then Range("F" & i).Value = myValue + 10 Dim r As Long
If myValue < 0 Then Exit For With ActiveSheet
Next i LastRow = .UsedRange.Cells(.UsedRange.Rows.Count, 1).Row
End Sub For r = LastRow To 4 Step -1
If .Rows(r).Hidden = True Then
.Range("H" & r) = "X"
' .Rows(r).Delete
End If
Next r
End With
End Sub
73
Do…Until / Do…While Loop
Do…While Loop runs as long as a specified condition is met
Do…Until Loop runs until a specified condition is met
Exit Do command leaves the loop immediately
You can also use Do…Loop
(without While or Until)
Sub Simple_Do_Until_V1()
Startcell = 8
Do Until ActiveSheet.Range("A" & Startcell).Value = "" While Wend is similar to Do loop
Range("B" & Startcell).Value = Range("A" & Startcell).Value + 10 and is still included in VBA for
Startcell = Startcell + 1 compatibility purposes.
Loop
End Sub
74
Find Method for Quicker Results
FIND method provides a quick way to find the answer without Looping
From MSDN.Microsoft.com
FIND with DO LOOP for Many Matches
Sub Many_Finds()
Dim CompID As Range, FirstMatch As Variant, i As Long
Dim Range("D3:D6").ClearContents
i=3
Set CompID = Range("A:A").Find(What:=Range("B3").Value, _
LookIn:=xlValues, LookAt:=xlWhole)
If Not CompID Is Nothing Then
Range("D" & i).Value = CompID.Offset(, 4).Value
FirstMatch = CompID.Address
Do
Set CompID = Range("A:A").FindNext(After:=CompID)
If CompID.Address = FirstMatch Then Exit Do
i=i+1
Range("D" & i).Value = CompID.Offset(, 4).Value
Loop
End If
End Sub
75
Add a Timer to Test & Speech to Inform
Adding a timer (VBA function) helps you test different versions of code for the same
task
Dim Start 1. Write your code
Start = Timer 'seconds since midnight 2. Add a Timer
3. Comment out the current code
[code instructions] 4. Write new code and test
5. Use the code version that runs fastest
Debug.Print Timer - Start 6. Remove the Timer or comment out
Allowing your computer to “speak” is a good way of informing the user that a long
procedure is now completed. Speakers should be turned on.
[code instructions]
Application.Speech.Speak "Job Done!"
End Sub
76
General Description
Const Declare a constant
Common Like Returns True if one string can be matched with another
Statements
Load Loads an object (like a userform) but doesn’t show it
On Error Give specific instructions for the case when an error occurs
While - Wend Loops through instructions as long as a condition is true (included for
compatibility purposes)
78
Text file & Dir Description
Close Close a text file
79
Key Takeaways: LOOPING IN VBA
1 For … Next Counter Loop
Very powerful and flexible way of looping through cells. It’s safer to use than the Do loop:
The loop only runs for a specific number of times depending on the lower and upper
values of the control variable.
2 Do Loop
Variations include Do…Until, Do…While and just Do (with a check for a condition when the
loop can be exited). These come in handy when you don’t know the number of times the
loop should run. Tip → Use F8 first before running the code to make sure it works properly.
3 Find Method
Find method can be faster than the For…Next and Do Loop methods when looking for
one or many matches.
Use a Timer & Speech to Inform
4 Use VBA’s Timer function to test different variations of code, in case you aren’t sure which
one is more efficient. Speech.Speak method is a good way of vocally informing the user the
macro has finished running.
80
1 Become familiar with Macros, VBE & the Object Model
How to Reference Ranges, Worksheets & Workbooks
Variables, Data Types
Working with Collections & Making Decisions
Useful VBA Functions
# Variant Arrays
82
How to Declare & Fill Arrays
Fill a 1 Dimensional Array
Dim MonthArray(1 To 12) As String
Declaring VBA Code Dim i As Byte
Arrays 'Fill up the month array
Declaring a Fixed Dim MonthArray(1 To 12) As For i = 1 To 12
Array String MonthArray(i) = Range("mymonths").Cells(i, 1).Value
Declaring a Dim MonthArray() As String Next i
Dynamic Array
Declaring a two Dim MonthInfo(1 To 12, 1 To 2) As
Dimensional Fixed Variant
Fill a 2 Dimensional Array
Array Dim MonthInfo(1 To 12, 1 To 2) As Variant
Referring to the LBound(MonthArray) Dim r As Long
Lowest / Highest UBound(MonthArray) Dim c As Long
Index in the array
'fill the rows
Define the size of ReDim MonthArray(1 To Cnt)
the dynamic array
For r = 1 To 12
'fill the columns
Keep the existing ReDim Preserve Cust(1 To 3)
values inside the For c = 1 To 2
array MonthInfo(r, c) = Cells(r + 4, c).Value
Next c
Next r
83
Working with Variant Arrays
• Similar to working with arrays in Excel
• Keep values of many cells inside one variable (compartment)
• Manipulate the members of this variable
• Write back to the range in one go
Example of Variant Array
Sub Write_to_Variant_Array()
'notice brackets are not required for variant arrays
Dim QuantityValue As Variant
Dim r As Long
'QuantityTbl is a range of cells defined in name manager
Looping inside QuantityValue = Range("QuantityTbl").Value
arrays is faster than For r = 1 To UBound(QuantityValue, 1)
looping in the cells. 'Add 10 to the existing value
QuantityValue(r, 1) = QuantityValue(r, 1) + 10
Next r
Range("QuantityTbl") = QuantityValue
End Sub
84
Key Takeaways: Arrays
1 One Dimensional Array
This is similar to highlighting one row or one column in Excel. Fixed one-dimensional array
is defined during the DIM statement: Dim MonthArray(1 To 12) As String.
3 Dynamic Array
The exact size of the array is defined during code execution. Use the REDIM statement
to define the size and then fill the array.
Variant Array
4 This is similar to Excel arrays. A range of cells is defined as a variant. It can be directly
manipulated with a loop and values written back to cells in one go. This is a faster method
than using a For…Next loop.
85
1 Become familiar with Macros, VBE & the Object Model
How to Reference Ranges, Worksheets & Workbooks
Variables, Data Types
Working with Collections & Making Decisions
Useful VBA Functions
87
Check if File or Folder Exist (DIR)
DIR Function uses a path argument and returns the name of the file or folder. If path
name is not found, DIR returns a zero length string (“”).
88
User Selects File(s): GetOpenFileName
GetOpenFileName Method to allow the
GetOpenFileName (Many Files)
user to select one or more files
Sub Select_Many_Files()
Dim FileToOpen As Variant
Dim FileCnt As Byte
GetOpenFileName (1 File)
Dim SelectedBook As Workbook
Sub Get_Data_From_File() 'Pick the files to import - allow multiselect
Dim FileToOpen As Variant FileToOpen = Application.GetOpenFilename _
Dim OpenBook As Workbook (Filefilter:="Excel Files (*.xlsx), *.xlsx", _
FileToOpen = Application.GetOpenFilename _ Title:="Select Workbook to Import", MultiSelect:=True)
(Title:="Browse for your File", _
FileFilter:="Excel Files (*.xls*),*.xls*") If IsArray(FileToOpen) Then
If FileToOpen <> False Then For FileCnt = 1 To UBound(FileToOpen)
Set OpenBook = Application.Workbooks.Open(FileToOpen) Set SelectedBook = Workbooks.Open
'[Instructions] _(FileName:=FileToOpen(FileCnt))
OpenBook.Close False ' [Instructions]
End If SelectedBook.Close
End Sub Next FileCnt
End If
End Sub 89
User Selects a Folder (to Loop Through)
Get Folder Name
Sub Loop_Inside_Folder()
Dim FileDir As String
FileDialog Property provides an easy way
Dim FiletoList As String
With Application.FileDialog(msoFileDialogFolderPicker) to allow the user to select a folder. You can
.Title = "Please select a folder" write a loop to go through each file inside
.ButtonName = "Pick Folder" the folder.
'Cancel show value = 0, -1 there was a selection
If .Show = 0 Then
Exit Sub
Else
FileDir = .SelectedItems(1) & "\"
End If Calling the Dir function again inside the
End With loop without any arguments moves on to
FiletoList = Dir(FileDir & "*xls*") the next file in the folder.
Do Until FiletoList = ""
FiletoList = Dir
Loop
End Sub
90
Export Sheets as CSV
Export as CSV
Sub Save_as_CSV()
End Sub
91
Writing and Reading a Text File
VBA Open Statement (not the Open Method of Workbook) opens a file for reading or writing.
This gives your more control over the layout (for example the delimiter)
Open pathname For mode [ Access access ] [ lock ] As [ # ] filenumber [ Len = reclength ]
2 GetOpenFileName Method
Use this method to allow the user to browse and pick a file. Set the filter using the correct
extension if you’d like to restrict them to certain file types.
3 FileDialog Property
Use this property to allow the user to browse for and select a folder (you can also use it
to select files). Use DIR to get the name of the first file inside the folder and then DIR
again without any arguments to loop through the folder, i.e. move on to the next file.
95
Using Excel Formulas In VBA
To ensure compatibility with different Excel languages, use the macro recorder to record
formulas. The formulas are always recorded with the default English reference library.
These work on all the different languages of Excel.
FormulaR1C1 property uses the row and column numbering to refer to cells.
Formula property uses the A1 Type of referencing (although it can interpret R1C1
referencing as well).
To display formulas in local language, use the FormulaLocal property. E.g:
Range(“F20”).FormulaLocal instead of Range(“F20”).Formula
96
Table Task VBA Code
Declaring Tables Dim myTable As ListObject
Set myTable =Activesheet.ListObjects(“Table1")
Whole Table myTable.Range.Select
All Data – No Headers myTable.DataBodyRange.Select
myTable.ListRows.Add , False
Add a 2nd Row myTable.ListRows.Add 2
Add a Column to the end myTable.ListColumns.Add
Add a 2nd Column myTable.ListColumns.Add 2
Add a Column to the end myTable.ListColumns.Add
Rename the last Column myTable.ListColumns(myTable.ListColumns.Count).Name = “NEW"
Add Formula to Row 1 Column 6 myTable.DataBodyRange(1, 6).FormulaR1C1 = "=(“put formula”)"
97
Working with Pivot Tables
3 Pivot Tables
Pivot Cache is the brain of the Pivot Table. When creating a Pivot Table, a Pivot Cache is
created first. Make sure you don’t have duplicate Pivot Caches in your reports (unless
you need them).
99
1 Become familiar with Macros, VBE & the Object Model
How to Reference Ranges, Worksheets & Workbooks
Variables, Data Types
Working with Collections & Making Decisions
Useful VBA Functions
101
Interacting with Other
Applications
(Word, PowerPoint, Adobe etc.)
102
Excel’s In-built Methods / Dialogs
For Easy Interaction
You can loop through different cells to get individual email addresses,
email subject information and respective Excel sheets to be sent as
attachment
Application.Dialogs(xlDialogSendMail).Show [email], [subject]
103
Early Versus Late Binding
To work with other applications you need to create an instance of the object.
You have two options:
1. Early Binding
2. Late Binding
Early Binding: Go to Tools / References / Place a check mark on the application
Advantage: You have access to the Object Reference Library of this application
Disadvantage: The reference is version specific
GetObject → Uses an existing instance of the application or starts the application with
a file loaded (you need to specify the path)
105
Key Takeaways: Other Applications
1 Use ExportAsFixedFormat method to create PDF files
2 Use xlDialogSendMail to create simple E-mails (no need to activate the reference library)
Use Early Binding to connect to other applications if you’d like to get IntelliSense.
3 Do this by activating the Object Reference Library of the respective application.
106
1 Become familiar with Macros, VBE & the Object Model
How to Reference Ranges, Worksheets & Workbooks
Variables, Data Types
Working with Collections & Making Decisions
Useful VBA Functions
108
What are Events?
Excel is programmed to monitor various events:
109
Useful Workbook Events
Common Workbook Events How it’s triggered
Open & BeforeClose Workbook is opened & workbook is about to be closed
Activate & Deactivate Workbook is activated & deactivated
SheetActivate & Sheet Any worksheet is activated & deactivated
Deactivate
BeforeSave & AfterSave A workbook is about to be saved & after it is saved
BeforePrint A workbook or parts of the workbook are about to be printed
NewSheet A new sheet is created in the workbook
SheetChange The contents of any worksheet are changed
111
2 Useful Tips When Using Events
1 Disabling Events → Application.EnableEvents = False turns off any worksheet or
workbook events. You might need this to prevent an infinite loop. E.g. You might need
to change a value in a cell inside the Worksheet_Change event. This would re-trigger
the event. To make sure it doesn’t, turn off events before this line of code and then turn
it on again after the line of code Application.EnableEvents = True.
Range
Private Sub Worksheet_Change(ByVal Target As Range)
Intersect If Not Intersect(Target, Range("A1:C6")) Is Nothing Then
[Instructions]
End If
End Sub
Target
112
1 Become familiar with Macros, VBE & the Object Model
How to Reference Ranges, Worksheets & Workbooks
Variables, Data Types
Working with Collections & Making Decisions
Useful VBA Functions
114
ActiveX Controls
Embed UserForm controls directly in your Worksheet
You don’t necessarily need to use Macros: You can link to values to cells.
Design mode: You need to switch to design mode to adjust properties of ActiveX controls
Use properties window to adjust control name, fill range and linked cell
ActiveX controls have event-handler procedures which is kept in the code window of the
sheet the ActiveX is in.
115
Steps to Your UserForm
1 Insert a UserForm (right-mouse click in Project View and Insert →
UserForm)
3 Adjust Properties for the UserForm and each Control in the Properties Window
Write procedures for the controls in the code window of the UserForm (use keyword
4 ME when referring to the UserForm (instead of referencing the form’s name)
116
Order of UserForm Events
Load Initialize
Show Initialize Activate
UnLoad QueryClose Terminate
Hide
Close Button UnLoad
117
UserForm Checklist
Does your UserForm have a simple & easy to read layout?
118
Using a ListBox or ComboBox
You can add items to a ListBox or ComboBox
# by specifying a range (or a named range) in the
RowSource property at design time
# You can link the value of a ListBox or ComboBox to a cell using the ControlSource property
or use the Value property in VBA code
# You can add items to a ListBox and ComboBox at runtime using the AddItem
method
# To get the Value for a ListBox (single) use Value or ListIndex property. For a Multiselect
ListBox use Selected() property
# You can allow MutiSelect in a ListBox and display the items with CheckBoxes or
OptionButtions (for single selection)
121
Creating Customized
Functions / Formulas
Make your own formulas in Excel
122
How Function Procedures Work
You can use Function Procedures in:
# Animated Charts
126
VBA Basics for Charts
Embedded Chart Chart Sheet
Application Application
Workbook Workbook
Embedded Charts are part
Worksheet of the ChartObjects & the Chart
Shapes Collection
ChartObject (Chart Element)
Chart
AddChart2 Method to
(Chart Element) create an Embedded
Chart and Add2 Method
Examples for embedded charts for a new Chart Sheet
(From Excel 2013 &
ActiveSheet.Shapes.AddChart2 , xlColumnClustered above)
Power Programming with VBA (Excel 2013): By John Walkenbach. This is one of my
absolute favorite VBA books.
129
THANK YOU!
Please take a few seconds to
leave a review for the course.
Your support is very much
appreciated.
130