VBA - Overview
VBA stands for Visual Basic for Applications an event-driven programming language from Microsoft that is now
predominantly used with Microsoft office applications such as MSExcel, MS-Word, and MS-Access.
It helps techies to build customized applications and solutions to enhance the capabilities of those applications. The
advantage of this facility is that you NEED NOT have visual basic installed on our PC, however, installing Office will
implicitly help in achieving the purpose.
You can use VBA in all office versions, right from MS-Office 97 to MS-Office 2013 and also with any of the latest versions
available. Among VBA, Excel VBA is the most popular. The advantage of using VBA is that you can build very powerful
tools in MS Excel using linear programming.
Application of VBA
You might wonder why to use VBA in Excel as MS-Excel itself provides loads of inbuilt functions. MS-Excel provides only
basic inbuilt functions which might not be sufficient to perform complex calculations. Under such circumstances, VBA
becomes the most obvious solution.
For example, it is very hard to calculate the monthly repayment of a loan using Excel's built-in formulas. Rather, it is
easy to program a VBA for such a calculation.
TOPIC 1
Activate developer tab in excel (Excel 2007 and up)
Go to “File”, then Click “Options”, then “Customize Ribbon” and check the “Developer” and “OK” to enable the
developer tab in excel.
Shortcut keys
Alt + F11 : Visual basic editor window
Ctrl + R Project Explorer
F4 Properties Windows
Click new module
Type “sub groupname”
Type between Sub & End Sub
Range("a1") = 12
Then click play button (observe what happens on the excel sheet)
Next try
Range("a1:c6") = 12
Topic 1 – Range Objects and Range Properties
1. Range object – same as cell in excel
Range object with cells
2. Range Properties:
a. .Value Property
MsgBox Range(“a1”).Value
b. .Text Property
MsgBox Range(“a1”).Text
c. .Row and .Column Property
MsgBox Range(“a1”).Text
d. .Select property
Range(“table_01”).Select
e. .Count Property
MsgBox Range(“table_01).Count
f. .ADDRESS PROPERTY
MsgBox Range(“a1”).Address(0,0)
g. .FORMULA PROPERTY
Range(“a1”).Formula = “=A2+A3”
h. .NUMBERFORMAT PROPERTY
Range(“a1”).NumberFormat = “0.00””mm”””
i. .FONT.BOLD, UNDERLINE OR ITALIC
Range(“a1”).Font.Bold = true
Range(“a1”).Font.Underline = true
Range(“a1”).Font.Italic = true
Exercise 1
Objectives:
1. Create a Macro that types the following headers on row 1:
•ID
•First Name
•Last Name
2. Make the headers BOLD!
Exercise 2
Create a Macro that:
1. Enters the following data
2. Makes a1 through b1 BOLD
3. Selects cell C1
4. Now, manually create
a shape that says Click
Me and assign your
macro to it. This is not
part of the macro, just
make the shape
manually.
TOPIC 2
a. The Cell Object
Cells(1,2) = 50
Cells(1,”b”) = 50
b. Using Cells positionally within a Range
Cells(6) = 44
Range(“a1:c16”).cells(6) = 44
c. Affecting all cells in a worksheet
Cells.Font.Name = “Arial”
Cells.Font.Size = 15
d. Using Range Object with cells Object
Range(Cells(1,2),Cells(4,3)) = 44
Exercise 3
By default, Sheet1 on a worksheet will have a default cell font and will be zoomed to 100%.
In this exercise, the user wants a macro that formats a sheet to ideal conditions for their
work.
1. Format all cells as font "Arial"
2. Zoom in to
145%
3. Format Column D (4th column) as currency, because your company always has currency in column D
TOPIC 3 – VARIABLES
a. Intro to Variables
Sub MyVar1()
MyVar = 50
b. Sub Var2()
Dim x As Integer, y As Integer
x = 10
y = 100
MsgBox "the value of x is " & x & Chr(13) & "the value of y is " & y
End Sub
c. Sub myVar3()
Dim hi as string
Dim hello As double
Dim mydate1 as Date
Hi = “Hello World”
Hello = 634.85
Mydate1 = “01/28/2019”
End Sub
d. Private and Public variables
Public myVar3
Sub MyVar1()
MyVar = 50
Call myVar3
MsgBox Hi
End Sub
e. Constant
Constant consname as string = “Bimby”
Exercise 4
Continue with current procedure called 'getDaysOld' …
This procedure takes any Birthdate and reveals how many Days old someone is.
1. Take today's date minus the entered date to get difference (number of days since then)
2. Display "You are NNN days old" in a messagebox
3. BONUS! - Also display how many total hours old they are!
TOPIC 4
Important Tools and Excel Logic
a. Determining the last rows in your data set
Ex. Last row in Column 1(row no.)
LastRow = cells(rows.count,1).end(xlup).row
b. Determining the last column in your data set
Ex. Last column in row 1
LastColumn = cells(1,columns.count).end(xltoleft).column
c. Determining the next row in your data set
Ex. Next row after the last row in Column 1(row no.)
NextRow = cells(rows.count,1).end(xlup).row+1
d. Absolute vs Relative references in Macro Recording
e. Using With and End With
With Range(“a1”)
.Font.Bold = true
.Font.Underline = true
.Font.Italic = true
End With
f. If then statement
Sub MyIfstatements()
If Range (“c6”) = 12 Then
MsgBox “Good!”
End If
End Sub
g. If not equal to (<>) statement
Sub MyIfstatements()
If Range (“c6”) <> 12 Then
MsgBox “Good!”
End If
End Sub
h. If , Then, ElseIF Statement
Sub MyIfstatements()
If Range (“c6”) = 12 Then
MsgBox “Good!”
Else
MsgBox “Bad”
End If
End Sub
Another Example:
Sub MyIfstatements()
If Range (“c6”) = 12 Then
MsgBox “Twelve!”
Elseif Range(“c6”) = 5 then
MsgBox “Five”
Else
MsgBox “Please enter either a Five or a Twelve”
End If
End Sub
i. Comparative Operators with Text and Numbers
Note: VBA tend consider text somehow greater than any numbers so you'll have to compensate
Sub MyIfstatements()
If Range("c6") > 3 And IsNumeric(Range("c6")) Then
MsgBox "Good!"
End If
End Sub
j. Select Case as alternative to IF THEN Statements
Sub myCase()
Select Case Range(“c6”)
Case 12
MsgBox “Twelve”
Case is <2
MsgBox “less than 2”
Case Else
MsgBox “else”
End Select
k. GoTo and Labels (Skip “underconstruction” codes)
Goto myEnding
.
.
myEnding:
l. Message box with Yes and No Options
Sub myMessage
Answer = MsgBox (“Do you like excel vba?”, vbyesNo)
If answer = vbYes Then
MsgBox “I like it too!”
Elseif answer = vbNo Then
Msgbox “I think you should like it, it’s cool!”
End If
End Sub
Exercise 6
NOTE: To get the row number of the Selected
cell, use Selection.Row
When user clicks on a cell and clicks blue
button, the macro will use items on that row in
various columns.
Create a Macro that does the following:
1. Asks user "Add 100 to current row sales?"
2. If Yes, add 100 to Sale Amount (current row,
column 4)
3. If No, do nothing
4. Assign Macro to blue button
m. Relative positioning using Offset
Sub MyOffset
Selection.Offset(3,1) = Selection
Or
Cells(1,1).Offset(3,1)=”Mabuhay”
End Sub
n. User Defined function
Function MoI(b, d)
MoI = (b * (d ^ 3)) / 12
End Function
With optional parameter
Function MoI(b, d, Optional dplaces)
If IsMissing(dplaces) then
MoI = (b * (d ^ 3)) / 12
Else
MoI =Round(( (b * (d ^ 3)) / 12),dplaces)
End If
End Function
Topic5 - Loops and Report Writing Basics
a. Intro to loops; the For Next Loop
Sub MyFirstLoop()
For X = 1 to 10
Cells(x, 1) = x
Next x
End Sub
Another sample:
Sub MyFirstLoop2()
For x = 1 to 10
Cells(x,1) = x * 12.75
If cells(x, 1) > 50 Then
Cells(x, 2) = True
Cells(x, 2).Font.Bold = True
Else
Cells(x, 2) = False
Cells(x, 2).Font.Bold = False
End IF
Next x
End Sub
b. Beginning our first Report using Loops
Sub myFirstReport()
lastRow = Cells(Rows.Count, 1).End(xlUp).Row
For x = 2 To lastRow
If Cells(x, 4) >= 400 Then
myMsg = myMsg & vbNewLine & Cells(x, 1)
End If
Next x
MsgBox myMsg
End Sub
c. Using InputBox
Sub myIB()
myIB1 = InputBox("How much money should they make", "How Much", "200")
End Sub
d. Dynamic Report using InputBox
Sub myFirstReport()
lastRow = Cells(Rows.Count, 1).End(xlUp).Row
myIB1 = InputBox("How much money should they make", "How Much", "200") +0
For x = 2 To lastRow
If Cells(x, 4) >= myIB1 Then
myMsg = myMsg & vbNewLine & Cells(x, 1)
End If
Next x
MsgBox myMsg
End Sub
Change MyMsg to:
myMsg = myMsg & vbNewLine & Cells(x, 1) & “, “ & Cells(x, 2)
e. Add Button to open our report
Using Command Button (ActiveX Control)
To be discuss manually
f. Add a “Cool Looking” Button or Image to Open Report
To be discuss manually
g. Printable Report: Declaring and Setting the Sheets
Sub myPrintableReport()
Dim dsheet As Worksheet
Dim rptsheet As Worksheet
Set dsheet = ThisWorkbook.Sheets(“data”)
Set rptsheet = ThisWorkbook.Sheets(“report”)
h. Printable Report : Getting Items on Report Sheet
Sub myPrintableReport()
Dim dsheet As Worksheet
Dim rptsheet As Worksheet
Set dsheet = ThisWorkbook.Sheets("Data")
Set rptsheet = ThisWorkbook.Sheets("report")
lastRow = dsheet. Cells(Rows.Count, 1).End(xlUp).Row
myIB1 = InputBox("How much money should they make", "How Much", "200") + 0
y = 2 'starting row
For x = 2 To lastRow
If dsheet.Cells(x, 4) >= myIB1 Then
rptsheet.Cells(y, 1) = dsheet.Cells(x, 1) 'name
rptsheet.Cells(y, 2) = dsheet.Cells(x, 4) 'sale amount
y=y+1
End If
Next x
End Sub
i. Clearing the Last Report
Input “rptLR” before “lastRow” variable
Let rptLR variable be the last row of the report
rptLR = rptsheet.Cells(Rows.Count, 1).End(xlUp).Row
rptsheet.Range("a2:b" & rptLR).ClearContents
j. Ensuring visibility and autoselect report sheet
Add this codes at the end of loops
rptsheet.Visible = True
rptsheet.Select
i. Using print preview automatically
add this before “End Sub”
rptsheet.PrintPreview
j. Handling debug error when cancelling input box
Insert:
On Error Resume Next
If myIB1 = Empty Then Exit Sub
k. Looping with specific interval or backward
Ex.
For x = 2 to 10 step .5
Or For x = 10 to 2 step -1
l. The For Each Loop
Ex.
Sub MyForeachloop()
For each cell in range(“names”)
Msgbox cell
Next cell
End Sub
To cancel the loop,
Insert:
If cell = “any on the list” Then Exit For
EX:
Sub MyForeachloop()
For each cell in range(“names”)
IF cell = “Kellu” Then Exit For
Msgbox cell
Next cell
End Sub
Exercise 7a
Add the following to the Existing Macro:
1. Add a Yes/No Messagebox to report with prompt "Use Title on
Report?"
2. If Yes, include Title information, if No, omit Title info on 3rd column.
3. BONUS: Create a separate procedure (copy/paste current macro) that prompts for User's Name
and only lists records with that user's name. Make a button or shape that triggers this other report.
Exercise 7b
Create a procedure that:
1. Populate the table as in the image below. Attach procedure to the blue Shape as in previous exercises
2. Note: Each Name has a number that matches their ID and they go from 1 to 25 (Use a loop!)
3. BONUS: If the ID is greater than 17, make those cells in column A have a red background as below
j. Intro to DO LOOPS
Sub MyDoLoop()
X=2
Do
MsgBox Cells(x,1)
x = x +1
Loop
End Sub
k. Do Until
Sub MyDoLoop()
X=2
Do Until Cells(x,1) = “”
MsgBox Cells(x,1)
x = x +1
Loop
End Sub
l. Loop Until
Sub MyDoLoop()
X=2
Do
MsgBox Cells(x,1)
x = x +1
Loop Until Cells(x,1) = “”
End Sub
m. Do While
Sub MyDoLoop()
X=2
Do While Cells(x,1) <> “”
MsgBox Cells(x,1)
x = x +1
Loop
End Sub
n. Loop While
Sub MyDoLoop()
X=2
Do
MsgBox Cells(x,1)
x = x +1
Loop While Cells(x,1) <> “”
End Sub
o. Exit Do
Sub MyDoLoop()
X=2
Do
If Cells(x,1) = “” Then Exit Do
MsgBox Cells(x,1)
x = x +1
Loop
End Sub
p. Loop Through Multiple Files in a folder and Scrape Data From Each
Sub getDATAFromWbs()
Dim wb As Workbook, ws As Worksheet
Set fso = CreateObject("scripting.filesystemobject")
Set fldr = fso.getfolder("C:\temp\")
For Each wbfile In fldr.Files
If fso.getextensionname(wbfile.Name) = "xlsx" Then
Set wb = Workbooks.Open(wbfile.Path)
For Each ws In wb.Sheets
Next ws
wb.Close
End If
Next wbfile
End Sub
Sub getDATAFromWbs2()
Dim wb As Workbook, ws As Worksheet
Set fso = CreateObject("scripting.filesystemobject")
Set fldr = fso.getfolder("C:\temp\")
y = ThisWorkbook.Sheets("sheet1").Cells(Row.Count, 1).End(xlUp).Row + 1
For Each wbfile In fldr.Files
y = ThisWorkbook.Sheets("sheet1").Cells(Row.Count, 1).End(xlUp).Row + 1
If fso.getextensionname(wbfile.Name) = "xlsx" Then
Set wb = Workbooks.Open(wbfile.Path)
For Each ws In wb.Sheets
wsLR = ws.Cells(Rows.Count, 1).End(xlUp).Row
For x = 2 To wsLR
ThisWorkbook.Sheets("sheet1").Cells(y, 1) = ws.Cells(x, 1) '<<<<col1
ThisWorkbook.Sheets("sheet1").Cells(y, 2) = ws.Cells(x, 2) '<<<<col2
ThisWorkbook.Sheets("sheet1").Cells(y, 3) = CDate(ws.Cells(x, 1)) '<<<<col3
ThisWorkbook.Sheets("sheet1").Cells(y, 4) = ws.Cells(x, 4) '<<<<col4
y=y+1
Next x
Next ws
wb.Close
End If
Next wbfile
End Sub
Topic6 – Events: Worksheet Events made Easy
a. Intro to Worksheet Events and Selection_Change
Click Sheet1(Sheet1) on the Project Explorer then change into ‘Worksheet” on the upper box.
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Target.Address(0, 0) = "C2" Then
MsgBox "You've got cell C2"
Else
MsgBox "Not Cell C2"
End If
End Sub
b. Worksheet Activate Events
Private Sub Worksheet_Activate()
MsgBox "Welcome to Sheet2"
End Sub
c. Worksheet Deactivate Events
Private Sub Worksheet_Deactivate()
Sheets("Sheet3").Visible = False
End Sub
d. BeforeDelete Event
Private Sub Worksheet_BeforeDelete()
MsgBox "Hala Bakit mo binura?"
End Sub
e. BeforeDoubleClick Event
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
If Target.Address(0, 0) = "c3" Then
MsgBox "you double clicked c3"
Cancel = True
End If
End Sub
f. BeforeRightClick Event
Private Sub Worksheet_BeforeRightClick(ByVal Target As Range, Cancel As Boolean)
If Target.Address(0, 0) = "C3" Then
MsgBox "you double right clicked c3"
Cancel = True
End If
End Sub
g. Calculate Event
Private Sub Worksheet_Calculate()
Columns("a:F").AutoFit
End Sub
h. Disable Events
Sub disableEvents()
Application.EnableEvents = False
End Sub
i. Intro to Change Event
Private Sub Worksheet_Change(ByVal Target As Range)
Stop
End Sub
i. Change Event with EnableEvents toggle
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Column = 2 Then
If Target.Offset(0, -1) = "Destiny" Then
Application.EnableEvents = False
Target = 0.75
Application.EnableEvents = True
End If
End If
End Sub
j. Change Event triggered with custom range using Intersect
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Target, Range("b2:b4")) Is Nothing Then
MsgBox "You changed something in b2:b4"
End If
End Sub
j. FollowHyperlink Event
Private Sub Worksheet_FollowHyperlink(ByVal Target As Hyperlink)
MsgBox Target.Name
End Sub
Topic7 – Workbook Events
a. Workbook Open Event
Private Sub Workbook_Open()
Dim sh2 As Worksheet
Set sh2 = ThisWorkbook.Sheets(“Sheet2”)
shLR = sh2.Cells(Rows.Count, 1).End(xlUp).Row + 1
sh2.Cells(shLR, 1) = Date
sh2.Cells(shLR, 1) = Time
End Sub
b. Workbook Activate Event
Private Sub Workbook_Activate()
MsgBox "Welcome Back!"
End Sub
c. Workbook Before Save Event
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
answer = MsgBox("Are you sure you want to save?", vbYesNo)
If answer = vbNo Then
Cancel = True
End If
End Sub
d. Workbook After Save Event
Private Sub Workbook_AfterSave(ByVal Success As Boolean)
If Success = True Then
myVAR = "successful"
Else
myVAR = "unsuccessful"
End If
MsgBox "The save was " & myVAR
End Sub
d. Workbook Before Close Event
Private Sub Workbook_BeforeClose(Cancel As Boolean)
answer = MsgBox("Are you sure you want to close?", vbYesNo)
If answer = vbYes Then
Cancel = False
Else
Cancel = True
End If
End Sub
e. Workbook Before Print Event
Private Sub Workbook_BeforePrint(Cancel As Boolean)
Cancel = True
MsgBox "Bawal print, mahal ink, mahal papel, ikaw di mahal, gawa ka iyo spreadsheet tsaka ka print!!"
End Sub
f. Workbook Deactivate Event
Private Sub Workbook_Deactivate()
MsgBox "Balik ka ha?, mamimiss kita!"
End Sub
g. Workbook New Sheet Event
Private Sub Workbook_NewSheet(ByVal Sh As Object) application.displayalerts
MsgBox "You have a new sheet"
Sh.Cells.Font.Bold = True
End Sub
h. Workbook Sheet Activate Event
Private Sub Workbook_SheetActivate(ByVal Sh As Object)
If Sh.Name = "Sheet3" Then
Sheets("Sheet3").Visible = False
MsgBox "Uy nawala!"
End If
End Sub
h. Workbook Delete, Double Click, Event
Private Sub Workbook_SheetActivate(ByVal Sh As Object)
If Sh.Name = "Sheet3" Then
Sheets("Sheet3").Visible = False
MsgBox "Uy nawala!"
End If
End Sub