bc2014_session6
TRANSCRIPT
-
7/24/2019 BC2014_Session6
1/36
Visual Basic for Applications
(VBA)
1
-
7/24/2019 BC2014_Session6
2/36
VBA is a subset of the Visual Basic programming language.
It is Microsoft's common application programming language (for developingmacros) integrated to MS Office applications lie !ord" #$cel" etc.
VBA is interpreted" it is not compiled" so e$ecution is slo%
VBA is an Ob&ect Oriented" Application rogramming anguage though *ou ma*not notice it or no% of an* alternatives
A VBA macro is a user defined program %hich effectivel* result in the e$ecution aseries of MS #$cel activities
+eveloper ,ab -
Excel Options Popular Show Developer tab
2
-
7/24/2019 BC2014_Session6
3/36
What Can You Do With VBA
Write Macros to Automate Labor-Intensive and RepetitiveTasks
Create User-Defined Functions to Achieve CompicatedFunctionait!
Create customi"ed user forms# menus$too bars for Interface
Interact %ith &ther Windo%s 'ro(rams
I$& %ith )*terna Fies
Database &peration +,
3
-
7/24/2019 BC2014_Session6
4/36
First Step to VBA : Record a Macro
imiar to audio$video recorder Records a the steps !ou take and transates to ./A code
)*ercise0 Create a si"e-12 coumn of random vaues each time
!our macro is caed,
4
-
7/24/2019 BC2014_Session6
5/36
Working with the Visual Basic Editor
Developer tab Code roup Macros button
!elect "acro na"e Edit
5
-
7/24/2019 BC2014_Session6
6/36
Working with the Visual Basic Editor(contd#)
A projectholds all "acros$ worksheets$ for"s$and other ite"s that "ake up %ourcusto"i&ed 'ls" application'
Project Explorer is the window in the VisualBasic Editor that displa%s a hierarchical list of allcurrentl% open proects and their contents
An objectis an% ele"ent within the Ecelworking environ"ent such as a worksheet$ cell$workbook$ or even the Ecel progra" itself'
6
-
7/24/2019 BC2014_Session6
7/36
Working with the Visual Basic Editor(contd#)
You can view a list of properties for an% obect in theProperties window
A moduleis a collection of VBA "acros
*he Code windowdispla%s the VBA "acro codeassociated with an% ite" in +roect Eplorer
7
-
7/24/2019 BC2014_Session6
8/36
8
-
7/24/2019 BC2014_Session6
9/36
Working with VBA
,sing VBA we can develop !ub +rocedures and-unction +rocedures
A sub procedure perfor"s an action on %our
proect or workbook$ such as for"atting a cell ordispla%ing a chart$ .lling a se/uence$ etc !ub procedure can be directl% eecuted (can be associated
with /uick access tool bar)$ or called b% another subprocedure
A function procedureperfor"s anAction0calculation and can return a value Assign return value to function na"e A function procedure can be used directl% in a for"ula on
the spreadsheet$ or called b% another procedure'
9
-
7/24/2019 BC2014_Session6
10/36
!ub +rocedures
!ubs can have +ublic or +rivate scope (default is+ublic)
Basic s%nta
{Public|Private} Subname(arguments)[statements]Exit Sub[statements]
End Sub
10
Optional way to leave the Sub
before reachin the !n" #tate$ent
-
7/24/2019 BC2014_Session6
11/36
-unctions
-unctions can have +ublic or +rivate scope (defaultis +ublic)
Basic s%nta
{Public|Private} Functionfname(arguments)AS type[statements]Exit Function
[statements]End Function
11
Optional way to leave the %unction
before reachin the !n" #tate$ent
-
7/24/2019 BC2014_Session6
12/36
1bects2 3n VBA tasks are perfor"ed b%"anipulating obects
12
-
7/24/2019 BC2014_Session6
13/36
P ope t es
& property i# an attribute of an ob'ect that "efine#
one of it# characteri#tic#( #uch a# it# na$e( #i)e(
color( or location on the #creen( etc*
)*ampes
Ran(e34A50/5146,Ro%s,Count 3a read-on! propert!6
Ran(e34A50/5146,Font,/od 7 True 3read-%rite propert!6
13
-
7/24/2019 BC2014_Session6
14/36
Methods
Methods are the actions that can be performed on&b8ects# such as cosin( a %orkbook
Methods for &b8ects
Ran(e34A50/5146,CearContents
ActiveCe,Cop!
14
-
7/24/2019 BC2014_Session6
15/36
Events
&b8ects can respond to Events# such as a Mouse-Cick#Doube Cick on a ce# Activate a Worksheet#
&pen$Cose$ave a Workbook# etc,
Worksheet events0
uch as Activate# Deactivate# Chan(e# eectionChan(e# /efore Doube Cick# etc,
Workbook )vents0
uch as &pen# /efore Cose# /efore avin(# /efore
'rint# 9e% heet,
15
-
7/24/2019 BC2014_Session6
16/36
Collection Objects
1bects are often grouped into collections$ whichare the"selves obects$ called collectionobjects
Coection &b8ects share Common 'roperties# Methods and )vents
)*ampes 0 Workbooks# Worksheets# etc,
Worksheetsis a coection of a the Worksheet ob8ects in the specified oractive %orkbook,
16
-
7/24/2019 BC2014_Session6
17/36
Referring Objects Worksheets356 refers to the 5st %orksheet of current active %orkbook,
Worksheets3:Annua;6 refers to the %orksheet named :Annua;,
17
-
7/24/2019 BC2014_Session6
18/36
4eferring to 1bects
VBA organi&es obects and obect collections in a hierarch%with the Ecel application at the top and the individual cellsof a workbook at the botto"
18
-
7/24/2019 BC2014_Session6
19/36
4eferring to +ropert% of 1bects
19
-
7/24/2019 BC2014_Session6
20/36
Appl%ing 5ethods
20
-
7/24/2019 BC2014_Session6
21/36
Working with Variables
A variable is a na"ed ele"ent in a progra" thatcan be used to store and retrieve data
Ever% variable is identi.ed b% a uni/ue variablename
Di" variableas type
21
-
7/24/2019 BC2014_Session6
22/36
Variables
Better to use Data *%pes2 Dima"ount AsDouble Dimna"e AsString
1ther data t%pes2 Boolean$ Bte$ Currenc$ Date! etc
Default (no t%pe) is "ariant
Option Explicit forces all variables to be declared
Can "odif% scope (outside !ubs 6 -unctions) Private7 As#nteger
(onl% current "odule) Publicbills+aid AsCurrenc
(available to an% "odule)
22
-
7/24/2019 BC2014_Session6
23/36
,ser interaction 2 3nputBo
23
-
7/24/2019 BC2014_Session6
24/36
5essage Bo
5sgBo +ro"pt$ Buttons$ *itle
24
-
7/24/2019 BC2014_Session6
25/36
,ser -or"
,hese are custom made dialogue bo$es
Appropriate ontrols from the ,oolbo$ ontrols can be added as re/uired
roperties of a control can be changed
VBA Sub procedures to handle events (#vent handlers) that are generated inthe 0ser form need to be %ritten
25
-
7/24/2019 BC2014_Session6
26/36
Writing to a !heet
+ut the absolute value of the variable -in row 8 $colu"n * of the Worksheet na"ed "%!heet'
26
+or,#heet#-.$ySheet/*ane-.2/&*&b#-%
-
7/24/2019 BC2014_Session6
27/36
4eading fro" a Worksheet
*o read in a value$ use the 'Value"ethod$ appl%ing thesa"e ideas used for writing2
9 : Worksheets(;"%!heet
-
7/24/2019 BC2014_Session6
28/36
Wa%s to use '4ange 5ethod
4ange(=A>=) ell &1
4ange(=A>2B?=) ell# &1 throuh 5
4ange(=C?2D@$@2>=) & $ultiplearea #election
4ange(=A2A=) olu$n &
4ange(=>2>=) ow 1
4ange(=A2C=) olu$n# & throuh
4ange(=>2?=) ow# 1 throuh 5
4ange(=>2>$2$2=) ow# 1( 3( an" 8
4ange(=A2A$C2C$-2-=) olu$n# &( ( an" %
28
-
7/24/2019 BC2014_Session6
29/36
,se an Ecel -unction
VBA has a li"ited nu"ber of builtin functions$ but %oucan access the plethora of Ecel worksheet functions'
*his ea"ple uses the Ecel 41,FDD1WF function
29
+ +or,#heet%unction*oun""own-alue
-
7/24/2019 BC2014_Session6
30/36
Control !tructures
Decisions
#fan%Date G Fow $%enan%Date : Fow
End#f
9e*t# consider If + Then + )se
30
-
7/24/2019 BC2014_Session6
31/36
Decisions(contHd')
#f3nde : I $%en9 : 9 J >Y : VBA'!/r(9)
Else#f3nde : > $%enY : VBA'!/r(9)
Else#f3nde : 8 $%en
Y : 9Else
9 : IEnd#f
31
-
7/24/2019 BC2014_Session6
32/36
Decisions(contHd')
SelectCaseInde*.ariabeCase2
statements+Case5 to 52
statements+
CaseIs < 2statements+
Case9umtepsstatements+
CaseElsestatements+
EndSelect
32
otice that the .ca#e#/ can
be con#tant#( ranevalue#( con"ition# an"
variable#: thi# i# a
powerful control #tructure
that we will u#e to #elect
event# to e;ecute
-
7/24/2019 BC2014_Session6
33/36
7oops03terationsDoK&%ile'(ntil)#condition
statements*oop
lCount = 0
lNum = 10
Do Until lNum = 0
lNum = lNum 1 lCount = lCount + 1
Loop
lCount = 0
lNum = 10
Do While lNum > 0 lNum = lNum 1
lCount = lCount + 1
Loop
33
-
7/24/2019 BC2014_Session6
34/36
7oops(contHd')
+orcounter : start $oend LStepincre"entM#statements
,extcounter
otal 0
%or O
-
7/24/2019 BC2014_Session6
35/36
Eit Co""ands
Exit +unction2 3""ediatel% eits the +unctionprocedure in which it appears'
Eecution continues with the state"ent following the state"ent that calledthe +unction'
Exit Sub-
3""ediatel% eits the Subprocedure in which it appears'
Eecution continues with the state"ent following the state"ent that calledthe Subprocedure'
35
-
7/24/2019 BC2014_Session6
36/36
*hank Y1,