VBA - Overview: TOPIC 1 - Introduction
VBA - Overview: TOPIC 1 - Introduction
TOPIC 1 – Introduction
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.
Shortcut keys
Alt + F11 : Visual basic editor window
Ctrl + R Project Explorer
F4 Properties Windows
Page |2
2. Range Properties:
a. .Value Property
MsgBox Range(“a1”).Value
b. .Text 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”””
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
Cells(1,2) = 50
Cells(1,”b”) = 50
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
Page |6
TOPIC 4 – 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
e. Constant
Constant consname as string = “Bimby”
Page |7
EXERCISE 3
TOPIC 5
Important Tools and Excel Logic
f. If then statement
Sub MyIfstatements()
If Range (“c6”) = 12 Then
MsgBox “Good!”
Page |9
End If
End Sub
g. If not equal to (<>) statement
Sub MyIfstatements()
If Range (“c6”) <> 12 Then
MsgBox “Good!”
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
Sub MyIfstatements()
If Range("c6") > 3 And IsNumeric(Range("c6")) Then
MsgBox "Good!"
End If
End Sub
Case is <2
MsgBox “less than 2”
Case Else
MsgBox “else”
End Select
Goto myEnding
.
.
myEnding:
EXERCISE 4
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.
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
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
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
rptsheet.Visible = True
rptsheet.Select
Sub MyForeachloop()
For each cell in range(“names”)
IF cell = “Kellu” Then Exit For
Msgbox cell
Next cell
End Sub
p. Intro to DO LOOPS
Sub MyDoLoop()
X=2
Do
MsgBox Cells(x,1)
x = x +1
Loop
End Sub
q. Do Until
Sub MyDoLoop()
X=2
Do Until Cells(x,1) = “”
P a g e | 16
MsgBox Cells(x,1)
x = x +1
Loop
End Sub
r. Loop Until
Sub MyDoLoop()
X=2
Do
MsgBox Cells(x,1)
x = x +1
Loop Until Cells(x,1) = “”
End Sub
s. Do While
Sub MyDoLoop()
X=2
Do While Cells(x,1) <> “”
MsgBox Cells(x,1)
x = x +1
Loop
End Sub
t. Loop While
Sub MyDoLoop()
X=2
Do
MsgBox Cells(x,1)
x = x +1
Loop While Cells(x,1) <> “”
End Sub
u. Exit Do
Sub MyDoLoop()
X=2
Do
If Cells(x,1) = “” Then Exit Do
MsgBox Cells(x,1)
x = x +1
Loop
End Sub
v. Loop Through Multiple Files in a folder and Scrape Data From Each
Sub getDATAFromWbs()
P a g e | 17
Set wb = Workbooks.Open(wbfile.Path)
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
Set wb = Workbooks.Open(wbfile.Path)
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
P a g e | 18
wb.Close
End If
Next wbfile
End Sub
EXERCISE 5
and only lists records with that user's name. Make a button or shape that triggers this other report.
EXERCISE 6
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
P a g e | 19
d. BeforeDelete Event
Private Sub Worksheet_BeforeDelete()
MsgBox "Hala Bakit mo binura?"
End Sub
e. BeforeDoubleClick Event
P a g e | 20
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
l. FollowHyperlink Event
Private Sub Worksheet_FollowHyperlink(ByVal Target As Hyperlink)
MsgBox Target.Name
End Sub
sh2.Cells(shLR, 1) = Date
sh2.Cells(shLR, 1) = Time
End Sub
End Sub
P a g e | 22
-Make a Excel VBA program that will calculate the area of closed traverse after you
input the bearings and length of the lot. Limits (3-1000 bearings)
-Need each button for Clearing of Data, Input of data, and Calculating the Area
P a g e | 24
dsheet.Range("A1") = "BEARING"
dsheet.Range("B1") = "DISTANCE"
End Sub
End Sub
P a g e | 25
dsheet.Cells.HorizontalAlignment = xlCenter
GoTo Line2
Line1:
Dim ErrorLot1 As Double
ErrorLot1 = Application.WorksheetFunction.Sum(Range("O2:O" &
LastRow))
Dim ErrorSumL1 As Double
ErrorSumL1 = Application.WorksheetFunction.SumIf(Range("O2:O" &
LastRow), ">0")
Dim ErrorSumL2 As Double
ErrorSumL2 = Application.WorksheetFunction.SumIf(Range("O2:O" &
LastRow), "<0")
Dim ErrorSumL As Double
P a g e | 26
ErrorSumL = Application.WorksheetFunction.Sum(Abs(ErrorSumL1) +
Abs(ErrorSumL2))
ErrorL = ErrorLot1 / ErrorSumL
GoTo Line3
Line2:
For x = 2 To LastRow
End If
Line3:
For x = 2 To LastRow
dsheet.Cells(x, 17).formula = "=ABS(O:O*" & ErrorL & ")"
dsheet.Cells(x, 18).formula = "=ABS(P:P*" & ErrorD & ")"
dsheet.Cells(x, 19).formula = "=O:O-Q:Q"
dsheet.Cells(x, 20).formula = "=P:P-R:R"
P a g e | 28
End Sub