Notes on Excel Macros 0301

39
 Notes on Excel Macros From: Jürgen Kozlik [email protected] +49 !! "#! $%9& 'u()ect: Notes on Excel Macros *ate: June #!4 ,ersion: $.! Abstract: ese are some notes on Excel macros an/ ,0 1rogramming tat 2 use/ 3or an internal training. e are (ase/ on Excel # in its Englis 5ersion. e notes are not a com1lete /ocumentation on Excel an/ ,isual 0asic. e realit is muc more com1lex. 6se at o7n risk. 8a5e 3un rea/ing tring an/ succee/ing. omments an/ corrections are a11reciate/. T a ble of Contents 1 Gettin g Start ed... ................................................................................ ...3 !.! *e5elo1er Menu ................................................................................. $ !.# 'ecurit 'etti ngs................................................................................$ 2 How to ecor d a Macro... ........................................................................ .! 3 How to "n a Macro.... ........................................................................ ....# $.! ;un 3rom te <i st o3 Macro s..................................................................." $.# =ll ocati ng a K e( oar/ ' ortcut to a Macr o.................................................9 $.$ =ll ocati ng an 2con or a Menu in a o ol(ar to a Macro...................................! $ T%e &'A Editor ..................................................................................... 12 ( Coding................................................................................................ 13 &.! >r iting lean o/e ............................................................................!$ &.# ,a ria(les........................................................................................!$ &.#.! 1es o3 ,aria(les ..................................................................................!$ &.#.# *eclaration o3 ,a ria(le s..... ........................................................ ..............!4 &.$ =// ressing ?()ects........................................................................... .!4 &.$.! >o rk(ooks........................................................................................... !4 &.$.# >o rkse ets.. .......................................................................... ..............!4 &.$.$ = ;ange o3 ells.....................................................................................!& &.$.4 = 'in gle ell.........................................................................................!& &.4 >o rking 7it ?()ects.........................................................................!& &.4.! 'elec tion.............................................................................................!& &.4.# Meto /s... ...........................................................................................!& &.4.$ r o1ert ies. ...........................................................................................!% &.& <oo1 s............................................................................................!% &.&.! <oo1 6N2 < on /itio n 2s r ue.....................................................................!% &.&.# <oo1 >82<E on/i tion 2s r ue.............................................................. .......!% &.&.$ <oo1 ?5 er Fix e/ Num(er o3 Elements...........................................................! &.&.4 <oo1 ?5e r = ll Elements o3 a 'et..................................................................! &.&.& Exiting <oo1s............................................................................. ...........! &.&.% Aetti ng ?u t o3 En/less <oo1s ............................................................... ......! age ! o3 $"

description

excel macros

Transcript of Notes on Excel Macros 0301

7/18/2019 Notes on Excel Macros 0301

http://slidepdf.com/reader/full/notes-on-excel-macros-0301 1/38

Notes on Excel Macros

From: Jürgen [email protected]+49 !! "#! $%9&

'u()ect: Notes on Excel Macros*ate: June #!4

,ersion: $.!

Abstract:

ese are some notes on Excel macros an/ ,0 1rogramming tat 2 use/ 3or an internaltraining. e are (ase/ on Excel # in its Englis 5ersion.

e notes are not a com1lete /ocumentation on Excel an/ ,isual 0asic. e realit is mucmore com1lex. 6se at o7n risk. 8a5e 3un rea/ing tring an/ succee/ing.

omments an/ corrections are a11reciate/.

Table of Contents

1 Getting Started......................................................................................3!.! *e5elo1er Menu.................................................................................$!.# 'ecurit 'ettings................................................................................$

2 How to ecord a Macro............................................................................!

3 How to "n a Macro................................................................................#$.! ;un 3rom te <ist o3 Macros..................................................................."

$.# =llocating a Ke(oar/ 'ortcut to a Macro.................................................9$.$ =llocating an 2con or a Menu in a ool(ar to a Macro...................................!

$ T%e &'A Editor.....................................................................................12

( Coding................................................................................................13&.! >riting lean o/e............................................................................!$&.# ,aria(les........................................................................................!$

&.#.! 1es o3 ,aria(les..................................................................................!$&.#.# *eclaration o3 ,aria(les...........................................................................!4

&.$ =//ressing ?()ects............................................................................!4&.$.! >ork(ooks...........................................................................................!4&.$.# >orkseets..........................................................................................!4&.$.$ = ;ange o3 ells.....................................................................................!&&.$.4 = 'ingle ell.........................................................................................!&

&.4 >orking 7it ?()ects.........................................................................!&&.4.! 'election.............................................................................................!&&.4.# Meto/s..............................................................................................!&&.4.$ ro1erties............................................................................................!%

&.& <oo1s............................................................................................!%&.&.! <oo1 6N2< on/ition 2s rue.....................................................................!%&.&.# <oo1 >82<E on/ition 2s rue.....................................................................!%&.&.$ <oo1 ?5er Fixe/ Num(er o3 Elements...........................................................!&.&.4 <oo1 ?5er =ll Elements o3 a 'et..................................................................!&.&.& Exiting <oo1s........................................................................................!&.&.% Aetting ?ut o3 En/less <oo1s.....................................................................!

age ! o3 $"

7/18/2019 Notes on Excel Macros 0301

http://slidepdf.com/reader/full/notes-on-excel-macros-0301 2/38

Notes on Excel Macros

&.% on/itions......................................................................................!&.%.! 23 en...............................................................................................!&.%.# 23 en Else BElsei3C................................................................................!"&.%.$ 'elect ase..........................................................................................!"

&. D>itD 'tatement..............................................................................!"

&." Error 8an/ling..................................................................................!9&.".! =5oi/ing Errors......................................................................................!9&.".# Error 8an/ling ;outine.............................................................................!9

! )eb"gging...........................................................................................21%.! 'ingle-'te11ing................................................................................#!%.# 0reak1oints.....................................................................................##%.$ ecking te ,alues o3 ,aria(les............................................................#$%.4 >atc >in/o7.................................................................................#$%.& *e(ug rints....................................................................................#4

* +ser ,n-"t/"t-"t.................................................................................2(.! 6ser 2n1ut.......................................................................................#&.# Messages to te 6ser..........................................................................#&

# 0ile ,n-"t/"t-"t..................................................................................2#".! >riting to a ext File..........................................................................#"".# ;ea/ing 3rom a ext File.....................................................................#"".$ 2m1orting a ext File into Excel.............................................................#9".4 6sing a File *ialog.............................................................................$

".4.! 'elect ?ne File......................................................................................$".4.# 'elect ?ne or More Files..........................................................................$!

New Excel 0"nctions..............................................................................32

1 Coand '"ttons and ot%er Controls........................................................33!.! 6se3ul ontrols.................................................................................$$!.# *esign Mo/e....................................................................................$$

!.$ 2m1ortant ro1erties o3 ontrols...........................................................$4

11 Excel and /t%er Microsoft A--lications......................................................3(!!.! 2nclu/ing <i(raries.............................................................................$&!!.# Make Excel 'en/ = Mail 7it M' ?utlook..................................................$%

12 +sef"l Ti-s..........................................................................................3*!#.! ?1timizing For '1ee/.........................................................................$!#.# *ate an/ ime..................................................................................$

!#.#.! 8ar/co/e/ BFrozen imeC.........................................................................$!#.#.# <i5e Burrent imeC................................................................................$"

!#.$ our o/e *oesnt 'tartG......................................................................$"

age # o3 $"

7/18/2019 Notes on Excel Macros 0301

http://slidepdf.com/reader/full/notes-on-excel-macros-0301 3/38

Notes on Excel Macros

1 Getting Started

1.1 Developer Menu

Man macro actions are accesse/ o5er te *e5elo1 menu 7ic is ( /e3ault inacti5e. oacti5ate /o te 3ollo7ing:

!. lick on te Excel circle in te u11er le3t corner o3 te Excel 7in/o7 Bor t1e =lt-FC

#. lick on HExcel ?1tionsI

$. 'elect te tir/ o1tion: H'o7 *e5elo1er ta( in te ;i((onI

1.2 Security Settings

Macros are 1rograms tat ma /o lots o3 tings tat ou /ont ex1ect tem to /o. <ike 7itan oter 1rogram ou soul/nt trust tem too muc.

Macro 'ecurit 'ettings are in te menu )e4elo-er 5 Macro Sec"rit6:

age $ o3 $"

7/18/2019 Notes on Excel Macros 0301

http://slidepdf.com/reader/full/notes-on-excel-macros-0301 4/38

Notes on Excel Macros

Four le5els o3 securit are /e3ine/:

Hint: 6suall te D*isa(le all macros 7it noti3icationD setting is su33icient.

23 ou o1en Excel seets o3 unkno7n relia(ilit:

!. Kee1 7it macros /isa(le/ Bel1 1rotect meC

#. eck te macro co/e 7eter it seems sa3e

$. lose te 3ile

4. 23 te macro co/e seems sa3e reo1en te 3ile 7it ena(le/ macros

age 4 o3 $"

7/18/2019 Notes on Excel Macros 0301

http://slidepdf.com/reader/full/notes-on-excel-macros-0301 5/38

Notes on Excel Macros

>en o1ening an Excel 3ile tat contains macros ou ma (e 1rom1te/ 7eter ou 7antto acti5ate tem:

age & o3 $"

7/18/2019 Notes on Excel Macros 0301

http://slidepdf.com/reader/full/notes-on-excel-macros-0301 6/38

Notes on Excel Macros

2 How to ecord a Macro

is is use3ul 7en ou a5e to /o te same seuence o3 actions again an/ again.

!. <aunc te macro recor/er B)e4elo-er 5ecord MacroC

#. ?1tionall: /e3ine a macro name B/e3ault: DMacroD an/ a num(erC an/or a sortcutke.Hint: use 'i3t+<etter as a sortcut in or/er not to o5er7rite Excel ke(oar/sortcuts like trl-? trl- trl-'...

$. er3orm te actions tat ou 7ant to recor/

age % o3 $"

7/18/2019 Notes on Excel Macros 0301

http://slidepdf.com/reader/full/notes-on-excel-macros-0301 7/38

Notes on Excel Macros

4. 'to1 recor/ing B)e4elo-er 5 Sto- ecordingC

No7 te actions a5e (een sa5e/ into a macro.

age o3 $"

7/18/2019 Notes on Excel Macros 0301

http://slidepdf.com/reader/full/notes-on-excel-macros-0301 8/38

Notes on Excel Macros

3 How to "n a Macro

3.1 Run from the List of Macros

e list o3 macros can (e accesse/ 7it te menu )e4elo-er 5 Macros Bor &iew 5 Macros7or sim1l 7it Alt80#. 'elect our macro an/ click on D"nD. e (utton DSte- ,ntoD is goo/3or /e(ugging.

age " o3 $"

7/18/2019 Notes on Excel Macros 0301

http://slidepdf.com/reader/full/notes-on-excel-macros-0301 9/38

Notes on Excel Macros

3.2 Allocating a Keyboar Shortcut to a Macro

23 ou /ont assign a ke(oar/ sortcut /uring te recor/ing ou can /o so later. ?1en telist o3 macros 7it Alt80# 1ick our macro an/ click /-tions.

No /igits are allo7e/ onl letters (ut tese are case-sensiti5e.

'ome ke(oar/ sortcuts are alrea/ taken 3or someting else like trl-= trl-? trl-'trl-> Btr tisLC

Hint: 2t is sa3er to use trl-'i3t-<etter.

?nce te sortcut is /e3ine/ ou can run our macro rigt 3rom te ke(oar/.

age 9 o3 $"

7/18/2019 Notes on Excel Macros 0301

http://slidepdf.com/reader/full/notes-on-excel-macros-0301 10/38

Notes on Excel Macros

3.3 Allocating an !con or a Menu in a "oolbar to a Macro

For a/5ance/ users an/ teir 3a5orite macros tat must al7as (e a5aila(le:

6se te 7ell i//en (utton 3or te Excel /-tions.

'elect te categor DC"stoi9eD coose comman/s 3rom HMacrosI an/ select tose o3our macros tat ou 7ant to a11ear in te uick =ccess ool(ar. lick HAddI. 6sing teHModif6I (utton ou can allocate an icon to our macro.

=3ter tis our macro 7ill (e a5aila(le in te uick =ccess ool(ar. 6n3ortunatel 7itExcel # it is no longer 1ossi(le to mo/i3 te tool (ars Bno7 calle/ ri((onsC.

age ! o3 $"

7/18/2019 Notes on Excel Macros 0301

http://slidepdf.com/reader/full/notes-on-excel-macros-0301 11/38

Notes on Excel Macros

age !! o3 $"

7/18/2019 Notes on Excel Macros 0301

http://slidepdf.com/reader/full/notes-on-excel-macros-0301 12/38

Notes on Excel Macros

$ T%e &'A Editor

ou /ont nee/ al7as to recor/ actions to create a macro. ou can also co1 an existingmacro an/ mo/i3 it or ou can 7rite it 3rom scratc. is is /one in te ,0= e/itor. e

1rogramming language is calle/ ,0= B,isual 0asic 3or =11licationsC.e ,0= E/titor is launce/ 3rom Excel or an M' ?33ice a11lication 7it 'tart E/itor 7itD)e4elo-er 5 &is"al 'asicD or sim1l ( t1ing Alt8011.

e ,0= e/itor consists o3 se5eral 7in/o7s. e most im1ortant are:

• e ro)ect >in/o7 Busuall on te le3tC so7s all o1en Excel 3iles 7it teir7orkseets an/ teir mo/ules. 23 ou nee/ a mo/ule 3or an Excel 3ile use a rigt-click an/ D2nsert Mo/uleD.

• e o/e >in/o7 so7s te co/e. e current line is marke/ in ello7 (reak1ointsare marke/ in /ark re/.

• e 2mme/iate >in/o7 can (e use/ to t1e comman/s /irectl. 2t is also use/ to/is1la /e(ug.1rints

• e >atces >in/o7 so7s te 5alues o3 7atce/ 5aria(les.

• e all 'tack so7s 7ic 3unction calls 7ere use/ to get to te current 1ositionin te co/e. 2t can (e o1ene/ 7it Ctrl8 an/ close/ 7it Esc.

• e ?()ect 0ro7ser so7s te a5aila(le classes 1ro1erties meto/s etc. tat oucan use. 2t can (e o1ene/ 7it 02 an/ close/ 7it Ctrl80$.

e /is1la o3 te 7in/o7s is controlle/ 7it te &iew menu.

age !# o3 $"

7/18/2019 Notes on Excel Macros 0301

http://slidepdf.com/reader/full/notes-on-excel-macros-0301 13/38

Notes on Excel Macros

( Coding

#.1 $riting %lean %oe

omments start 7it an a1ostro1. e rest o3 te line is ignore/.

' This macro does the following: ....Dim D as Integer, M as Integer, Y as Integer ' day, month and year of each purchase

0ut o3 course 5aria(les ma a5e names tat make comments unnecessar:

Dim DayOfPurchase as Integer, MonthOfPurchase as Integer, YearOfPurchase as Integer

<ong 1rogram lines can (e 7ritten o5er se5eral e/itor lines. 23 te last caracter o3 a line isan un/erscore BD ;DC it 7ill continue on te next line.

Answer = MsgBox("Do you want to move this ine!", _   vO#$ance % v&xcamation, _   "Be carefu'"

Hint: 23 ou 7rite 1ro1er comments ou 7ill still un/erstan/ our co/e next ear. ou/ont a5e ten secon/s time to 7rite a commentG en ou 7ill nee/ ten minutes sometime laterL

#.2 &ariables

(.2.1 T6-es of &ariables

,aria(les are o3 /i33erent t1es 7ic control teir 5alue range an/ te 3unctions ou canuse on tem.

2m1ortant 1es:

T6-e )escri-tion ,-licite )eclaration

0oolean rue or False

2nteger !%-(it signe/ integer

<ong $#-(it signe/ integer

'ingle $#-(it 3loat L

*ou(le %4-(it 3loat O  

*ate 3loat 5alue counting /as

'tring 5aria(le lengt P

?()ect a//ress o3 an o()ect

,ariant an o3 te a(o5e

Hint: 23 ou use a 5aria(le 3or Excel line num(ers /ont use Integer (ut )ong (ecause2nteger as a maximum o3 5alue o3 $#% 7ile Excel line num(ers can go u1 to %&&$&.

'ome o1erations can use 5aria(les o3 mixe/ t1es. ou can a// an 2nteger to a single3loating num(er. ou can 1ut an 2nteger num(er at te en/ o3 a string B3or messages likeDError in line !DC.

age !$ o3 $"

7/18/2019 Notes on Excel Macros 0301

http://slidepdf.com/reader/full/notes-on-excel-macros-0301 14/38

Notes on Excel Macros

(.2.2 )eclaration of &ariables

= /eclaration o3 a 5aria(le means tat ou 3ix a certain t1e to a certain 5aria(le name. 23ou /ont /o tis te 5aria(le 7ill (e o3 te D,ariantD t1e.

Ex1licit *eclaration in te 3irst line o3 a 1roce/ure or a 3unction:

Dim $urrent)ine As IntegerDim *uscrier As IntegerDim $ountry+ame

=rras can (e /eclare/ too. e arra in/ex starts 7it i3 not state/ oter7ise:

Dim A(-.. As )ong / -.- eements from . to -..Dim Monthy0Average(-1 as *inge / In2ex . exists, ut is 3roay not use2Dim Yeary0Average(1..4 5o 1.-1 / 6 eements from 1..4 to 1.-1

Hint: 6se O3tion &x3icit as te 3irst line in te co/e so tat accessing anun/eclare/ 5aria(le 7ill cause an error.

0esi/es te t1es mentione/ in ca1ter &.#.! tere are 3urter t1es tat relate to

o()ects like A33ication 7ie 8ange 7ieDiaog an/ *heet.

#.3 Aressing 'b(ects

8o7 o()ects can (e a//resse/ B1lease note tat te 1lural is use/: 'eets ells etc.C:

(.3.1 <or=boo=s

e acti5e 7ork(ook BExcel 3ileC can (e a//resse/ 7it Active9or:oo:.

(.3.2 <or=s%eets

>orkseets can (e a//resse/ ( teir name or ( teir num(er Bin te or/er te a11earstarting 7it !C: *heets("*heet-" or *heets(-.

e acti5e seet can (e a//resse/ 7it Active*heet.

age !4 o3 $"

7/18/2019 Notes on Excel Macros 0301

http://slidepdf.com/reader/full/notes-on-excel-macros-0301 15/38

Notes on Excel Macros

(.3.3 A ange of Cells

?ne cell ( a//ress: 8ange("B;"

'e5eral non-a/)acent cells togeter ( a//ress: 8ange("B;, $6"

= rectangle ( a//ress o3 to1-le3t an/ (ottom-rigt cell: 8ange("$<D>" or8ange("$<", "D>".

?ne ro7: 8ows(;

?ne or se5eral ro7s: 8ows (";6"

?ne column: $oumns(4 Bselecting column EC

?ne or se5eral columns: $oumns("?*"

=ll cells: $es

(.3.$ A Single Cell

= cells ( ro7 an/ column: $es(4,- 7ill a//ress cell =&

e acti5e cells can (e a//resse/ 7it Active$e.

= cell relati5e to te acti5e cell: Active$e@Offset(-, 1 7ill a//ress cell % 7encell =& 7as acti5e Bone ro7 /o7n t7o columns rigtC.

#.) $or*ing +ith 'b(ects

is ca1ter gi5es a 3e7 exam1les 7at ou can /o 7it some o()ects. ?3 course tere ismuc more.

(.$.1 Selection

?nce ou a5e selecte/ an o()ect ou can also a//ress it 7it *eection.

'election is /one ( a//ing .'elect to te o()ect like *heets(")iste"@*eect or8ange("&<&-."@*eect.

(.$.2 Met%ods

Action Code ear=

lear te selection *eection@$ear$ontents

*elete current line *eection@Deete *hift=x3 lines (elo7 are si3te/ u1

=/)ust 7i/t o3 allcolumns

$oumns@Auto7it

age !& o3 $"

7/18/2019 Notes on Excel Macros 0301

http://slidepdf.com/reader/full/notes-on-excel-macros-0301 16/38

Notes on Excel Macros

(.$.3 >ro-erties

Most 1ro1erties o3 an o()ect can (e rea/ an/ 7ritten.

>ro-ert6 Code ear=

Name o3 te current Excel3ile 5his9or:oo:@+ame

,alue o3 te acti5e cell Active$e@aue

Font size o3 te currentselection

*eection@7ont@*iCe

'et text colour o3 cell 04 tore/

$es(>,1@7ont@$oorIn2ex = < $oorIn2ex 5alues range3rom to &%

'et (ackgroun/ colour o3cell 04 to ello7

$es(>,1@Interior@$oorIn2ex= ;

$oorIn2ex 5alues range3rom to &%

'et (ackgroun/ colour o3

cell 04 to orange

$es(>,1@Interior@$oor =

8B(144,-4<,.

e tree 1arameters o3

te 8B 3unction are teintensities o3 re/ greenan/ (lue ranging 3rom to #&&

*is1la 5alues in column *7it tree /ecimals

$oumns("D"@+umer7ormat =".@..."

ell sall al7as so7te current /ate

8ange("$E"@7ormua ="=5ODAY("

*ate o3 last recalculationtime is mi/nigt.

Formula relati5e to teacti5e cell

Active$e@7ormua = "= 8$FG-H%-"

>en te acti5e cell is 0&te 3ormula 7ill (e"=A4%-" Bsame ro7 one

column to te le3tC

#.# Loops

(.(.1 oo- +NT, Condition ,s Tr"e

/ )oo:ing for first em3ty ce in coumn A = .Do  = % -)oo3 nti $es(, -@aue = ""

(.(.2 oo- <H,E Condition ,s Tr"e

/ )oo:ing for first nonGem3ty ce in coumn A = -Do 9hie $es(, -@aue = ""  = % -)oo3

=lso 1ossi(le 7it >82<E->EN*:

9hie $es(, -@aue = ""  = % -9en2

age !% o3 $"

7/18/2019 Notes on Excel Macros 0301

http://slidepdf.com/reader/full/notes-on-excel-macros-0301 17/38

Notes on Excel Macros

(.(.3 oo- /4er 0ixed N"ber of Eleents

Year*um =.7or Month = - 5o -1  Year*um = Year*um % Month*um(Month+ext

(.(.$ oo- /4er All Eleents of a Set

*u ProtectA*heets(  Dim 5his*heet As 9or:sheet  7or &ach 5his*heet In 9or:sheets  Deug@Print "Protecting wor:sheet "J 5his*heet@+ame  5his*heet@Protect  +ext 5his*heet&n2 *u

(.(.( Exiting oo-s

23 ou nee/ an a//itional con/ition to lea5e te loo1 use &xit Do or &xit 7or:

7or Something   some action

  If somecondition 5hen &xit 7or  some more action

+ext

?r

Do 9hie Condition

  Some action

  If somecondition 5hen &xit Do  Some more action

)oo3

(.(.! Getting /"t of Endless oo-s2n case ou are caugt in an en/less loo1 tere are t7o 7as to get out:

!. ress trl-0reak BAerman ke(oar/: 'trg-auseCis /oes not al7as 7orkL

#. <aunc te task manager Btrl-'i3t-EscC locate te 1rocess EQE<.EQE an/ kill itis 7ill close our Excel 7orkseets 7itout sa5ingL

Hint: 'a5e our 7ork (e3ore running a ne7 macro. 23 ou nee/ to kill Excel ou still a5ete last sa5e/ 5ersion.

Hint: *uring /e5elo1ment ou soul/ sa5e earl an/ sa5e o3ten.

#., %onitions

(.!.1 ,f T%en

?ne con/ition one action:

If A3ha K . 5hen A3ha = A3ha % <;.

age ! o3 $"

7/18/2019 Notes on Excel Macros 0301

http://slidepdf.com/reader/full/notes-on-excel-macros-0301 18/38

Notes on Excel Macros

(.!.2 ,f T%en Else ?Elseif7

?ne con/ition t7o /i33erent actions:

If P KL . 5hen  $es(1, 4@aue = - P&se  $es(1, 4@aue = "cannot cacuate vaue"&n2 If

'e5eral con/itions 7it one action eac:

If A L A0Max 5hen  *tatus = "A is too high"&seIf B L B0Max 5hen  *tatus = "B is too high"&se  *tatus = "A an2 B are o:ay"&n2 If

(.!.3 Select Case

e 'elect ase 'tatements cecks one 5aria(le 3or /i33erent 5alues or ranges. 2t allo7se33icient usage o3 con/itions (ecause se5eral con/itions can (e grou1e/.

*eect $ase A87$+  $ase . 5o -1>, NE4 5o -.1<  D) = )(A87$+ % >4  $ase 4-1 5o 664  D) = )(A87$+ % N4  $ase &se  D) = "invai2"&n2 *eect

#.- $ith Statement

e D>itD 'tatement can (e use/ to 7rite sorter co/e 7en se5eral lines re3er to tesame o()ect. 2nstea/ o3

  *eection@7ont@+ame = "Aria"  *eection@7ont@7ont*tye = "*tan2ar2"  *eection@7ont@*iCe = --  *eection@7ont@$oorIn2ex = xAutomatic

)ust 7rite

  9ith *eection@7ont  @+ame = "Aria"  @7ont*tye = "*tan2ar2"  @*iCe = --  @$oorIn2ex = xAutomatic

  &n2 9ith

Note te 1oint at te start o3 te line.

age !" o3 $"

7/18/2019 Notes on Excel Macros 0301

http://slidepdf.com/reader/full/notes-on-excel-macros-0301 19/38

Notes on Excel Macros

#./ 0rror anling

(.#.1 A4oiding Errors

Hint: For e5er line o3 co/e tat ou 7rite consi/er 7at coul/ go 7rong

Exam1les:

• ou /i5i/e ( a num(er an/ it a11ens to (e zero.

• e user is 1rom1te/ 3or a text (ut e enters an em1t string.

• ou ceck all Excel lines (ut ou reac line %&&$& (e3ore our con/ition is met.

• ou 7ant to o1en a 3ile (ut it /oesnt exist.

• is ear is a lea1 ear so tere is a Fe(ruar #9t.

e o(5ious 7a is to ceck 3or tese error con/itions in te co/e:

If P <> 0 5hen  $es(1, 4@aue = - P&se  $es(1, 4@aue = "cannot cacuate vaue"&n2 If

?r

Do  Pro2uct = In3utBox("&nter name of 3ro2uct" 0  $hr(-< "()ine must not e em3ty", 0  "9hat are you oo:ing for!")oo3 ntil !en"Product# > 0

(.#.2 Error Handling o"tine

2n some error cases it is use3ul to (ranc to a /i33erent 1art o3 te co/e. For tis te ?nError statement can (e use/. 2n an case te &rr o()ect is a5aila(le 7it its 1ro1erties+umer an/ Descri3tion.

$n %rror &oTo 0 7ill /isa(le s1eci3ic error an/ling. E5er error is 3atal an/ 7ill sto11rogram execution.

$n %rror &oTo 7it a line la(el 7ill s1eci3 7ere to )um1 to in case o3 an error. <inela(els consist o3 a 7or/ 3ollo7e/ ( a colon. e line la(le must (e in te same 3unction orsu(routine.

$n %rror esume (e)t s1eci3ies tat in case o3 error te next line 7ill (e execute/.

is is use3ul i3 te &rr o()ect is cecke/ imme/iatel a3ter a critical o1eration 7ere anerror ma (e cause/ ( run-time en5ironment BFile not 3oun/ an/ te likeC.

age !9 o3 $"

7/18/2019 Notes on Excel Macros 0301

http://slidepdf.com/reader/full/notes-on-excel-macros-0301 20/38

Notes on Excel Macros

e 3ollo7ing 1iece o3 co/e /emonstrates te usage o3 all tree meto/s:

Puic *u My0*uroutine(  On &rror 8esume +ext  PerformSomeActionWithPotentialError / $ritica o3eration  *eect $ase &rr@+umer  $ase . / &rr@+umer = . means no error  $ase >1N / here is a s3ecific error  &rr@$ear / 8eset error  TidyUpInCaseOfError 

  If &rr@+umer L . 5hen  MsgBox &rr@+umer " " &rr@Descri3tion  TidyUpInCaseOfError 

  &xit *u  &n2 If  $ase &se / Dis3ay message ox with numer an2 2escri3tion  MsgBox &rr@+umer " " &rr@Descri3tion  TidyUpInCaseOfError 

  &xit *u  &n2 *eect  On &rror o5o 7in / +ow in case of error goto en2 of routine

  $a DoWhatYouIntendedToDo / 2o what is necessary when there is no error7in  TidyUpInCaseOfError 

  If &rr@+umer KL . 5hen MsgBox "7eher " 0  &rr@+umer " " &rr@Descri3tion&n2 *u

age # o3 $"

7/18/2019 Notes on Excel Macros 0301

http://slidepdf.com/reader/full/notes-on-excel-macros-0301 21/38

Notes on Excel Macros

! )eb"gging

,.1 SingleStepping

ou can ste1 troug a macro line ( line. is can (e launce/ 3rom te list o3 macros (selecting DSte- ,ntoD.

?r in te ,0 e/itor 7it te menu D)eb"g 5 Ste- ,ntoD

?r ( 1ressing D0#D.

age #! o3 $"

7/18/2019 Notes on Excel Macros 0301

http://slidepdf.com/reader/full/notes-on-excel-macros-0301 22/38

Notes on Excel Macros

e 3ollo7ing sortcuts can (e use/:

@e6 Action

F" 'ingle 'te1

'i3t-F" 'te1 o5er tis su(routine

trl-'i3t-F" 'te1 out o3 te current routine

trl-F" ;un until cursor

F& ;un until en/ Bor next (reak1oint see ca1ter %.#C

,.2 rea*points

ou can set (reak1oints in te co/e ( clicking into te gre area le3t o3 te co/e or (t1ing D0D. >en ou run te 1rogram it 7ill automaticall sto1 at te (reak1oint. ou7ill (e a(le to ceck 5aria(les or continue ( single-ste11ing.

0reak1oints are cleare/ te same 7a as te are set: clicking into te gre area or t1ingD0D.

age ## o3 $"

7/18/2019 Notes on Excel Macros 0301

http://slidepdf.com/reader/full/notes-on-excel-macros-0301 23/38

Notes on Excel Macros

,.3 %hec*ing the &alues of &ariables

>ile ou are in single-ste1 mo/e ou can ceck te 5alues o3 5aria(les:

• 2n te o/e >in/o7 mo5e te mouse o5er te name o3 a 5aria(le. = ello7 (alloon7ill a11ear an/ so7 its 5alue Bmouse is o5er DD in te exam1le (elo7C

• 2n te 2mme/iate >in/o7 1rint out te 5aria(le3rint Y

?r! Y

• 2n te >atc >in/o7 i3 ou a5e /eclare/ a D7atcD Bsee ca1ter %.4C

,.) $atch $ino+  

23 ou are intereste/ in te 5alue o3 a 5aria(le /uring te run o3 te 1rogram ou can/e3ine a 7atc to 7atc tis 5aria(le.

Easiest 7a to /eclare a 7atc: rig%t8clic= on a 4ariable nae in te co/e 7in/o7 an/select DAdd <atc%D 3rom te menu.

age #$ o3 $"

7/18/2019 Notes on Excel Macros 0301

http://slidepdf.com/reader/full/notes-on-excel-macros-0301 24/38

Notes on Excel Macros

>atces can (e /is1lae/ in te D>atcesD 7in/o7 o3 te e/itor. =t an (reak all 7atce/5aria(les an/ teir 5alues are /is1lae/.

Hint: >atces slo7 te 1rogram /o7n. 6se onl i3 necessar.

,.# Debug 4rints

ou can 7rite /e(ug 1rints into our co/e in or/er to a5e a trace. *e(ug 1rints are/is1lae/ in te 2mme/iate >in/o7.

Deug@Print $urrentaue

our /e(ug trace is muc more rea/a(le i3 ou a// a note a(out 7at ou are 1rintingout:

Deug@Print "$urrentaue"J $urrentaue

23 ou a5e macros tat run 3or a certain time it ma (e a goo/ i/ea to inclu/e a timestam1 in te /e(ug 1rint so tat ou kno7 te run time o3 5arious 1arts o3 our 1rogram.

Deug@Print 5imeJ "*tart sorting 2ata"

age #4 o3 $"

7/18/2019 Notes on Excel Macros 0301

http://slidepdf.com/reader/full/notes-on-excel-macros-0301 25/38

Notes on Excel Macros

* +ser ,n-"t/"t-"t

-.1 5ser !nput

e 2n1ut0ox can (e use/ to reuest in1ut 3rom te user:

  *earchItem = In3utBox("9hat are you oo:ing for!", "A uestion"

e ans7er is 1ro5i/e/ as a string 5aria(le 7ic ere is calle/ *earchItem. 23 te userclicks on DancelD or its te Esc-ke te 5aria(le is em1t.

-.2 Messages to the 5ser  

23 ou nee/ to gi5e an im1ortant message to te user an/ ma(e ask 3or a /ecision oucan use a message (ox:

  Decision = MsgBox("$onversion finishe2", vO#Ony, "*tatus"

  Decision = MsgBox("Do you reay want to 2eete the 2ata!", 0  vYes+o % v?uestion, "Be carefu'"

2t is o(5ious tat te 3irst 1arameter is te string tat a11ears in te message (ox an/ tetir/ 1arameter is te string in te title (ar o3 te message (ox.

age #& o3 $"

7/18/2019 Notes on Excel Macros 0301

http://slidepdf.com/reader/full/notes-on-excel-macros-0301 26/38

Notes on Excel Macros

e secon/ 1arameter is a numerical 5alue tat controls te a11earance an/ (ea5iour o3te message (ox. For co/e clarit it is use3ul not to use num(ers (ut te (uilt-in Excelconstants:

Constant &al"e )escri-tion

0irst gro"-: b"ttons

5(?K?nl *is1la ?K (utton onl

5(?Kancel ! *is1la ?K an/ ancel (uttons

5(=(ort;etr2gnore # *is1la =(ort ;etr an/ 2gnore (uttons

5(esNoancel $ *is1la es No an/ ancel (uttons

5(esNo 4 *is1la es an/ No (uttons

5(;etrancel & *is1la ;etr an/ ancel (uttons

Second gro"-: icons

5(ritical !% *is1la ritical Message icon5(uestion $# *is1la >arning uer icon

5(Exclamation 4" *is1la >arning Message icon

5(2n3ormation %4 *is1la 2n3ormation Message icon

T%ird gro"-: defa"lt b"tton

5(*e3ault0utton! First (utton is /e3ault

5(*e3ault0utton# #&% 'econ/ (utton is /e3ault

5(*e3ault0utton$ &!# ir/ (utton is /e3ault

5(*e3ault0utton4 %" Fourt (utton is /e3ault Bi3 a 8el1 (uttonis use/ 7ic 2 7ill not /escri(e ereC

et"rn Codes

5(?K ! D?KD selecte/

5(ancel # ancel

5(=(ort $ =(ort

5(;etr 4 ;etr

5(2gnore & 2gnore

5(es % es

5(No No

age #% o3 $"

7/18/2019 Notes on Excel Macros 0301

http://slidepdf.com/reader/full/notes-on-excel-macros-0301 27/38

Notes on Excel Macros

Exa-les:

  Decision = MsgBox("Do you reay want to 2eete the 2ata!", 0  vYes+o % v?uestion, "Be carefu'"  If Decision = vYes 5hen  @@@  &n2if

  Do  Decision = MsgBox("Qave you un2erstoo2!", vYes+o % vcritica  )oo3 nti Decision = vYes

lease note tat te return 5alue is an integer.

age # o3 $"

7/18/2019 Notes on Excel Macros 0301

http://slidepdf.com/reader/full/notes-on-excel-macros-0301 28/38

Notes on Excel Macros

# 0ile ,n-"t/"t-"t

/.1 $riting to a "e6t 7ile

ext 3iles are o1ene/ 7it a numerical an/le BO! in te exam1le (elo7C. e 3ollo7ingexam1le 7rites te 5alues o3 te cells 0! to 0! into a 3ile:

O3en "$R5em3R5estfie@txt" 7or Out3ut As S-7or = - 5o -.  Print S-, $es(, 1@aue+ext$ose S-

*ont 3orget to close te 3ile a3ter ou 3inise/ 7riting.

/.2 Reaing from a "e6t 7ile

ext 3iles are o1ene/ 7it a numerical an/le BO! in te exam1le (elo7C. e en/ o3 te3ile can (e cecke/ 7it te 3unction E?F 7it te 3ile an/le as 1arameter.

e statement )ine In3ut rea/s one com1lete line 3rom te 3ile Bterminate/ ( ;<FCan/ 1uts it into a string 5aria(le.

O3en "$R5em3R5esfie@txt" 7or In3ut As S-

9hie +ot &O7(-  )ine In3ut S-, strIn3ut  Deug@Print strIn3ut9en2$ose S-

*ont 3orget to close te 3ile a3ter ou 3inise/ rea/ing.

age #" o3 $"

7/18/2019 Notes on Excel Macros 0301

http://slidepdf.com/reader/full/notes-on-excel-macros-0301 29/38

Notes on Excel Macros

/.3 !mporting a "e6t 7ile into 06cel

>it O3en5ext ou ma o1en a text 3ile 7it Excel as ou 7oul/ /o 7it DFile R ?1enD 3ora text 3ile 7it te 3ollo7ing im1ort 7izar/:

2n ,0= te co/e 7oul/ look some7at like tis:

9or:oo:s@O3en5ext 7iename="$R5em3Rtestfie@txt", Origin=xM*DO*, 0  *tart8ow=-, Data5y3e=xDeimite2, 0  5ext?uaifier=xDoue?uote, $onsecutiveDeimiter=7ase, 0  5a=5rue, *emicoon=7ase, $omma=5rue, *3ace=7ase, Other=7ase

is 7ill o1en te 3ile $R5em3R testfie@txt an/ rea/ ta(-/elimite/ /ata. e 3ile7ill (e /is1lae/ in a ne7 Excel 7ork(ook.

age #9 o3 $"

7/18/2019 Notes on Excel Macros 0301

http://slidepdf.com/reader/full/notes-on-excel-macros-0301 30/38

Notes on Excel Macros

/.) 5sing a 7ile Dialog

ou can use a 3ile /ialog to 1ick one or more 3iles 3rom te 3ile sstem. = 3ile /ialog is ano()ect tat must (e /eclare/ like a 5aria(le so tat ou can access its 1ro1erties. 2t 7illreturn 1at an/ 3ile name togeter as a string. e /esire/ action Bo1en or sa5eC must (e

1rogramme/ se1aratel.

#.$.1 Select /ne 0ile

o 1ick one Q<' 3ile te name o3 7ic is returne/ in File! inclu/ing 1at:

Dim f2- As 7ieDiaog

Dim 7ie- As *tring

*et f2- = A33ication@7ieDiaog(mso7ieDiaog7iePic:er9ith f2-  @7iters@A22 "&xce fies", "T@xs"  @AowMuti*eect = 7ase  @*how  7ie- = @*eecte2Items(-  Deug@Print 7ie-&n2 9ith

age $ o3 $"

7/18/2019 Notes on Excel Macros 0301

http://slidepdf.com/reader/full/notes-on-excel-macros-0301 31/38

Notes on Excel Macros

#.$.2 Select /ne or More 0iles

23 ou 7ant to (e a(le to 1ick se5eral 3iles ou nee/ to set @AowMuti*eect to rue.e num(er o3 selecte/ 3iles is a5aila(le in te @$ount 1ro1ert. e names o3 te 3ilesare in te arra @*eecte2Item.

Dim f2- As 7ieDiaogDim 7ie- As *tringDim As Integer

*et f2- = A33ication@7ieDiaog(mso7ieDiaog7iePic:er9ith f2-  @AowMuti*eect = 5rue  @*how  7or = - 5o @*eecte2Items@$ount  7ie- = @*eecte2Items(  Deug@Print 7ie-  +ext &n2 9ith

age $! o3 $"

7/18/2019 Notes on Excel Macros 0301

http://slidepdf.com/reader/full/notes-on-excel-macros-0301 32/38

Notes on Excel Macros

New Excel 0"nctions

ou can /e3ine our o7n Excel 3unctions. e can (e calle/ like te (uilt-in Excel3unctions.

Functions take zero or more in1ut 1arameters. eir t1es /ont nee/ to (e /eclare/.

Functions return exactl one return 5alue. 2ts t1e /oesnt nee/ to (e /eclare/ eiter.

Puic 7unction )(A87$+  *eect $ase A87$+  $ase . 5o -1>  ) = 6N. % .@1 T A87$+  $ase 4-1 5o 664  ) = -E-.@1 % .@1 T (A87$+ G 4-1  $ase NE4 5o -.1<  ) = 6N. % .@1 T (A87$+ G -.1>  $ase &se  ) = "invai2"  &n2 *eect&n2 7unction

Puic 7unction D)(A87$+  *eect $ase A87$+  $ase . 5o -1>, NE4 5o -.1<  D) = )(A87$+ % >4  $ase 4-1 5o 664  D) = )(A87$+ % N4  $ase &se  D) = "invai2"  &n2 *eect&n2 7unction

age $# o3 $"

7/18/2019 Notes on Excel Macros 0301

http://slidepdf.com/reader/full/notes-on-excel-macros-0301 33/38

Notes on Excel Macros

1 Coand '"ttons and ot%er Controls

18.1 5seful %ontrols

DontrolsD are among oters:

Control A--earance ear=s

omman/ 0utton 6se/ to launc macros

'1in 0utton 6se/ to increment or/ecrement te 5alue o3te linke/ cell

'croll 0ar 6se/ to cange te 5alue

o3 a cell o5er a large range

?ter controls are eck 0oxes ext 0oxes ?1tion 0uttons <ist 0oxs om(o 0oxes an/oggle 0uttons (ut teir 3unctions can (e acie5e/ in Excel 7it (uilt-in meto/s. ou/ont nee/ a om(o 0ox 7en D*ata R ,ali/ationD o33ers ou te same (ene3it 7it lesse33ort.

18.2 Design Moe

2n te )e4elo-er menu tere is a (utton to s7itc te D)esign ModeD on an/o33:

?nce te /esign mo/e is on click on te ,nsert (utton an/ ten on te icon o3our /esire/ control. en /ra7 a rectangle 7it te mouse on te Excel seet.our /esire/ control 7ill (e tere an/ ou can mo/i3 its 1ro1erties.

age $$ o3 $"

7/18/2019 Notes on Excel Macros 0301

http://slidepdf.com/reader/full/notes-on-excel-macros-0301 34/38

Notes on Excel Macros

18.3 !mportant 4roperties of %ontrols

>eter it is a control (ox a s1in (utton a scroll (ar look at:

>ro-ert6 Meaning

8eigt>i/t 'ize o3 controlo1<e3t osition o3 control

,isi(le *etermines 7eter control is /is1lae/ or not

Ena(le/ *etermines 7eter control 7ill a5e an e33ect or not

a1tion ext o3 control (utton

0ackolor Foreolor olor o3 (ackgroun/ an/ 3oregroun/

icture 0ackgroun/ 1icture o3 control (utton

=ccelerator Ke tat as to (e 1resse/ togeter 7it D=ltD in or/er toaccess control

<inke/ cell ell to 7ic control is linke/ B3or scroll (ar s1in(utton ceck (ox etc.C

'mallange<argeange

'te1 sizes 3or s1in (uttons Bonl small cangeC an/ scroll(ars

Min Max 'mallest an/ largest 1ossi(le 5alues 3or scroll (ar an/s1in (utton

age $4 o3 $"

7/18/2019 Notes on Excel Macros 0301

http://slidepdf.com/reader/full/notes-on-excel-macros-0301 35/38

Notes on Excel Macros

11 Excel and /t%er Microsoft A--lications

11.1 !ncluing Libraries

ou ma control oter Microso3t a11lications B>or/ o7er1oint ?utlook ...C 3rom Excel.2t is reuire/ to inclu/e te oter a11lications o()ects so ou nee/ to ceck tea11ro1riate (oxes in te list tat ou can o1en 7it te menu DTools 5 eferencesD.

23 ou 7ant to a//ress ?utlook o()ects ou nee/ to inclu/e te ?utlook li(rar:

age $& o3 $"

7/18/2019 Notes on Excel Macros 0301

http://slidepdf.com/reader/full/notes-on-excel-macros-0301 36/38

Notes on Excel Macros

11.2 Ma*e 06cel Sen A Mail +ith MS 'utloo*

ou can make excel sen/ a mail using ?utlook 7ere a//ressee su()ect text etc. can (econstants or ma retrie5e/ 3rom Excel cells.

*u *en20A0Mai(

  Dim oA33 As Outoo:@A33ication / 5his is to o3en Outoo:  Dim oMai As MaiItem / A mai oUect, of which you can access the 3ro3erties

  *et oA33 = +ew Outoo:@A33ication  *et oMai = oA33@$reateItem(oMaiItem

  9ith oMai  @5o = "*ome@A22ressVsomewhere@xyJ *ome@Other@A22ressVsomewhere@xy" /*emicoon to se3arate a22resses  @$$ = "Any@Other@A22ressVsomewhere@xy"  @*uUect = "Qere is the suUect"  @Bo2y = "Qere is the text"  @Attachments@A22 "$R5em3Rtestfie@txt" / 5his can e 2one severa times  @Dis3ay / 5his is to 2is3ay an Outoo: win2ow with the mai

  @*en2 / 5his wi actuay sen2 the mai using Outoo:  &n2 9ith

  *et oMai = +othing / 8eease the mai item  *et oA33 = +othing / 8eease the Outoo: a33ication&n2 *u

6sing suc a routine ou can sen/ mails 7ere te /ata is taken out o3 Excel seets. emails 7ill (e store/ in ?utlookSs 3ol/er as usual.

Hint: *ont a(use tisL

age $% o3 $"

7/18/2019 Notes on Excel Macros 0301

http://slidepdf.com/reader/full/notes-on-excel-macros-0301 37/38

Notes on Excel Macros

12 +sef"l Ti-s

12.1 'ptimi9ing 7or Spee 

Excel co/e runs muc 3aster i3 ou s7itc o33 time consuming 1roce/ures.

=3ter ou cange te a11earance o3 someting Excel 7ill re/ra7 te screen. ou ma7ant to a5oi/ tis an/ re/ra7 te screen onl a3ter all our mo/i3ications are 3inise/.is is controlle/ 7it A33ication@*creen32ating.

=3ter ou a5e cange/ one cell Excel 7ill recalculate all cells tat /e1en/ on it. ou ma7ant to a5oi/ tis an/ launc te recalculation onl a3ter te mo/i3ication o3 all cells is3inise/. is is controlle/ 7it A33ication@$acuation.

'o at te start o3 our co/e ou ma use:

A33ication@*creen32ating = 7aseA33ication@$acuation = x$acuationManua

0ut /ont 3orget to return to te 1re5ious state (e3ore te en/ o3 te co/e:

A33ication@*creen32ating = 5rueA33ication@$acuation = x$acuationAutomatic

12.2 Date an "ime

12.2.1 Hardcoded ?0ro9en Tie7

23 ou nee/ to insert te current /ate or time as a constant so tat it 7ill not (e u1/ate/ou can /o te 3ollo7ing

1ing Ctrl8 BAerman ke(oar/: StrgB+sc%alt"ng8@oaC on te ke(oar/ 7ill 1ut tecurrent /ate into te selecte/ Excel cell. e time 7ill (e :. is is a constant tat7ill not (e u1/ate/.

1ing Ctrl8: BAerman ke(oar/: StrgB+sc%alt"ng8>"n=tC on te ke(oar/ 7ill 1ut tecurrent time into te selecte/ Excel cell. e /ate 7ill (e set to *a o3 Excels internalcalen/er Blike Januar t !9C. is is a constant tat 7ill not (e u1/ate/.

e ,0 co/e +ow 7ill return te current /ate an/ time as a constant tat 7ill not (eu1/ate/:

$es(-6, -@aue = ")ast change y macro"$es(-6, 1@aue = +ow$es(-6, 1@+umer7ormat = "yyyyGmmG22 hhmmss"

e cell 7ill not (e automaticall recalculate/T it is onl cange/ 7en te macro runs.

age $ o3 $"

7/18/2019 Notes on Excel Macros 0301

http://slidepdf.com/reader/full/notes-on-excel-macros-0301 38/38

Notes on Excel Macros

12.2.2 i4e ?C"rrent Tie7

23 ou nee/ to a5e te current /ate an/ time an/ te 5alue sall al7as (e u1/ate/ 7ente seet is recalculate/

$es(-;, -@7ormua = "=+O9("

2n te ,0 e/itor 5ime is a string tat gi5es ou te current time 7it a 1recision o3 ! s:

3rint time-4>.<1

is can (e use/ in /e(ug 1rints:

  Deug@Print 5ime, "GGGGGGG *5A85 GGGGGGG"

12.3 :our %oe Doesn;t Start<

23 our co/e 7ill not start Bneiter 3rom te Excel seet nor 3rom te ,0= e/itorC ten ouare 1ro(a(l in te (reak mo/e Breset stateC.

is is 5isi(le in te title (ar o3 te ,0= e/itor Bgreen arro7C.

ou nee/ to click on te ;eset 0utton Bre/ arro7C or use te menu D"n 5 esetD or teke(oar/ sortcutDAlt 5  D

EN) /0 )/C+MENT