You are on page 1of 5

Lesson

nTranscrip
pt

Chandoo.org

Understandingg&UsinggCellsObjectinV
VBA

[00:00:000minutes]
Helloevveryone,welcometohttp
p://vbaclassees.com.ThisisVijaySharrma.Intodayy'slesson,w
wewillbe
learningg how we usse the cells object
o
that hhas been pro
ovided to uss in Microsooft Excel. Cells are all
those in
ntersections of a row and column that we see
e and make
e use of dayy in and dayy out by
providin
ng and inputtting values that make up our spre
eadsheets. Often,
O
it is rrequired of us to do
somethiingorwrite codesothattsomecalcuulationsorfo
ormattingha
appensautoomaticallyussingcells.
So,wew
willbelearningafewthin
ngsaboutth ecellsobjecct.

[00:01:000minutes]
Let's go
o to the VBA window and
a
insert aa blank module. We'll start with aa blank sub
b routine
namedTTestingCells.Theveryfirrstthingthattwewantto
ocheckisusingthecells object.IfIjustwrite
cellsoveerhereand putadot,Iw
willseeallthhemethods andproperttiesthatareexposedtothecells
object.TTheyaremoreorlesssim
milartotherrangeobject anditisadvvisablethatiinsteadofussingcells,
weusettherangeob
bject.Youca
anseealltheeseoptions.Themajorittyoftheareeasorreason
nswhere
we use cells are th
he ClearConttents methood which will remove everything inn all the cells in the
current sheet.WeaalsomakeusseofClearFoormatswhen
nwewantto
ogetridofttheformattinginthe
cells.Let'screatea basictableinthesheet sothatwe canmakeusseofthecelllsobject.Iw
willwrite
Headingg1hereandthenjustusetheautofiillhandletocreatesome
eheadingsfoorme.Ihave
ecreated
10 head
dings over here. I will no
ow add in s ome random
m numbers over
o
here. I will copy and paste
themassvaluesbecaauseIdon'tw
wantthemttochange.N
Now,wehave
esomedum
mmydatawitthusand
wewillsseewhatweecandowith
hthecellsobbject.

[00:03:117minutes]
Bringup
ptheVisual Basicwindo
owonthesccreen.Theveryfirstthin
ngthatIwannttoseeis thetotal
countoffcellsthathaavebeenocccupiedinthiissheet.IfIttrytocounttthecolumnssoccupied,in
nsteadof
the currrent data area, Excel providess me the total num
mber of coolumns exp
posed in
thisworrksheetwhichis16,384.Similarly,if Iwanttokn
nowhowma
anyrowsIhaave,wecan seethat
wehavee1millionro
ows.Howeve
er,wewanteedtocountthenumbero
ofcellshere andithasth
hrownus
anerrorrwhenwew
wroteCells.Co
ountbecauseewehavenotadvisedw
wherewewaanttocountthecells.
So,wew
willwrite:
MsgB
BoxCells.CurrrentRegion.Count
Iget1400astheresu
ult.Let'stakeamanualccountofthissIhave14rowsofdattaand10columnsof
dataso
o,ifIselect everything, Icanveryeeasilyseethaatthecountif140.Inthheveryfirst instance
wherew
wejustused Cells.Count,,wegotan errorbecaussewedidno
otspecifyth eareathat Iwanted
theVBA
Acodetocou
untthedatafrom.Itisnnotagoodprracticetouseitdirectly likethis.We
eneedto
specifyw
whichareao
ofregionweareworking oninordertogetthecu
urrentcountt.

Page1off5

Lesson
nTranscrip
pt

Chandoo.org

[00:06:440minutes]
Similarlyy,ifIwanted
dtoknowhowmanyrow
wsIhaveoccupied,Icanw
write:
MsgB
BoxCells.CurrrentRegion.R
Rows.Count
When I press F5, I can see tha
at I have occcupied 14 rows
r
of whicch 1 is my hheader row and the
remainin
ng13aremydatarows.WhenIknoowthatIhavveaheaderrow,Icanvveryeasilysu
ubtract1
overherreanditwilltellmethatIhave13roowsofdata:
MsgB
BoxCells.CurrrentRegion.R
Rows.Count 1

[00:07:115minutes]
Similarlyy,Icansay:
MsgB
BoxCells.CurrrentRegion.Columns.Couunt
Weget 10asthereesultwhichisswhathave beenusediinthecurren
ntregion.If Iinsert4bla
ankrows
hereand
drunthecod
de,whathap
ppens?
MsgB
BoxCells.CurrrentRegion.R
Rows.Count
We get 10 as the output still. The
T reason i s that we sttart from cell A1 and theere are no breaks
b
in
between
ntillrownum
mber10.The
ereisabreaakafterthatandthendatastartsagaainfromrow
wnumber
15.So,w
whenweuseeCells.CurrentRegion,it willonlycou
unttheareatillthetime itfindsabre
eak.That
iswhat ithasdone. Ihavehund
dreditemsinnthistablen
now10row
wsand10coolumns.How
wever,ifI
wanted togetacou
untofthissection,Ineeedtospecifyymystarting
gpoint.Int hiscase,myystarting
areaisrownumber15andtheccolumnis1.SSo,Iwillsay:
MsgB
BoxCells(15,1).CurrentR
Region.Rows. Count
Now,Isshouldget4 whenIrun thecodeanndthatiswh
hatIget.The
ecurrentreggionhasnow
wstarted
countinggfromcellA
A15andhassshownmethhatIhaveused4rowsfro
omthispoinnt.Thisishow
wwecan
makeusseofCurrentRegion.Row
ws.Count.Itiisusefulwhenwearegettingdataffromadatab
baseand
ourupdatingoneofourrawdatasheets.

[00:10:004minutes]
WehaveecoveredCu
urrentRegion
nandCount inthisexam
mple.Attime
es,whenwehaverawda
atainput
inoneo
oftheExcelssheetsandw
wewanttoclleartheexistingrawdatabeforeweegetnewraw
wdatain
to my sheet, how can we make
e use of the cells objectt? I normallyy don't use ccells; I use the range
object.H
However,inthisexample
e,Iwillshow
wyouhowto
ousethecellsobjecttoaaccomplishtthesame
thing.W
Wewillassum
methatthis isourrawddataandbefforeweimpo
ortournewrawdataovverhere,
we need
d to clear th
his. So, I will delete theese blank ro
ows manually. This is ouur raw data and our
objectiveistocleartthisusingVB
BAcodeand thecellsobjject.Let'ssta
artanewsubbprocedure
SubcclearRawDatta()
Sheeets("Sheet").Select
EndSSub
IfIhadn
namedmysheetrawdatta,Iwouldhaavewrittenrawdataherre.AnotherqquicktipthatIwould
liketosharehereis thatinstead
dofusingShheetsandpro
ovidingthen
nameofthe sheetthatyyouwant
u can give a name to th
he sheet object itself. Ass you can se
ee in the
to select in double quotes, you
ProjectEExplorer,weehaveSheet1andwehavve,withinbrrackets,Shee
et1writtenooverhereandSheet2

Page2off5

Lesson
nTranscrip
pt

Chandoo.org

and Sheeet3. If I bring up the Properties


P
W
Window, if I select Sheett1 here, theere is a nam
me within
bracketssasSheet1aandthenthe
ereisanothe rnamehere
easSheet1.T
Thesecondiinstanceoftthename
whichissnotinbracketsisthen
namethatis visibleonth
hescreenintheExcelw
worksheet.So
o,ifIput
thenam
measrawDattaandpressenter,youccanseethattithaschangedthenam
meoftheshe
eethere.
Howeveer, another good
g
way off naming thee object is that
t
you putt the name of the object in the
actualnameintheP
PropertiesW
Windowoverhere.Sinceitisasheetobject,Icannsaysht(threeliteral
characteersthatiden
ntifytheobje
ect)andIca nthensayrawdata.WhenIputintthisname,th
hevisible
name on
n the screen
n has not changed. It wiill still remaiin Sheet1 be
ecause that is what I wa
ant to be
displayeed to the en
nd user. How
wever, in th e code, I caan now select the rawD
Data sheet by
b a new
method.Icansay:
shtrawd
data.Select

[00:13:449minutes]
There iss another diffference in this.
t
When w
we use the sheets
s
objecct and I put a dot over here,
h
the
autolisttmembersd
donotappea
arbecausew
wehavenotsetitasan object.So, Ihavetotypeselect
overherre.Howeverr,whenIuse
etheobject nameitselfaandputado
ot,theauto listmemberrsappear
automatticallyandIccanmakeusseofthemasspermyreq
quirement.T
Thechoiceisentirelyyou
ursabout
howyou
uwanttouseethis.Myre
ecommendattionistoidentifyeveryo
objectwithittsownuniqu
uename.
Howeveer,itisaperssonalchoice.Ifyouwantttouseit,ittisagoodop
ption.Ifyou don'twanttouseit,
youcanstilllivewith
houtit.

[00:14:443minutes]
Let'sgettbacktoourrobjectiveo
ofclearingthherawdata.SinceIhave
eusedthenaameobject,Iwilluse
thisonlyyandIwilld
deletethislin
ne.ThereasoonwhyIammakingsure
ethatIamsselectingthisssheetis
becausee if I have a report which has multipple worksheets within itt and I wantt to remove the data
from on
ne sheet, beffore I run th
he code whicch will remo
ove the data
a, I will ensuure that this rawdata
sheetis selectedsothatthecod
dedoesnotaaccidentlyw
wipeoutthedatafromannyothershe
eetwhich
ng. Often tim
mes, the raw
wdata sheetss are hidden from the eend user so it
i a good
can be vvery annoyin
practicetosay:
shtR
RawData.Visiible=xlSheettVisible
Onceweearedonew
withthecod
de,wecanaggainhideit fromtheenduser.Incaaseyouhide
etheraw
datasheeetinyourreports,makesurethatyyoufirstmakkeitvisibleb
beforeyouddoaselecto
otherwise
Excel will throw up
p an error because it w
will not be able to find it. The objeective is to clear
c
the
rawdataa.Let'saddth
hatasacom
mmenthere:
'clearrtherawdata
Weare startingfrom
mcellA2.Th
hisisendinggincellJ14 howeverIamnotworriiedaboutwhereitis
ending rright now beecause the CurrentRegio
C
on will automatically takke care of thhat. We havve a very
simpleliine;sincemyystartingare
eaisA2and notA1,Iwillsay:
Cells((2,1).Select
Cells((Selection,Seelection.End(xlToRight)). Select
Weare tellingtheccodethatIw
wanttostarttfromtheplacewherem
mycurrentsselectioniso
orwhere
myactivvecellis.Theen,startingffromcellA22,Iwanttosselectallthecellstotherightofitso
othatall
the colu
umns are selected. In ca
ase you don 't know how
w to get thiss, we can goo back to the Object

Page3off5

Lesson
nTranscrip
pt

Chandoo.org

Browserrandwecan
ntypexlToRigghthereanddthesearethefourdirecctionalmem
mbersthatwe
ecanuse
xlDown
n,xlToRight,xlToLeftand
dxlUp.Acom
mmonthingiswhynotu
usexlRight;llet'sseeifw
wehaveit
here.Yees,wehavexxlRightherebutitmight notbehavin
ngthesameeffectasperrthemovem
mentthat
wewanttohappen.So,wenee
edtousetheedirectioncconstantsoverhere.WhhenIrunthisscode,it
willnot clearthedaatarightnow
w,solet'sseeethiscode inaction.PressF8.Asssoonasthis linewas
executed, cell A2 go
ot selected. If we set thhis as the sttatement, an
nd before w
we run this code
c
and
evaluateeit,ifIbringgthemouse
epointeron thislineand
dpressF8,ttheselectionnrightnow ishaving
139.And
d,whenwe usedtheabove(2,1),w esaidthatw
wewanttosselectrownuumber2and
dcolumn
1.So,it isstartingfromrow139andpickinngupthelasstvaluehere
ewhichis1666andselecctingthat
cell.Butt,thatisnotwhatwewanted.So,ob viously,usin
ngCellsisnottwhatwew
wouldwanthere.

[00:21:559minutes]
Wewan
nttheselectiionfromthisspointtothhispointand
dwewillhavvetoreplaceethiswithth
heRange
object:
Rang
ge(Selection,Selection.En
nd(xlToRight))).Select
WhenI pressF8now
w,wecanseethattheheeadershavebeenselected.AsImaddeclear,Ido
on'tmake
useofth
hecellsobjeectveryoftenandsoIh aven'tencou
unteredthecorrectusaggeofthecellsobject
before.SSo,Iamlearrningaswell..

[00:22:336minutes]
Forthisexampleofclearingtherawdata,heenceforth,w
wewillmakeuseoftheraangeobjectonly.We
haveselectedalltheeheadingsan
ndwenownneedtoselecctalltherow
ws.So,wewiillsay:
Rang
ge(Selection,Selection.En
nd(xlDown)).SSelect
Icandirrectlycleartthataswell byusingCleearContents butIwantedtoshowyoouwhatwillhappen
whenw
weexecuteth
hiscodefirstt.So,justm
makethisVB windowab
bitsmaller.PPressF8;the
estarting
cellisseelected.Allm
myheadersareselectedaandmyentirretableisno
owselected. Icannowsa
ay:
Selecction.Clear
Thiswilllgetridofallthedata.R
Runthiscod eandthere wego.Thisisaseasyassitcanbe.H
However,
thereis asmalltip thatIwant tosharewitthyouallhe
ereassomeo
onewhoha sbeenworkkingwith
Excelovverthelastffewyears.W
Whenwerem
movethedatabyusingS
Selection.Cleear,eventho
oughthe
datahassbeenwiped
doutfromthescreen,thhedirtycellsswillstillrem
main.When weremovethedata
by usinggSelection.C
Clear, we acttually get ridd of the dataa; however, the dirty ceells still rema
ain there
andmayyincreaseth
hefilesizeovveraperiod oftime.Eve
enthoughth
hedataisnootvisibleorh
hasbeen
clearedout,thecellssremaindirtty.So,thesuuggestedme
ethodisusing
gClearConteents:
Rang
ge.ClearConteents
If I just use Clear, itt only clearss the data. B
But, ClearCon
ntents will remove everrything and so
s this is
whatIrecommendw
whenyouarredealingw
withaworkbo
ookthathassrawdatatoobesavede
everyday
andyouoverwritethedata.So,ifyouhave 100rowson
nday1andyyouhave5000rowsonda
ay5,and
you havve 300 rows on day 6 th
hen if you oonly use Sele
ection.Clear, the remainning 200 row
ws at the
bottom wouldstillb
bedirty.So,itisadvisablletouseCle
earContentsandthensavveyourworkbookso
ortheghostcellsarerem
movedandth
hesizeofyourworkbookkisoptimized.
thattheblankcellso

Page4off5

Lesson
nTranscrip
pt

Chandoo.org

[00:26:115minutes]
Inthissession,welearnthowtousetheceellsobjectan
ndtherewassomelearnninginvolvedforme
also. Wee also learntt how we ca
an use the R
Range objectt (as I have been doing earlier) and how we
cannotu
useCellsasitwillselecttthecellaspeertheaddre
ess.Incaseyo
ouhaveany questionsorqueries
intheco
ontextofthissession,pleasefeelfreeetoask.Inthecomingsessions,weewillbetalkingmore
aboutth
heRangeobjjectandafe
ewexamplessrelatedtotheRangeob
bject.Thisis VijaySharmasigning
off.Than
nkyou.

Page5off5

You might also like