Вы находитесь на странице: 1из 9

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

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.

Вам также может понравиться