Sei sulla pagina 1di 7

1B40 Computing Visual Basic

1
Visual Basic: Objects and collections
Visual Basic is an (OO) object-oriented language. Performing a task in Visual Basic
(VB) or Visual Basic for Applications (VBA) involves manipulating various types of
objects eac! of "!ic! may !ave several #ifferent properties an# methods. $o perform a
task using VBA you return an object t!at represents t!e appropriate %&cel element an#
t!en manipulate it using t!e o'(ects) methods an# properties.
Objects
A simple statement Range(A1).Select illustrates an important c!aracteristic of
VB. $!e synta& of many statements first specifies an object Range(A1) an# an
action upon it Select. An o'(ect is a special type of varia'le t!at contains 'ot! #ata
an# co#e an# represents an element of %&cel. O'(ects e&ist only in t!e computer)s
memory* t!ey #on)t appear in your co#e. $!ere are many types of objects in VB an#
even more in %&cel VBA. %&cel o'(ects t!at you "ill encounter inclu#e t!e
Application o'(ect "!ic! represents t!e %&cel application itself t!e Worksheet
o'(ect representing a "orks!eet an# t!e Range o'(ect representing an in#ivi#ual cell or
a rectangular range of cells (e.g. cells A+,C- of t!e currently active "orks!eet).
O'(ects !ave types (ust as varia'les !ave #ata types.. O'(ect types are calle# classes.
.ork'ook .orks!eet an# /ange are (ust a fe" of %&cel)s o'(ect classes.
0or %&cel sprea#s!eets functions etc. to 'e controlle# an# manipulate# from a VBA
program t!ese 1t!ings2 in %&cel must !ave correspon#ing o'(ects t!at can 'e referre# to
in t!e program. $!e collection of o'(ects correspon#ing to 1t!ings2 in t!e %&cel
application is calle# t!e %&cel object model.
Methods
3n VB an action t!at an o'(ect can perform is referre# to as a method. $!us a method of
an o'(ect is a proce#ure t!at carries out some action involving t!e o'(ect. Consi#er t!e
o'(ect Dog. $o cause it to 'ark "e coul# "rite
Dog.Bark.
4o"ever a Dog is capa'le of more t!an 'arking for e&ample "e coul# !ave
Dog.Sit, Dog.Fetch.
3n %&cel for e&ample t!e statement
ActiveCell.Delete
calls t!e Delete met!o# of t!e ActiveCell o'(ect "!ic! #eletes t!e contents of
t!e
cell. 5ike any ot!er proce#ure a met!o# of an o'(ect can take one or more arguments as
in t!is e&ample,
ActiveCell.ACo!!ent "his is a co!!ent
$!e list of met!o#s t!at an o'(ect can perform #epen#s on t!e o'(ect. 0or e&ample t!e
Range o'(ect supports a'out 60 #ifferent met!o#s.
1B40 Computing Visual Basic
+
A method is accesse# 'y follo"ing t!e relevant o'(ect "it! a #ot an# t!en t!e name of t!e
met!o#.
Properties
An object can !ave properties. A property is a 7uality or c!aracteristic of t!e o'(ect e.g.
t!e lengt! of t!e #og)s tail t!e lou#ness of its 'ark. 3f you t!ink of objects as t!e nouns
of VB t!en properties are its a#(ectives an# methods are its ver's.
3n %&cel t!e properties may t!emselves 'e eit!er primitive #ata types suc! as num'ers
strings or Boolean values or may t!emselves 'e o'(ects of some kin#.
One of t!e many properties of t!e Application o'(ect is calle# #a!e an# is a
rea#only
string containing t!e name of t!e application i.e. 18icrosoft %&cel2. 3t can 'e
accesse# 'y a##ing a #ot an# t!e #a!e property after t!e o'(ect,
$sgBo% Application.#a!e
$!e Application o'(ect also !as a property calle# ActiveCell "!ic! represents
t!e currently active cell in t!e active %&cel "orks!eet. ActiveCell is an instance of
t!e o'(ect type calle# Range an# one of its properties is calle# &al'e an# represents
t!e value (num'er string or formula) !el# 'y t!e cell.
$!e statement
Application.ActiveCell.&al'e ( )ello
"ill place t!e string 14ello2 in t!e active cell.
8any properties of t!e Application o'(ect can 'e use# "it!out using t!e 7ualifier 9
Application in t!is e&ample * an# t!e a'ove statement coul# simply 'e "ritten
ActiveCell.&al'e ( )ello
5et)s consi#er in #etail t!e statement
Worksheets(sheet1).Range(A1).&al'e ( +
:tep 1 ; Worksheets(sheet1) evaluates t!e "orks!eets method an# returns t!e
object t!at refers to s!eet1. :o "e no" !ave
,Worksheet o-.ect that re/ers to sheet10.Range(A1).&al'e ( +
:tep + evaluates t!e Range method to return t!e o'(ect t!at refers to cell A1 of s!eet1.
:o "e no" !ave
,Range o-.ect that re/ers to cell A1 o/ sheet10.&al'e ( +.
:tep < evaluates t!e &al'e property of t!e range o'(ect at sets it to t!e num'er <.
Object variables
=ou !ave alrea#y come across several types of varia'le in VB inclu#ing numerical types
(e.g. 1nteger, Single, Do'-le) t!e String type an# t!e &ariant type
"!ic! can !ol# a value of any type. $!ere is also anot!er type of varia'le calle# an
1B40 Computing Visual Basic
<
2-.ect varia'le "!ic! can refer to any of t!e o'(ects in Visual Basic or in t!e %&cel
o'(ect mo#el.
$!e synta& for #eclaring an o'(ect varia'le is muc! t!e same as t!at for any ot!er
varia'le e.g.
Di! rangeA as Range
reserves space for a varia'le t!at "ill refer to an o'(ect of type Range.
One important #ifference 'et"een an o'(ect varia'le an# any ot!er type of varia'le is t!at
an o'(ect varia'le !ol#s only a reference to a specific o'(ect rat!er t!an t!e o'(ect itself.
($!e #ifference 'et"een references an# values "as #iscusse# in t!e lecture on mo#ules
an# proce#ures in t!e conte&t of passing arguments to su'routines an# functions.) $!is
#istinction may 'e clearer if "e consi#er a concrete e&ample using primitive an# o'(ect
varia'les,
Di! n'!A As 1nteger, n'!B As 1nteger
n'!A ( 1
n'!B ( n'!A
n'!B ( 3
$sgBo% (4A(4 5 n'!A 5 4, B(4 5 n'!B)
n'!B is a copy of n'!A so setting n'!B to !ave t!e value + !as no effect on n'!A
"!ic! still !as t!e value 1.
$!e situation is #ifferent for o'(ect varia'les,
Di! /ontA As Font, /ontB As Font
Set /ontA ( ActiveSheet.Range(4A14).Font
/ontA.Bol ( False
Set /ontB ( /ontA 6#ote7 /ontB an /ontA re/er to sa!e o-.ect
/ontB.Bol ( "r'e 6so changing o-.ect /ontB changes o-.ect
/ontA
$!e o'(ect referre# to 'y t!e varia'le /ontA represents t!e font use# to #isplay t!e
contents of cell A1. /ontB is a reference to t!e same o'(ect not a copy of it so "!en
t!e Bol attri'ute of /ontB is c!ange# /ontA is also affecte#.
=ou may also !ave notice# t!e use of t!e Set key"or# in t!e a'ove e&amples. $!is is
anot!er #ifference 'et"een o'(ect an# primitive varia'les, "!en assigning an o'(ect
reference to an o'(ect varia'le Set must 'e use# "!ile it is not nee#e# "!en assigning
a value to a primitive varia'le.
Collections
A collection is an o'(ect t!at contains a group of relate# o'(ects. %ac! o'(ect "it!in t!e
collection is calle# an element of t!e collection. Collections are o'(ects so !ave
associate# met!o#s an# properties.
An e&ample is t!e Sheets collection "!ic! represents t!e "orks!eets in t!e active
"ork'ook. $!is 'e!aves a 'it like an array in t!at a specific "orks!eet in t!e collection
can 'e reference# using a numeric in#e&,
1B40 Computing Visual Basic
4
Sheets(3).Activate
$!is makes t!e secon# "orks!eet active. >nlike a normal array t!e in#e& in a collection
o'(ect can 'e a name instea# of a num'er,
Sheets(Chart1).Activate
.!en you "ant to "ork "it! a single o'(ect you usually return one mem'er from t!e
collection. $!e property or met!o# use# to return t!e o'(ect is calle# an assessor.
$!ere are some useful "ays of #ealing "it! collections 'uilt into t!e VB language. 0or
e&ample to loop over all t!e mem'ers of a particular collection one can use t!e For
8ach synta&,
Di! range9 As Range, cell: As Range
Di! i As 1nteger
Set range9 ( ActiveSheet.Range(4A17C+4)
i ( 1
For 8ach cell: 1n range9.Cells
cell:.&al'e ( i
i ( i ; 1
#e%t
$!e a'ove piece of co#e uses a loop in "!ic! t!e o'(ect varia'le cell: refers to eac!
cell mem'er of t!e collection range9.Cells in turn. 3t assigns t!e value 1 to A1 + to
A+ < to A< 4 to B1 etc an# to - to C<. 3n t!is case "e coul# simply !ave "ritten
range9 instea# of range9.Cells 'ut see "!at !appens if you c!ange it to 0or
%ac!
cell= 3n range9.Ro<s. ?o" Range9 represents t!e same range of cells in eac! case
'ut range9.Cells an# range9.Ro<s represent t"o #ifferent collections of
o'(ects.
3n t!e first case t!e mem'ers are in#ivi#ual cells 'ut in t!e secon# case t!e mem'ers are
ranges representing rows of cells "it! eac! ro" 'eing itself a collection "it! its o"n
mem'ers (t!e in#ivi#ual cells).
The With statement
$!e With statement provi#es a "ay to carry out several operations on t!e same o'(ect
"it! less typing an# often lea#s to co#e t!at is easier to rea# an# un#erstan#. 0or
e&ample instea# of
Selection.Font.#a!e ( 4"i!es #e< Ro!an4
Selection.Font.FontSt=le ( 4Bol4
Selection.Font.Si>e ( 13
Selection.Font.Color1ne% ( +
one can "rite
With Selection.Font
.#a!e ( 4"i!es #e< Ro!an4
.FontSt=le ( 4Bol4
.Si>e ( 13
.Color1ne% ( +
8n With
1B40 Computing Visual Basic
@
Using the macro recorder to build an expression
$!e macro recor#er is a convenient "ay to 'uil# e&pressions t!at return o'(ects as it
kno"s t!e o'(ect mo#el of t!e application an# t!e met!o#s an# properties of t!e o'(ects.
4o"ever it can pro#uce very ver'ose co#e. Consi#er t!e follo"ing e&ample to c!ange
t!e siAe an# font in a c!art)s title,
S'- $acro1()
ActivateChart.Chart"itle.Select
With Selection.Font
.#a!e ( "i!es #e< Ro!an
.FontSt=le ( Bol
.Si>e ( 3?
.Strikethro'gh ( False
.S'perscript ( False
.S'-script ( False
.2'tlineFont ( False
.Shao< ( False
.@nerline ( False
.Color1ne% ( %lA'to!atic
.Backgro'n ( %lA'to!atic
8n With
8n S'-
$!is co#e contains many re#un#ant lines. Only t!e siAe an# fontstyle "ere c!ange# from
t!e #efault values. $!is co#e after recor#ing s!oul# 'e c!ange# to
S'- For!atChart"itle()
With Charts(Chart1).Chart"itle.Font
.FontSt=le ( Bol
.Si>e ( 3?
8n With
8n S'-
Setting and getting properties
.it! some properties you can set an# return t!eir values 9 t!ese are calle# rea#;"rite
properties. .it! some ot!ers you can only return t!eir values 9 t!ese are rea#;only
properties.
.e !ave alrea#y met e&amples of setting a property e.g.
Worksheets(Sheet1).Range(A1).&al'e ( ?3
Worksheets(Sheet1).Range(A1).&al'e ( A
Worksheets(sheeet3).Range(B3).&al'e
$o get t!e value property of cell A1 in s!eet1 "e "oul# use
!=&al'e ( Worksheets(sheet1).Range(A1).&al'e
$!ere are some properties an# met!o#s t!at are uni7ue to collections. $!e Count
property is one. 3t returns t!e num'er of elements in a collection. 3t is useful if you "ant
to loop over t!e elements of t!e collection (t!oug! t!e For Each Next loop is
prefera'le). $!e follo"ing e&ample uses t!e Count property to loop over t!e "orks!eets
in t!e active "ork'ook !i#ing alternate ones,
1B40 Computing Visual Basic
B
S'- )ie8ver=2therSheet()
For i ( 1 "o Worksheets.Co'nt
1/ i $o 3 ( B "hen
Worksheets(i).&isi-le ( False
8n 1/ over collections
#e%t i
8n S'-
ooping on collections
One can loop over collections using variants of t!e a'ove e&ample. 4o"ever t!e
recommen#e# "ay is to use t!e For Each Next loop. 3n t!is structure VB
automatically sets an o'(ect varia'le to return in turn eac! o'(ect in t!e collection. $!e
follo"ing co#e loops over all "ork'ooks open in %&cel an# closes all e&cept t!e one
containing t!e proce#ure,
S'- CloseWork-ooks()
Di! <- As Work-ook
For 8ach <- 1n Application.Work-ooks
1/ <-.#a!e CD "hisWork-ook.#a!e "hen
<-.Close
8n 1/
#e%t <-
8n S'-
The !ange object and method
$!e range o'(ect can represent a single cell a range of cells an entire ro" or column
even a <;C range. $!e range o'(ect is unusual in representing 'ot! a single cell an#
multiple cells.
One of t!e most common "ays to return a range o'(ect is to use t!e range met!o#. $!e
argument to t!e range met!o# is a string e.g. A1 or a name 1my/ange2.
%&amples are,
Range(B1).For!'la ( (1BERA#D()
Range(C178+).&al'e ( F
Range(A1, 8+).ClearContents
Range(!=Range).Font.Bol ( "r'e
Set ne<Range ( Range(!=Range)
The Cells method
$!e cells met!o# is similar to t!e range met!o# e&cept t!at it take s numeric
arguments instea# of string arguments. .!en use# to return a single cell t!e first
argument is t!e ro" t!e secon# is t!e column. 0or e&ample for cell B1
Cells(1,3).For!'la ( (1BERA#D()
1B40 Computing Visual Basic
D
$!e cells met!o# is particularly useful if you "ant to refer to cells in a loop using
counters. $!e e&ample loops t!roug! t!e cells A1,C10 an# replaces any "!ose value is
less t!an 0.01 'y Aero.
S'- Set"oGero()
For col1ne% ( 1 "o ?
For ro<1ne% ( 1 "o 1B
1/ Worksheets(Sheet1).Cells(ro<1ne%,Col1ne%) CA
B.B1 "hen
Worksheets(Sheet1).Cells(ro<1ne%, A
col1ne%).&al'e ( B
8n 1/
#e%t ro<1ne%
#e%t col1ne%
8n S'-
Combining !ange and Cell method
=ou can com'ine t!e range an# cell met!o#s. :uppose you "ant to create a range o'(ect
#efine# 'y a top ro" a 'ottom ro" an# left an# rig!t columns. $!e co#e 'elo" returns a
range o'(ect t!at refers to cells A1,C10. $!e cells met!o# #efines cells A1 an# C10 an#
t!e range met!o# t!en returns t!e o'(ect #efine# 'y t!ese cells,
Set area2-.ect ( A
Worksheets(Sheet1).Range(Cells(1,1), Cells(1B,?))
The O""set method
:ometimes you "ant to return a range t!at is a certain num'er of ro"s an# columns from
anot!er cell. $!e 2//set met!o# takes an input range o'(ect "it! ro<o//set an#
col'!no//set arguments to return a range. :uppose t!e #ata in a column of cells is
eit!er a num'er or te&t. $!e follo"ing co#e "rites 1$e&t2 or 1?um'er2 in t!e a#(acent
column.
For 8ach c in Worksheets(sheet1).Range(A17A1B).Cells
1/ Application.1s"e%t(c.&al'e) "hen
c.2//set(B, 1).For!'la ( "e%t
8lse1/ Application.1s#'!-er(c.&al'e) "hen
c.2//set(B, 1).For!'la ( #'!-er
8n 1/
#e%t c

Potrebbero piacerti anche