440

Getting to Know Arc Objects

Embed Size (px)

Citation preview

Page 1: Getting to Know Arc Objects
Page 2: Getting to Know Arc Objects

lot rndllr! oQD ~,

Chaoter 1 Programming with oblects 1

SacHan, Understanding VBA

Chapter 2 Building a custom applicallon 5 Exemse 2a Ofganillng commands on a tooltwr 7 Exercise 2b Making your 0W'fl commands 16 Exerose 2c Storing val~ with variables 24

Chaoter 3 Creating a dialog box 37 Exerd!.e 3 Using controls to build a form 38

ght:x:l rna rial

Page 3: Getting to Know Arc Objects

UnderstAnding ArcObllhb

Chapter 9 MakinQ your own objects 133 E.Q'I'd~ 9a CrPating d.n~ 136 E~erdse 9b Creatlf"lg obie<U 142

Chapter 10 Programming W1th Interfaces 147 exercise lOa USing IApplication all!! IDocument ill Exefdse lOb USing multIple irnerlac:es 159

Chapler 11 Navigating object model diagrams 171 Exefcise l1a Getting laye~ 178 Exercise lib Creating and assigning colofs 188

Chapter 12 Making tools 199 Exercise 12a Reporting coordinates 200 E~ercise 12b Dr"....,!"!!! graphics 211 Exercise 12c Using TypeOf statements 221

S~ctJon 3 Usin g Ard)blecb

Chaoter 13 Executing commands 227 Exercise 13 lkinq COITlI1\olll!!Items all!! COITVT\aIl!!8a~ 228

Chapter 14 Adding layers to a map 239 Exercise 14a Addin9 a qeodatabase leatUie cI~ 242 Exercise 14b Adding a laster data se! 254

Chaoter 15 Seltlng laver symbologv 263 Exercise 15a Setting !aye! color 265 exerCISe ISb Selting!aye! symbols 273 Exercl!.t! 1 Sc Creating a class breaks rendefer 285

Chapter 16 USing ArcCatalog objects in ArcMap 295 Exerci!.t! 161 Adding \ayef files to ArcMap 299 Exerci!.t! 16b Making)'OUr own Add Data diaiog box 305

Chapter 17 Controlling feature display 315 E~ercise 17a Making definition queries 318 Exerci!.t! 17b $electing features and seiling the ~tion color 332

Chapter 18 Working with selected features 339 Exercise lSa Using selection sets 342 Exercise lab Usin9 cursors 348

CO NTENTS

Page 4: Getting to Know Arc Objects

CO NTENTS

Chapter 19 Making dynamic layouts 359 Exercise 19a Naming tlelTlfl1ts 362 ElI~ 19b Manipulating t~ eierT'oellts 370

Chapter 20 Editing tables 377 ElI~ 20a Adding l i~ds 379 ElIertise 20b Getting and setting values 390

What's next? 403

AppendIx A Data license agreement 405

Aopendlx a Installing the data 409

10M, 4! 1

Page 5: Getting to Know Arc Objects

W hy learn how to program ESRI · A rcObjects"' !

Think of ArcGIS· as a house that someone else has built and furnished for you. You move in and find that it has 10[5 of rooms, great furn iture, all the conveniences, artwork hangi ng on the wa lls, a swimming pool out back, everything you could ever want ... except rour own personal touch.

Learning how to program ArcObjec[5 with VBA means learning how to make ArcMap'" and A rcCata log'" your own . You may not even want to change them too much . Maybe remove a tool that you never use fro m a tool bar. O r take a certain menu choice and put it on a bulton. O r reduce some repet iti ve task to a single button click.

On the other hand. you might have plans to remodel the whole house.

Whatever the scope of your ambition, getting to know A rcObjects-and the concepts behind programming them-will give ~'ou a new level of confidence in your relationship with the software.

If you have li tt le or no programming experience, begin with the book's first section. "UnderstandinG" VBA." There you'lIleam about objects, properties, and methods; how to set variables; how to wri te procedures and link them to buttons on the user interface; how to use simple objects like message boxes; and how to employ program­ming constructs like If Then statements and Do While loops.

If ~'ou are already comfortable with an object-oriented language, especially Visual B.'lsic- (or Applications (VBA ) or Microsoft- Visual Basic, you may want to start with the second section, "Understanding ArcObjects." There you'lIleam about the A rcObjects architecture, how to read object model diagrams, and how to use

righted material

Page 6: Getting to Know Arc Objects

programming intcrfaccs. (If you havc a good idca what thc last sentcncc is talking about, you probably know eno ugh to skip the first section.)

The third section of the book, "Using A rcObjects," leads you through a number of G IS programming tasks, such as adding layers to maps, symbolizing and classifying data, making feature selections, querying dam, and t-diting feature attributes.

This is a workbook of hands-on exercises, supported by introducto ry discussio ns, diagrams, and screen captures. The exercises procel-ci step-by-step, showing every line of code that needs to be written and explaining its purpose. You will type lots and lots of code in this book. Please be assured that all the exercise code has been rib>orously tested to work as instructed. Exercise code can fail, ho wever, with even the smallest of typi ng mistakes. (But every mistake is an opportunity to learn.) If exercise code does fu il, you can go thro ugh it yourself to check for typos. At different stages in the book, you will be inuoduced to many of VBA's error identification techniqucs.

You arc cncouraged to save your work along the way, but yo u do n 't have to because each exercise is a new staning point, al read y prepared with maps, data, and any VBA code you nced. This is true even when the exercises build, as they often do, on wo rk you have done previously. Every exercise .. Iso includes a map document with the correct results, in case you get stuck. Each chapter has frolll one to four exercises (except fo r chaptcr I , which has none). The exercise Icnb'th varics, but as a rule, chapters should take twO to four hours to complete.

To usc (his book, you must have a copy of ArcVicw· , ArcEd iror"', o r Arclnfo'" versio n 8.3 (or a later version) running on your computer. The map documents used in thc exercises will not open on carlier vcrsions of the software. The CD thai comes with the book contains the exerc ise data you need, plus additional resources, but does not include the software itself. For instructions on insta lling the dam, refer ro appendix B.

Fo r the latest info rmation, Q & A's, addenda, and errata, visit the book's companion Web site at wtllw.esri .com/GTKArcObjects .

I NTllQDUCTrpN

Page 7: Getting to Know Arc Objects

Programming with objects

In this book, you willieam how to program ArcObjects with Visual Basic for Applications (VBA). This raises twO questions: what are ArcObject5 and what is Visual Basic for Applications ! You could say that ArcObjecu is a set of program­mable objects and Visual Basic for Applications is an object-Oriented programming language. That's true, but not very he lpful unless you know whm objcct·oriemed programming is.

Objed-orlellted pi ogrammlng Object -oriented programming is a structure o r design for computer programming languages. It resembles our own experience of the world. We see the world as divided into objects that have qualities, or properties, that behave in ccrtain ways. For instance, a tree is an objcC[, It has properties like a type (it could be an oak, a eucalyptus, o r a palm), a height, an age, and lots of other thinb'S you could specify (evergreen-yes or no! fru it-bearing-yes or no! and so on). A tree also has behav­iors. h may rustle in the wind or shed leaves in the full. It grows from a li ttle seed. One day it dies.

S imilarly, in an object-oriellted programming language, you work with objects thai have properties and behaviors (which arc called methods). Lots of these objects are familiar clements of software applications: buttons, tools. windows. and dialog boxes. Some afe complex and specialized. Depending on your programming job, you might use computer objects that represent heart valves. honey bee hives, or hurricanes.

Computer programs solve problems Of accomplish tasks: they beat you at chess. they guide rockets to Mars. they simulate a wide variety of human and natural processes. In object-oriented programming, you accomplish these tasks by giving instructions to objects that make them carry out their methods.

ighted material

Page 8: Getting to Know Arc Objects

The syntax of these instructions varies somewhat from language to language. but the bnsic form is "O bject.Method." (The period is pronounced "dot.") First comes the name of the object, then comes the behavior that ~'ou want from it. Fo r example. to add a reco rd to a table object, you would write something like:

Table. AddRecord

To make a tree object d rop its leaves, )'ou would wri te something like:

Tree . OropLeaves

Some methods take along extra in(onnation. called parameters or arguments. For example, in an instruction like:

Tree.Grow(lOJ

the argument tells the tree how much to grow- ten units of some kind or o ther.

What makes object-oriented programming interesting and rich is that objects have relationsh ips to one another and effects on one another. In the real world, a tree has branches and branches have apples on them. These relationsh ips arc mirrored by computer objects. For example, you migh t be able to wri te an instruct ion to create a ut.'C object (Tree.C rente) but not to create a branch object. Branch.C reate doesn 't work because branches don't exist independently of trecs----and this is defined by the propert ies and methods of your objects. Instead, to make a branch. you fi rst create a tree and then run its O rowBranch method .

Tr ee.Crea t e Tr ee.GrowBranch

If you want to make an apple, it might be Trt'(' .Create, fo llowed by Tree.GrawBranch, fo llowed by Br.mch.G rowApple.

Suppose you want to be elaborate and make a boy objec t eat an apple object. You would fi rst write a series of instructions, like those above, to make an apple, and then another series to make a boy. Having produced these two objects, you would wri te an instruction like:

BOy . Eat{ AnApp l e )

When the boy eats the apple, consequences ensue. For example, the apple will no longer exist and the bo)" s IsHungry property migh t change from Yes to No.

You can sec that in o bjec t-orien ted programming. it 's important to learn the relationships among the objects you work with: which ones you can make. whic h ones make others. which ones have ..... h ich properties and methods, and which ones arc affected by the propert ies and methods of others. The need to understand these relationships-..... h ich can be vcry complicated- has led to th .... cr .... ar ion of a special system (or diagramming them. You will stan seeing these d iab>rams in the sc<:ond part of the book. They look like this:

C IV,PTI!R I PROGRAMMING WITII OI:lJECTS

Page 9: Getting to Know Arc Objects

'.m • ,-• .... 8,....:11 • • - U'

Once you know what all the arrows, boxes, diamonds, lines, and smrs mean . you'll be able lO [ell (rom a diagram that a branch object can make an apple object; that apple and leaf objects can exist independently of tree and bl'3.llch objects; and that if you want a tree to do something, you first have to specify which orchard thc tree is in and which fann the orchard is on. In other words. diagrams give you the rules you need to follow when you write code.

When you get to the second parr of this book, it will be helpful [0 have printed copies of some of these d iagrams, including the ones called ArcMap, Gcodatabasc, Display, Geometry, and Styles. All the ArcOhjects diagrams arC included as PDF fil es on thc CD that comes with this book. Some of the diagrams are poster-sized. If your printer canno t accommodate them, you can purchase a bundle of printed copies at www.esri.com/Explo ringArcObjects.

Visual Basic for Applications (VBA) Visual B'lsic for Applications, a Simplified version of Visual Basic. is one of many object-oriented programming languages. You can use Other languages to program A rcObjects (like C++ or Visual Basic), but VBA comes included with AreG IS Desktop. If ArcMap and ArcOualog are lo.1ded on your computer, so is VBA.

The main difference between VBA and other object-oriented programming hmguages is that VBA was designed to be embedded within applications. Program­mers working in languages like C++ typically build software applications from scr:ltch with a set of objects, while VBA programmers customize applications, like ArcMap, that come with VBA inside them. YBA programmers can use as much of the application's built-in functionality as the~' want.

VBA has its own set of development tools. many of which you will use in this book. For example . it has windows for o rganizing and sroring the code you write; tools for creating dialog boxes and their components (buttons, d rop-down lists. scrolling boxes, and so on); and tools for debugging code.

Code is o rganized in procedures. A procedure includes all the instmct ions needed to accomplish some clearly defined task, like printing a map or making a boy eat an apple. Procedures can be linked to each other so thar when one fin ishes it tells

ight I,

Page 10: Getting to Know Arc Objects

another to begin. For example, when a procedure that spell checks a document is finished , it might "call" another procedure that prints the document.

You may sometimes have a chain of procedures calling one another, but the first link in the chain requires a human touch . Actions like opening an application, clicking a button, o r moving the mouse pointer arc called "events" and events are what make procedures run. The example below shows the procedure that runs when a person clicks the Full Extent bunon in Art Map.

Use. ,Ji(iu button

• •• "" • A .,

Arc:Objecb

Code n.ms

•• ... ....... ,= .< ... ... ... "...., ... .. "'" ..... v •••

.. . .... __ ... n •• _ _ ••

... . .. "....v .... . ... _ _ ••. , ....... .

• .... ...., •• • . l ..... . ....... n •• . h u .. '"" ..... ...., .......... -... ....

ArcO bjeclS are a set of computer objects specifically dcsign(..-d for progrnmming with ArcG IS Desktop applications. ArcObjects include things like darn frdmes, layers, features. tables, cartographic symbols. and the pieces th<lt m<lke up these things: poi nts. lines. polygons, records, fields, colors, and so on.

As <I n ArcG IS user, you have been using ArcObjects all along. C lick the Save bunon in A rcMap and a procedure runs to S<1ve your map document. Click the Draw Po int tool on a map and a procedure runs to draw a point graphic where you clicked. The map document, the Save bunon, the Draw Point tool, a nd the point graphic are all ArcObjects. In fact, ArcMap and ArcCatalog arc both built from ArcObject:5.

In rhis book, ~'ou will use ArcObjects to cuslomize and enhance ArcMap (and also jusl 10 b'Ct undemeath the hood and see how ArcMap works) . ArcObjcct's mn be used to progmm other applications as well. Thanks to a design standard ca lled COM, which provides guidelines to the programmers who develop objects, you can use ArcObjecrs to put map functionality in applications like Microsoft Word o r Microsoft Excel (and you can also PUI word-processing or spreadsheet funcriQnality in A rcMap).

On(' thing you won 't do in this book is masler [he universe of ArcObject.s-there are far too many of them. You will get to know a. lo t o f the common ones, however. More impormntly, you' ll get 10 know the princ iples of working with [hem and you'll learn how to read object model diagrnms. so that when you're done with the book, )'ou'll be ready to explore ArcO bjects on your own.

Ctl AI'TER I PROCkAMMIN~ wtTIi OllJECTS

Page 11: Getting to Know Arc Objects

Building a custom application Orgallitillg CUIIUrn.lnJ$ OI l U roollx,r Makillg ),Ollr Qtl'l l communds

Sfllting 1'llllI ts with I'uriublt'.~

ArcMap and ArcCaralog have plenty of toolb.'u s, menus, and commands (buttons and tools), enough and more for most users' needs. However, they will never have everything that everyone needs, and will always have something that some people simply do not. Fortunately, with a li ttle train ing you will be able to change things around. move toolbars, menus, and commands, delete ones you don't use, lind c rclIte the ones that n O one could ever have predicted you'd need .

Ml ln I~b.,

• • • -

ight

Page 12: Getting to Know Arc Objects

I

,

I ,

• • •

I •

• • ,

I

• , , • ,

• · ,

I I

L

Some of your ArcObjecrs wo rk isn 't programming at ;'111 , but customizing the user interface. Objects, like toolbars. buttons, and tools, can be crcatt .. d and rC3mngcd without any programming. Of course. if you create a IlCW bunon and want it 10 do something, then you have to write the code that runs when the user clicks it.

If you've used any software package lo ng enough, there arc prob.1bly some repet itive actions you do on a daily or weekly basis. Maybe you make a lot of fcature selec­tio ns in Arc Map and you'd like to be able to do that by clicking buuons ins tead of choosing items (rom the Selection menu. So you make a tool ba r and put all the selcction choices on it. You don't do any programming, bcc.1l1SC the Selection buttons al ready have code.

,1_ i !:II ~ [lit J!ooo ~ ~' I .... !fIC* W'lolc tI*

IQ _~tl/llw.. .. 5<t!Ktion m<!nu I!J _"'11>' 'p ••

'it WId f)' ft..-.cs

~ I-To'· '.'-""

I: 1Ic""<>.

So!l." • It ,,",,*,0..

/(11 __ ' ... .,1IItt!'!ool •

Qpucoo ...

New ~1!'Ction loolba'

When you need a completely new function , you can create ~our own bun ons and lOois and pm thcm on tooibars. And then you gCt to wri te code fo r them.

••

I Yo"" new bunon

CHAf'TER l B U I LDINC A CUilTOM A I'PLICAnON

Page 13: Getting to Know Arc Objects

\ l' l I I

Organizing commands on a toolbar

The graphic user interface (GUI) fo r A rcMap and ArcCaralog is made up of toolbars, menus, and commands. Toolbars conmin commands or menus. Commands come as e ither buttons o r tools. Menus provide pull-down Iisls of commands or of other menus.

AtcMap toollwf . . "" Command - -<'I. Com",,,," ...

' .. ,;' . " .... ~ Aq, , !B It\dof¥ D 5' .. • III ~u. +- Com~"" RIUtt ... n, • !!I II\dgIJ o-n

M .. nu Mtnu

To make changes [ 0 the user interface, you use the C ustomize dialog box, shown below. You use the Toolbars tab [Q create, delete. rename, and reset toolbm"s. and to

rum them on and off. The Commands tab displays commands and menus. which }'OU can drag from the C ustomize dialog box ontO toolbars. The Options tab contains security and other settings.

--

Orgalllz lllg COllll1lmltb Oil lI/oo/lJtlr

I I I I

" l

ght-:d ma 'I

Page 14: Getting to Know Arc Objects

Exen::ise 2a You arc a G IS programme r for the plann ing dcparrmcill o f Man hanan, Kansas. When pt.'Ople come 10 the planning department office for parcel maps, a planning depanmelll staff member uses A rcMap to locate the parcels and print the maps.

To free up staff members' t ime, you have been asked to create a pa rcel viewer application that anyone can usc.

Users of the parcel viewer application will need to find parcels, label them wi th identification numbers and values, zoom in on them, pan to ccnter them, and prim a map. They'll also need to mom back out to sec the entire ci ty. In ArcM"p, you' ll creme a toolbar with commands for only those actions.

D Start ArcMap and open ex02a.mxd in the C:\ ArcObjects\Chapte r02 folder. C:\ArcObjects is the assumed installation folder for this book's exercise and sample data . If you installed your data in a d ifferent folder or drive, go there now, locate the Chapter02 folder, and open the map.

The m<'lp cOnl<'lins I"yers for the cilY boundary, p<'lrcels, and streets.

Q Click the Tools menu and click Customize. Click the Toolba rs tab, unless it's already active.

O n the Toolbars tab, checked tool\).1rs arc visible, unchecked arc no l. Your list of tool bars will vary accord ing [0 which ArcG IS extensions yOu hnve \O<ldcd.

~~.. ..... I!!I

~­-­,-r ....... -­each' ..... O.,.f,_ I_ .... ~ II" :' """"'" ..... -

o Click New. _1- -

t 3

I c-.I I

The New Toolbar dialog bo_ opens.

CIiAPTIlR 1 BUILDINll" CU!ITQM APPLICATION

Page 15: Getting to Know Arc Objects

. '\l ((Itln (llll?

II Replace the toolba r name with Parcel Viewer. Make sure ex02a.mxd is se lected under Sa ... e in.

ji'--

D Click OK.

Parcel Viewer is added to the list of toolbars in the Customize dialog box. The small , empty undockcd toolbar wi ll expand as you add commands to it.

You'll now move the Find command from the Tools wolhar to the Parcel Viewer toolbar. People will use the Find dia log box to locate a parcel b)· typing a parcel 10 number.

D With the Customize dialog box open, drag Find from the Tools tool bar to the Parcel Viewer toolbar. (If your Tools toolbar is not displayed, you can go to the Toolbars tab of the Customize dialog box and check its box.)

0'8ll11fzillg commllllds 0 1/ {/ tooflxlr

,,-.. -ZOo ... ~­":[1." -Ct7~"'"

::;XI_ 'C:.:': _ .... -o..r,_,. ---:tJoIiIo II 7 :''''''''

-~--

• - I I I I

I

I right

Page 16: Getting to Know Arc Objects

Find is no longer on the Tools toolbar. because moving a command from one toolbar to another doesn't make a copy of it. In the fo llowing steps. you wi lileam how to put copies of a command on different toolb.'lrs. That way Find can be on both the Tools toolbar and the Parcel Viewer toolbar.

U In the Customize dialog box, d ick the Commands tab.

The Commands tab displays two lists. Categories and Commands. C ategories organizes commands by their funct ionality. Your list of categories may vary accord­ing to wh ich ArcG IS extensions you have Io..'lded.

The Commands list contains commands that you drag OntO [Qolbars. Unlike dragging fm m one toolbar to anothe r, commands remain in the Commands list . So you can drag as many copies to as many toolbars as you need.

In the fo llowing steps. you will drog commands (Q the Parcel Viewer tool bar to zoom in on the map, pan around it, print it, and zoom out to the full extent of the city.

CU"f'll!R 1 B UIWINO " CU5TO~1 "PPLlC"TION

Page 17: Getting to Know Arc Objects

II In the Categories list, scrol l down and click PanlZoom.

' .... -"

I

D From the Commands list, d rag Full Extent to the Parcel Viewer tool bar.

, I ~

I

-" I

IIJ Add the Zoom In and Pan commands to match the graphic below.

Next, you will add the Dara View and Layout View commands to the Parcel Viewer lOolbar. This way lIsers can go back and forth between looking at the dara and see ing how the map will look on paper with all its cartogrnphic components like north arrow, scale. and title.

O'R(lIIizillg colIIl//{//lils 011" too/bar

• •

( yrl hl~m n

Page 18: Getting to Know Arc Objects

,\ , m In the Categories list. click View. Drag the Data View command from the

Commands list onto the Parcel Viewer toolbar. Do the same for the Layout View command. Your toolbar should look like the one shown below.

Since some people may not be fam iliar with the A rcMap iCOns. you will use text instead of icons for the Data and L;lyour Vicw commands.

m On the Parcel Viewer toolbar. right-click Data View and click Text Only .

........ -

The icon is gone and only text d isplays. To keep all the commands on the 5."lmc line. you ma\' have to widen the toolbar.

m Right-cliCk layout View and click Text Only.

The tWO commands ;lrc now displaYI..-rl on the [oolbar with [heir names. To make them look more like bun oos, you will add sepamtor 1101.'"5.

m On the Parcel Viewer tool bar, right-click. Data View and click Begin a Group. Do the same for layout View.

Your toolbar should now look like this:

m In the Categories list, click File. From the Commands list, drag Print to the Parcel Viewer toolbar.

CHAPTER ~ BUIUllNG A CUSTOM .... :I"LlGAnON

Page 19: Getting to Know Arc Objects

.\ l' t' l I I 11 I II l

m Right-dick Print and d ick Begin a Group.

The Parcel Viewer toolbar now contains the commands you need to find a parcel and print a map. All other toolbars can be turned off.

m In the Customize dialog box, click the Toolbars tab. Uncheck all tool bars except Main Menu and Parcel Viewer.

Although you don't need it, ArcMap requires the Main Menu toolbar to be turned on.

m In the Customize dialog box, click Close.

m Dock the Parcel Viewer toolbar below the Main Menu .

Your ArcMap application should look like the graphic below .

.... _10

m Test the Parcel Viewer toolbar by following the instructions below.

- On the Parcel Viewer toolbar, dick Find .

- If needed, dick the Features tab.

- In the Find drop-down area, type the parcel 10, 71400.

- Click the Find button. The parcel record appears in the object found list.

r_I_'''' .1'" I r... 11ItI;II;I

...... ~ t.~

P r ... _____ .... _h __

~r. .. _

r... I 3 1

c ... rl ::~----------~3 ('[-...... _ ..... -

Organizillg commwu(s 0 11 a m()I/xlr yrl hl~ m '1.

Page 20: Getting to Know Arc Objects

- In the object found list, right-dick the parcel and click Flash feature .

.... '_II""~""~'~':'~I~':IJ:':_~I _____ ~ rH I - 1'- 3 I ........ I ~....... ::J -'-1 I" fftl_ .... __ ........... __

,- r: AI'" r--------" r-Io_ I ::::I (" [od! .... _-. ....

-I .\.,' .... ! t tI,looo.n(oj

"":' ''\

- If needed, move the Find window so you see the parcel flash in the display area.

" ,', '-rC ~'Q -~ ~)

, • ,. iN r ~ lY

,

,/> ~

I f ~ - In the dialog, right-dick the parcel row again and click Zoom to feature(s).

- Right-dick the parcel again and dick Select feature(s) .

- Close the Find window.

- On the Parcel Viewer tool bar, dick Layout View to see what the map looks like.

CUA"TER 2 BUJI,I>INOA CUSTOM J\I' I'LICAT10N

Page 21: Getting to Know Arc Objects

. "il'er/rln (Int.'

The parcel map displays, ready to print.

I

During the exercise, you turned off all toolbars except Main Menu and Parcel Viewer. You can tum them back on at any time, but you won't need them in rh(' following exercises.

You can use a shortcut to open the C ustomize d ialog box. Double-click on a blank area in the toolbar area.

'----_ ........

_. , . , ,

Ooubl~11d: here to oprn me Customize dialog 00.

m If you want to save you r work. dick the File menu in ArcMap and dick Save As. Navigate to C:\ArcObjects\Chapter02. Rename the file my_ek02a.mkd and dick Save. If you are continuing with the next exercise, leave ArcMap open. Otherwise dose it.

0'8(lII i:.:"1II8 com"'lII1ds 0 11 II foo/lxlr

yrl hl~m n

Page 22: Getting to Know Arc Objects

Making your own commands

In the pre" ious exercise, you made a toolbar and added some prcprogmmmcd ArcMap commands to it. When your npplicarion has to perform rasks that aren't already part of ArcMap, yOu make your own commands and write code to make them work.

You usc the C ustomize dialog box to c reate commands called user inte rface controls, or UIControis for short. UIBunon, UITool, UIComboBox, and UIEditBox arc the four types of UIControl you can make.

EKClm Ie Toolbar of UIControls

w )iii I :.::I I

UIBl.lt ton UrTooI UIEdi t80.

As with any bunan . clicking a U iBunon makes something happen. For example. when YOli dick the Save bUHon, the map is saved. UITools work by clicking them and then clicking in. the map display arca. Onl~' one can be active at a time. After you've clicked on a tool. irs cursor symbol appears when you move into the map dis­play area. For example. when } 'OU dick the Pan tool. the cursor you move over the map looks like a hand. You d ick and drag on the map to pan to different locations.

' ....... -- .......

+ - Map d' lplay Olrn

" • •

I~&~. .' .

n--- Tool', <u._ ,ymbol

, , • .,

• •

3 1" 3 • , a ~. ~ . ~ • ..:. ' . .. ="'., '"

To get a U IControi to do something. you write code with Visual Basic Editor. There. YBA organizes your code into projects, code modu les, and procedures.

C IIAM'ER 1 B U ILDI NG A CUSTOM AI'I' LICATIO N

Page 23: Getting to Know Arc Objects

\ll(//)ll (1IlL'

EdilOl'

"

Projects are files where your UIControls and VBA code are sto red. There are three rypes of projects: map documents (. mxd files), base templates (.mxt fi les), and the normal template (the Normal.mxt file stored in your personal pro fi les fo lder) .

Say you have a map document called rivers. mxd and it contains rivers and mhcr water-related layers. And you need to make a U I Button to calculate water fl ow rates. You would put the Flow Rate button and in code in the rivcrs. mxd project . It wouldn't make sense to put the button into mher map documents, since its code will be specific to calculate fl ow on rivers.

Say you need to make a U ITool that reports any polygon's arca in squarc fect, acres, and hectares. TIlis tool is not specific to any project. In fa ct you want it available whenever you have polygon layers d isplayed in an~' map document. You would put this Area Reporter tool and its code in thc Normal.mxt project. Every t ime ArcMap starts up, it reads the nom13l te mplate to see if it contains any UIControis and code {helt nceds to be available at all times. If your o f&'<lnimr ion uses base [cmpi:ucs, you can also store UIControis and code in them.

Projects organize code with code modules, windows that ~'ou type into. You make as many code modules as you wanl o r need. However, every projec t has a code modu le called ThisDocument . The ThisDocumcnt code module is the place for you to write code for any U IControis that you make in a parricular project .

.\laking yOllr Ofl'lI COII/mtll/tis :!d ma I.

Page 24: Getting to Know Arc Objects

, • • •

• •

I • I

I I •

, • , !

• j • • · , • •

I • • • , i • • • •

l

Within each code module, your YBA code is organized into procedures, listso(VBA instructions that perfonn a task. A procedure to cut the lawn might look like th is:

Sta r t CutTheLawn Get lawn mower f r om gar age, fil l with fuel if needed Remove sticks a n d other debris from lawn Scart lawn mower and cut grass TUrn mower off, clean, and return it to garage Dr ink cool beverage

End CucTh eLawn

VBA has four types of procedures: evem, subroutine, fu nct ion, and property. Event procedures correspond to user actions. For example, a UlButton has an event pro­cedure called C lick. You cooe the click event procedure so it will fun when the user clicks the bunon . The other three procl.-<!urcs arc all ca lled into action by event pro­cedures. So no code runs unless the user does something (causes an CVCnI).

All procedures havc a fi rs t and last linc, wh ich arc ca llcd wrappcr lincs. Your codc goes between thcm. The fi rs t line contains either the Public o r Private keyword. Privatc procedures can only be callcd on by procedures in the same code module . Public procedures can be called on by procedures in othe r code modules. The fi rst line also conta ins a keyword identifying the type of procedure (Sub, Function, Property), the name of the procedure (for instance, cmdQuit_Click) , and parentheses. (VBA identifies both subrout ine and eve nt procedures with the S ub keyword.) The parentheses are required. Here they're empty, but in later exerc ises, you'll ieam what can go into them .

Public Sub cmdQuit_Click () MsgBox "ArcMap is about to close"

End Sub

The last line in a procedure contains the End keyword and the keyword identifying the type of procedure. The click event procedure above has one indented line of code. Indenting makes your code easier [0 read without slowing it down.

MsgBox is a Visual Basic function that d isplays the quoted [ext mess.'lgt' in a d ialog box. When someone clicks the Quit bun on, the MsgBox line of cooe is executed, and the dialog box below appears. Visual Basic comes with many prewritten functions like MsgBox. You'lIleam how [0 usc it and other functions, and how [0 write your own, too.

• -~- .. -

(II: I

Clt"''TER <1 B U ILIJING A CUSTOM APPLICATION

Page 25: Getting to Know Arc Objects

, { ,

Exercise 2b People are now using the Parcel Viewer application to print their parcclm[lps. Occasionally. some people need help finding their parcel and making a map. You will create a button to tell people who 10 contact if they need help.

In thiS exercise. you wi ll make a bunoo . You will write codc in the button 's d ick evem, SO someone can click it to gel assistance with their map.

II Start ArcMap and open ex02b.mxd in the C:\ArcObjects\Chapter02 folder.

When the map opens, you Sl'C the parcels of Manhattan and the Parcel Viewer lOolbar.

D In ArcMap. click the Tools menu and click Customize. Click the Commands tab.

U In the Categories list, 5(roll down and dick UIControls. Make sure ex02b.mxd is selected under Save in.

The Commands list is empry. As you make UlCom roLs. they will be listed there.

, .... --. -

{

-I

s.-.e In: eJdl2b.nud

II Click the New UlControl button,

• 'II( ... 1 ....

Co'-....,. r .. ,. c .. ,. 11"< , :' r ,W" ,'·401

o With the radio button next to UIButtonControl selected, dick Create.

YOll sec the new button, Projcct.UIButtonControl t , in the Commands list. Its name has the "Project" prefix, be<:ause you selected ex02b.mxd in the Save in combo box.

,\ laldllM .1'0/1 r 0 (1'11 r;;olllll/(lluls

'1

I •

r Yfl(hl~m n

Page 26: Getting to Know Arc Objects

'XC 'el ~l 2

Had ~'ou selected Nonnai.mxt for Save in, the bunon's name would have "Normal" as a prefix. U IConrrois saved in a base t.emplate have a "Templat eProject" prefix. Since you saved the bun on in the ex02b.mxd fi le, you and your users must open cx02b.mxd to see and usc this new bunon. The Normal.mx! file is a file that A rcMap reads every t ime it starts up. Any U IConrro ls )'ou save in Nonnal.mxt

I always appear, regardless of the .mxd file you open. , • , I

, • I ,

I , •

I I I , I

IJ In the Commands list. click Project.UIButtonControl1 and change the name to Project.Help.

o Drag Project. Help to the Parcel Viewer toolbar.

iJ . 1.1\ , ,

(10<0_ ........ _ Q ~!- AddlhebutIOllhe.e

You will change the bunon's icon to display text only.

o RighHlick the new Help button and click Text Only.

D RighHlick the Help button and cl ick Begin a Group to add a separator line.

Now you will write some VBA cooc to makc thc new Help button work .

m RighHlick the Help button and click View Source.

The Visual Basic Editor window opens. It contains other windows, likc Project, Propert ies, and a code window ca lled ThisDocument. Depe[lding on your VBA set ­t ings, these windows may be diffe rent sizes o r in d ifferent positions compared to the OnCS in the fo llowing graphic.

CIIi\PTl!R 1 BUILDINC ... CUln'OM M'I'LlC",TtON

Page 27: Getting to Know Arc Objects

.'i~C[I(}n one

The Project window below, sometimes called the Project Explorer, shows two projects: Nonnal (NomlaJ.mxl) and Project (ex02b.mxd). Ahhough the Nonnal project is always prescnt, you will add U IConrrols and write code in the current project that corresponds [ 0 the currently opened map document. ex02b.mxd.

Event procedures for the projcCl's U IControis arc s[Ored in a code window called ThisDocument. That's why when you right-click on a U IControl and click View Source. the ThisDocumcnt code module opens. If it is a new UIButton, wrapper lines (or the butto n's click event procedure arc ;1mo matically added.

~1111_~'-~ .... r-~N.' • .J' 1i1 po ,. ... -' _. .

111(1 ....

m Between the wrapper lines, indent for a new line of code. Type msgbox, press the space bar, and stop typing for a moment.

msgbox

A yellow help tip pops up to display help for using the MsgBox. The words and phrases separated by commas are called arguments. To make unique-looking message boxes, you fill in different information for each uq,rument.

MlIkl"J.! .1 '{)II r oll''' COlI/ lIUlI/tiS j: right 0:0' "

Page 28: Getting to Know Arc Objects

The word "Prompr" is bold because it is the first argu ment you shou ld type. For Prompt, you ( ~'pe a text suing ( 0 be displayed in the meS&'lge box's dialog box. Argu­ments in square brackets arc optional. For a descript ion of each argumem . look up MsgBox in the online help.

<:<.do ....... 1" __ 0.0.

r_ •• _~_ 17 _ .. ,. , , p -q,n ... 17_Doto""

.'" (, -. I" 1100 •• OIl Do,",T"'-",

P DooI .... IO .... -.. _ 1" ., , .. _ _

---, __ 1"'--

m f inish typing the MsgBox line of code by add ing the fol lowing text string, quotes and all .

msgbox "For help di a l extension 25"

The click event procL-dure is now re:ldy to rcst.

m Highl ight the procedure as shown below.

VBA checks your syntax and, whcn it's okay, converts it to uppercase fo r you as needed. You typed msgbox and VBA changed it to MsgBox. lt 's a good idea to do your ryping in Im .. ·crcasc and let VBA check your syntax and handle capitalization.

_ •• ".~." ... , " ......... _ . «" .. ,

CH APTER 1 BUII.DI:<;(l A$\{.fH jlM ~f'f'PqATIO~

Page 29: Getting to Know Arc Objects

· .'i!.?ctlon (Inc

m On the Standard tool bar, click t he Run button (or press FS).

The Visual Basic Editor S tandard toolbar has a button that looks like a VCR's Run bunon. Clicking (hat button tells YBA to Stan executing the lines of code in the selected procedure.

The line of code runs, ArcMap comes to the foreground, and the help tnCM.'lge apj:Cars.

- ",

I '* I

Highlighting a procedure and clicking the Run but ton is o ne way [Q rest a procedure without leaving Visual Bask Editor. Parcel Viewer users, however. will not use the Run button [ 0 run this procedure. So next you'll use the Help button just like a user would .

m Click OK on the message box,

m Close Visual Basic Ed itor.

III On the Parcel Viewer tool bar. click Help .

... ®

The message d isplays .

.......... , .zs

0< I

ill Click OK.

In this exercise you made n UlBunon, put it on a toolbar, and wrote VBA code in its click event procedure.

m If you want to save your work, click the File menu in ArcMap and click. Save As. Navigate to C:\ArcObjects\Chapter02 . Rename the file my_ex02b.mxd and click. Save. If you are cont inuing with the next exercise, leave ArcMap open. Otherwise close it.

,\laM; 118 .1'0 11 r 0 1/'1/ CO"""f"l(ls ~ right

Page 30: Getting to Know Arc Objects

Storing values with variables ---

In the prev ious exercise you made a bunon and named it Project. Help. The hutton's mille is a value that gets stored in and s.wed with the map document. Values like a bunon's will probably never change. Some values. however, do change. Say you want [0 keep [rack of rhe temperature Qurside your home. As it gets warmer or colder oU[sidc. the temperature value changes. You usc variables to store values that might change over time.

To make a variable you write a linc of code. In the line, you make up a variable name and usc the equals sign to assign it a value. The line below makes a variable named Tcmper.nurc and sets it equal [032.

Temperature : 32

This line of code is called rm assignment statement because you assigned n number to the variable using 3 1\ equals sign. After the code runs, Temperature conrains or represents the number J2. In any subsequent lines of code. if you need the tempera­ture value. you use the Tempemture variable. For example. you could displa~' the va lue in a message box with the fo llowing line of code:

MsgBox Temperature

1M ~alue Inude the Temperiture variable displays here

01' I

As the da}' goes on, the number stored fo r Temperature will \'ary depending on the wcather. Bcc.'luse the value will vary, Temperature is called a variable.

The Tempemture vari:.blc currentl y contains 32. A variablc's contents can change by the mere writing of another assignment state ment. As it g N S warmer outside, a new number is assigned. When the line of code below runs, the o ld number is cleared out and the new number is assigned.

Temperature ; 50

The Temperature variable now contains 50.

A variable can be assigned a value that is the rcsuh of a math equation. Equations arc arranged to the right of the equals sign using operalOrs like +. -, ., and I. The equation belo\\' subtracts 5 from [he currcnt temperature. The rcsuhing value of 45 is assigned [Q the variable.

Temperature : 50 - 5

The temperature dropped five degrees, the new value is assigned, and Temperature now contains 45.

(.'HA I'TER 1 BUlll.>lNC A CUSTOM APPLICATION

Page 31: Getting to Know Arc Objects

·~i.!ctlon

Variables can be substituted for numbers. For example. you could have subtracted 5 from m e current temperature with the fo llowing line of code. The math equation. Temperature - 5, is solved before the variable's value is assignt.od.

Temperature : Temperature - 5

All math is perfonned from left to right. except fo r operations in parentheses, which are evaluated fi rst. In complex equations you usc parentheses to control the order of evaluation.

In places where it gets really cold (below 50 degrees Fahrenheit) and windy (wind speeds above 5 miles per hour), temperature gets measured in wind chill factor. a measure of how fast your body loses heat. With a temperature of 35 0 F and a wind speed of20 mph. the temperamre feels like 240 F to your body, but water will nOt freeze.

The equation below computes the wind chill factor given temperature (T ) and wind velocity (V); the resul t is assigned to the C hill variable. The operations inside the three sets of parentheses below are evalulued fi rst, and the results are added to 35.74.

Chill = 35.74 + (0.621 • TI + (35. 75 ~ VI + (0 .4275 • T • V)

Besides numbers, variables can contain other values. like character strings (text ). In an assignment statement to create a string variable, the characters must be quo ted. The colon and space after is have been added so that a number can go there.

Message = ' The cur rent t emperature is: •

To add the temperature next to the message, you use the ampers.:"lnd charact.er (&). which concatenates the two values.

MsgBox Message & Temperature

When this line of code runs, the message and temperature display as one value .

~ 1

To keep the temperature updated. someone must cntcr new numbers. A dialog box, called InpurBox, has an area [.0 type in values .

---

SJOrillB mllll.'S witb IVlriables

... I Ol I

0-01

Qhl

on!!

Page 32: Getting to Know Arc Objects

An InpurBox can be used in an assignment statement. The value typed in the input area is assigned to the variable. When you set variable values with an Input Box, its arguments, like the text mess.1ge below, go in parentheses.

Temperature : InputBo x ( "Enter temperature ")

-_ ..... .!l

I !lit I ~I

When the user types 85 and clicks OK, the Temperamre variable contains 85.

U nless othenvise instructed, VBA sets aside 16 b,·t't!s of space to store a variable's value. With that much space, you can store the number 1.797693 134862315 E308. EJ08 means that the decimal place in 1.79769) 1348623 15 can be moved 308 places to the right. That's like taking away the decimal place and adding 293 zeros ( 0 the cnd of that number. If the variable only needs to store a temperature, that 's a lot of wasted space.

You cut down a variable's storage space to size by telling VBA what values the variable should accommodate. This is called declaring or dimensioning a variable. You tell VBA the variable name and its data type, which could be number, string, date, or an)' of several mhcr data types.

Declaring a variable takes one line of code: he re it's the Dim keyword (for dimension), Temperature (the variable name) , As (a keyword), and Integer (the data type).

Dim Temperature As Int eger

Dim is only one of several keywords uSt.-d to declare variables. You'Uleam about others-public, private, and static- in later chapten.

Now that Temperature is declared as an Integer data type, it will only require 2 bytes of storage space, a savings of 14 bytes. You can learn more about VBA's data types and their storage requirements in the online help. For a list of sizes and , 'aloe ranges, search for Data Type Summary, as shown in the fo llowing graph ic.

CIIAPTER l BUILD ING A CUSTOM APPLICATION

Page 33: Getting to Know Arc Objects

• scellon nne

Il ...... , I •• l .....

'", • b, .. 0,," "' ........ 1 b,lO' T .... ., r., •• I~t.~ •• 2 b, ... "1.'" 10 'l.lU ,- • b, ... ·t.,., ......... to 2." ',0""" , ... -~,

, ... 1. • b"tI ·,ADI1UrM 10 ·IAOIltef.·., lot

( ....... ...,.., ••• _.: ,.001..-.... 10 ... " ..... UDnUf)l '" _ •• _ • . -. ....., o.w .... 1 hI" . \ ",.,U, .. ,UIU" 10 ( .... tI,. ....""06"" ... '2<1>1 ,.2<1 for ... _. - '_', .... 06"" ... U.>I·ll< "" .-. 1 ',,,,",,,,,um*tw _ •• ....., ._, h .... _~

I ."., ·tll."' .2IU'-"1I,~ "" ,- 9>l,I,',1O',mAlI.$801 ••••• : l

0 ....... 1 , ......

D.,. ...... , ........ 1.100 .. 00 .. _ ".-

O~ .. 't • ~,IO' ....., Ob!." , __ ....... '0 ..... . 0 ............... ,,1_ { .. ..-. ---, !i .......

_. Ito ............. ,,6~_ (~ •• O· ,--,

~" ,- i6 b ... , On, .................... "'"._ ... ----~ .. Oou.'.

Exercise 2c Pt.'Ople are using the Parcel Viewer application to locate parcels and print thei r maps but using pocket calculators to compute the tax for a parcel. They'd like me applica­tion to compute the taxes for them, In this exercise, you'll create a U IButton that calculates a parcel's tax. You'll make an input OOX that asks the user for the p.1rcel's value and then displays a message box with the tax.

U Start ArcMap and open ex02c.mxd in the C:\ArcObjects\Chapter02 folder.

When the map opens, you sec the parcels of Manhattan and the Parcel Viewer toolOOr.

o In ArcMap. click the Tools menu and click Customize. Click the Commands t ab,

U In the Categories list. scroll down and click UlControls. Make sure ex02c,mxd is selected under Save in,

srori"8 I t(I/II(.'S with /1flri(fbll!S

H.'" ,

ryrl(hl~m n.

Page 34: Getting to Know Arc Objects

... ' 1 l

In the Commands list, you see the Help burton you crc,ncd in the prcvious excrcise.

,_ eo_

C !J '"

I I

II Click the New UlControl bunon .

• , .. odl"",

,., IA· 'J t : ... (" ~.re =.,.

o With the rad io button ne)(t to UIButtonControl se lected. cl ick Create.

In the Commands list, you see a new bunon named Project.UIBunonComroll .

.Il

o In the Commands list. click Project.UlBunonControll and change t he name to Projed.Ca kulate Tax .

Page 35: Getting to Know Arc Objects

. S~ClI()n one

D Drag Project.CalculateTax to the Parcel Viewer tool bar and drop it to the right of the Pan tool.

You will change the button's icon.

o Right·click the new button, point to Change Button Image, and click Browse.

D In the Open file browser, navigate to C:\ArcObjects\Oata and dick Dollar.bmp. Click Open.

The dollar sign appears.

• .. Now you will write code to make the C,lculate Tax button work.

m RighHlick the Calculate Tax button and click View Source.

The Visual Basic Edi[Qr window opens. You see the empty wrapper lines for the Calculate Tax click evenr procedure in the ThisDocumcnt code window. You also see the Help dick event procedure you coded in the previous exercise.

Pun._ ' '''' ... ,,_cnu u bg"'. " ' 0 . "'" <11 . 1 ....... . 0. U · U d , ....

- c:'",!'''' T.,. did< _nt procedure

Help dick ewnt procedure

m Between the wrapper lines, indent and declare t he following variables.

Dim curPar ce l Value As Currency Dim curTaxValue As Cur r ency Dim datToday As Date

The Currency data type has tWO zeros to the right of a decimal to store dollars-and· cents values. The Date data type is capable of storing the current time, day, date, month . and year.

Slori"8 ,,,lilies II,Hlb tVlriablc:s ooyright 0:0' "

Page 36: Getting to Know Arc Objects

\ ,

Variable names must begin with a char..lCtcr and not exceed 255 characters. They cannOt contain spaces, periods, o r sJX"Cial characters (%, •• &), or be the s.1mc as a VBA keyword like 1(, Then, Suh. And, Or.

Within the rules. you can name \'ariablcs as you like. Some programmers add a prefix (Q variable names to indicarc rhe variable's data tYpe. For example, all srring variables might be named with the prefix "srr": slrName, strAddrcss. srrPhoncNu mbcr. In the code above, CUT is a prefix for C urrency vari:lblcs and dar for Date variables.

Next you ..... illuse an Input Box to SCI the parcel value variable. S ince Input Box has three argumen[:~-lIser message, window title, and defau lt value-the linc of code thar creates it will be rather lo ng. To make it easier (Q read, you'll lise the linc con­tinuation character (an underscore) to put each <lrgument on ils o wn line.

m Enter the following line of code, putting a space before each underscore.

cur Parcel Value = InputBox ( -Enter a parcel va lue", -Parcel Viewer", _ 100000)

Even Ihough you see four lines, VBA recogn i1:cs Ihem as o ne line o f code and executes it as such. Yo u can only use th(' !inc continuation ch:lraner between argu ­ments. You will get an error if you try 10 bre<lk a text string as shown below .

• Parcel _ Viewer' .

m Enter the following code to compute the tax value.

cu.rTaxValue = IcurParc elValue • 0 . 02) + 8.55 + 11

Resid('nlial parc('ls are taxed at 2 percent of ,heir value, plus an $8.55 convention ccntl!T fcc, and $ 11.00 for the city's new nrc tnlck.

TIle numlx-r in the input box is multiplied by 0.02 , then 855 and 11 ,Ire add<.'tI . The resul t of the calculation is assigned 10 cu rTaxV<llue.

DJ Enter the following code to set the date variable.

datToday = Now

"Now" is a Visual Basic functio n. Yo u'll learn how funct ions work in a few chapters. Fo r the time being, you can think of "Now" as a pfl!dcnned variable thm contains the current date and time.

All the necess:lry information has been gathered and evaiu:n<.-d. Whm rema ins is to

give the information to the user in a meSs.:lge box.

C IIAPTER l BUIU) ING A CUSTOM APPI.1CAT10N

Page 37: Getting to Know Arc Objects

.'iCClIOn ()Jlt!

m Enter the following code to display a message with the parcel 's tax amount and today's date . Use the vblnformation constant for the type of message box .

MsgBox "The tax value is: S" & cur TaxValue, _ vblnformation , _ datToday

Normally, after you type the first argument and a comma , you see a list of message box types to be used for the second aq,'Ument, as shown below. You didn't see the lisl because you used line continuation.

MsgBox "The tax va lue is: S" & curTaxValue.

TIle choices in the list arc called constants. Each has a vb prefix and produces a different dialog box. Examples of vbCritical, vbQuestion, and vbExciam:ltion arc shown below.

' ,J "lOOll 10 ........... .'''' :mIIlII ...... '·. - ",

o ....... ·"" .o Pt,.

I I (J( I c. I

vbCritlul vbQuHtlon

Thc third argumcnt, datToday. is the message box's ritle. The darToday variable. created in the previous step. contains coday's date. Without the third argument, the message box title will read eithe r "ArcMap" o r "ArcCaralog," depending on which application you wro te the procedure in. Your code should match that shown below.

D •• """Y.,.V. h •• u D ... <k<1'o<Ioo, u ~<.

c,...&rc.IV . .... " Im ... tlo" C "hur ••• , UI ..... I~." , ....... ,", -

c ... T",hl_ " (" .... ..-c.IV . .... . O.OU • '.5' • II IIot1'o<loo, " /lo_ bO .... "lM ... ",01 ... ,. , '" • c .. n""".,,,",

VII l"'On. .. o~, <k<T0400,

5101i"8 /1tlfll£'S lI'ith tmit/bles

I ."

r yrl hl~m rI;

Page 38: Getting to Know Arc Objects

CIS

Befo re testing the code. you will add a line of code [ 0 help identify errors.

m Move to the top of the code module and type the following line so that it is the fi rst line of code. Press Enter to add an empty line between Option Expl icit and the first procedure .

Option Explicit

TIle lOp of the code module is caJ1ed the General Declarations area. In this area you can declare variables and SCI o ptions like 0}lIion Explicit.

,"Va" s .... (.'CV1.'"t ... _cu~"u

D .. """..,".1 .... 1_ '" (lUre"",. Duo " ""T ... V.I_ ... e"" •• "",. Duo ".<T_, ... hte

""," .. : el ... al ... ,.pg' .... 1 _ "hu< .. p ... ".L .... 11 .. •• _ "'HCOII '11"'''-,

With Option Explicit on, your code will nm run if you have any undcclart.-d variables. This is VBA's way of automatically locating spelling mistakes. In the followi ng code. one line declares the variable (Test), onc sets it, and the other uses it.

On the third line, the variable has been intentionally misspelled Fest.

Po. Ten ... s«."" T .... ' • ·n,_ •• _ ..... -~ ... ,.

tN • ..,

Without Option Explicit, the three lines of code above execute without error and resuh in the followi ng empty message box. Fest is recognized as a variable, but because it isn't declared or set it contains no value.

I

CII A1'T'ER 1 BU1U)lNC A CUSTOM APPLICATION

Page 39: Getting to Know Arc Objects

. ~L'Cl,on -'ilL'

With Option Explicit on, when an attempt is made to execute the code, Fest is identified as an undeclared variable, and the following error mess.,gc displays:

~ ---~-

In the code window, VBA highlights the misspelled variable.

» ... To .. .. . «'11\1 T .... ""n •• • • • , . .. . _ .... .

With Option Explicit added lO the code module. the Calculate Tax buna n is ready to (CS t .

m Close Visual Basic Ed itor.

Ell Test the Calculate Tax button by following the instruct ions below.

- On the Parcel Viewer tool bar. click Calcu late Tax (S).

- For the value, replace 100000 with 150000. (If you enter t ext instead of a number, or if you cl ick the Cancel button, an error message will appear. In chapte r 5, you'll learn how to use branching statements to help avoid these errors.)

• - .........

- Click OK.

01' I

- Click OK.

Storing 1X1l1lt's u 'illl l'tlriables ~Yfl hl~ m nOli

Page 40: Getting to Know Arc Objects

You have now created two UIBut(ons and coded (heir cl ick evem procedures. Users click the buttons and your code runs. Next ~'ou arc going IO code 11 second t~'J't' of procedure called ToolTip.

Code in a ToolTip event procedure ru ns when a user moves their mouse over the top of a command. Th ere is no clicking involved. Below. 1I uscr hovers the mouse over the Zoom In command and a yellow tooltip appears with the name of the command.

III Right-click the Calculate Tax button and click View Source.

CalculateTax is selected in the object list , because you right-cl icked it. You see CalculateTax's click event procedure and the code rou al ready added. To add Dl her event procedures for CalculateTax, you select them from the procedure list. You will add the ToolTip e"ent procedure.

' . ,Vat a S ub ta'.~l auTa._" •• "O ~I. ~""'.'~.lVa' ...... t "" .. "", P .... . " •• r .... Vdue ... c .. .,. . ""', P .... ".<1'_, ... I>oote

~~.P •• ~.IV. I .. - l~pvtlO. 1 _ 'Int •• • P •••• , val .. •• "P.'cel Vle-.'-,

£Ill In the procedure list. click the drop-down arrow and click ToolTip.

The wmppcr lim.os for the Tooillp event procedure a rc added.

- ,,<!".,,~, ''-I''~'~.''-)

IOUOW)

~urT • • V. I" • I ~"", • ••• IV.I ... . O.OZ) • e . " • II da,TO"', ..... IUIV ..... n.. tall .... ' ... 10: I' •• urn,Va, ... ,

... Izotc .-, lea, d. Uo<I·V

Page 41: Getting to Know Arc Objects

. ";CctlOll one

m Add the following line of (ode to set the tooltip's help string.

CalculateTax_ToolTip = · Calculate Tax ·

Code in a ToolTip event proCl.-durc will not run if Visual Basic Editor is open.

m Close Visual Basic Ed itor.

m Hover your mouse over the Calculate Tax button to see its tooltip .

.. m If you want to save your work, click the File menu in ArcMap and click Save As.

Navigate to C:\ArcObjects\Chapter02. Rename the file my_ex02c.mxd and click Save. If you are continu ing with the nelrt chapter, leave ArcMap open. Otherwise close it.

')tOri1l8 l 'i'IIl IC'S lI'ith ['(I/tables

. '"

'::tyright

Page 42: Getting to Know Arc Objects

Creating a dialog box Usillg (:(n\ fTO/s 10 build II fonn

In the previous chapte r, )'OU called up mess.'lge boxes and input boxes just by using MsgBox or InputBox in lines of code. You could do that because both of them aTe canned dialog boxcs-precoded, preset, prefab. But bcc..1.USC they're canned, they can only do so much. YOli can't add buttons, slider bars. o r input boxes t.o them. To get a user's name, address. and phone number. you'd have to call three different input boxes.

-----~-

i

Fortunatcl~', there's a better way to do it. You can make ~'our own dialog boxes with as many input boxC5, check boxes. and slider bars as you need .

.. _--... .......... ' ........... -p-- p-1"'-... p __

"'- "_ Per_ C E , •

• _ 1_ . 1 ... 1

IOhl~ m n

Page 43: Getting to Know Arc Objects

U sing controls to build a form

No matter what they look like to a user, aJ1 these dialog boxes are called farols by programmers. The (o rm below has fi ve inpm boxes and three buttons. After filling OUI the form, the user cl icks Add Customer (0 enrer the daw imo OJ customer dmabase.

- 1 - Form

'55,w I 0 , 1

1Iojj 0 7

-- 1 - 1

In Visual Basic Editor, the blank cmnras (or making a user d ialog box is a lso called a foml. The objects on a (onn , like buttons, inpm boxes, and [(~X[ , arc ca lled controls.

- Form

- FOfm window

In the smile war that you dmg commands from rhe C ustomize di alog box onto a toolb..1.T, you drag comrols OntO a form (rom Visual Basic Ed itor's Toolbox.

TooIbo.-

7 7 I ... ..,

D.ag and - .\r) """

Label controls arc used to add descriptive info rmation.

C.b" - I -control A .. -I:' r. ,., 0 .... F I ...!l..:J ; ~" ~

C HAPTER ) C REATING A DIALOG IIOX

Page 44: Getting to Know Arc Objects

· ....... llllll1 lIne

Text boxes provide an area for [he user to type in information .

Combo boxes provide a list of choices (hat users click a drop.down arrow to see.

Combo8ox control ~_...,

- . - I

1 -

While designing the (onn, you don't sec values in the combo box. Values appear when the form is runn ing and the user is setting or entering values as shown below.

- 1-- 1----- 1- ....... - ,

As you add controls to a form, you set their properties in the Visual Basic Ed itor Properties window. Properties delcnnine the appearance of a control, including its height. width, color, and text. Below, the Add button's BackColor propcrry has been set to green and its ForeColor property to wh ite. The word "Add" has been t)'JX.>d in for the Caption property.

BlckColor-

~Plion-

foreColor-

UsillS cOII/l'Ois to build fl jo,.", I(hl~m n

Page 45: Getting to Know Arc Objects

After setting the propenies for a com rol, you then write its VBA code. Controls have procedures that arc coded to run when the contro l is used . For example, when a user clicks the Add button, your coded procedure runs to add a record into a data­base rable.

Since a d ialog box will fi ll a pan icular need for collect ing data o r perfo rming a task, it is helpfu l to begin its design by talking to the people who will use it. For the moment, suppose that these people arc city workers who repair streetlights. They have laptops in thei r [rucks and use A rcMap to locllte light poles. After a replI ir, they write the repair record on a paper foml , which is given [Q someone in the office to enter into a dawbase. Workers could So'we rime if they had an A rc Map form [Q usc in the field.

By examining the existing system of getting repair data into the dambase, you can determine the infonnation that gets collected (repai r date, type of repair, light iden­tihcafion number) and the tasks that arc performed (add a record in to the database for each repair) .

Before making the form with Visual Basic Editor, sketch it out on paper to show to the work crews and daw entry staff to see if it contains all thc controls that they wou ld expect .

C ... _ ••• '" .... \

...... 1 I I w " I ~. f===l I .~ I -C ~· .... · ~ o ' .. !u . ..... .,

o I! ... ~ . I On I

O nce your paper design rece ives everyone's approva l. you can sta n Visual B •• sic Editor, open a blank form, and drag controls OntO it from the Toolbox. Thcn for each control you can set properties to get it to look like the paper design .

CHAPTER] CREAT1NG A I)IA l OO so!>!:

Page 46: Getting to Know Arc Objects

Sl'Cll()n lIne

Exercise ) When Parcel Viewer users click the Calculate Tax bunoo (created in exercise 2e) .. ",. and enter a parcel value, the tax that is calculated and displayed is the residential rnte of 2 percent. However, while most parcels in the city are zoned residential, some 3 f C zoned commercial or industrial and each zone has a different tax ratc. To calcu­late taxes morc accurately, users need to be able to choose their parcel's roning code.

In this exercise, you will create a tax calculator dialog box that looks like the sketch below. It will contain a TextBox to enter a parcel value, a ComboBox with a list of zoning values, and a Label for the calcuhued tax amount. In chapters 4 and 5, you will write the VBA code to make it all work.

,~,.

CommandBunon

D Start ArcMap and open ex03a.mxd in the C:\ArcObjects\chapter03 folder.

Only the Main Menu and Parcel Viewer toolbars need to be turned on fo r this exercise.

D Click the Tools menu, point to Macros, and click Visual Basic Editor (or press Alt+F11).

You are going to create the new form in the projec[ for cxOJa.mxd.

Usillg collfrois /0 blilld (/ fonn OD'" ,hted mat"';a'

Page 47: Getting to Know Arc Objects

I

D In the Project window. right-cl ick Project (ex03a.m)(d). point to Insert. and cl ick UserForm .

A new form called UserForml opens, along with the Toolbox of controls.

too 'I lit AoaI lla Pr.,..O .... ..:.J~:!lGI

• . ... ~ -~.-- , • •

.. -----'~m

- Fotmwilldow

When you create forms and comrols, VBA assigns them a ,'ariable name. For example, if ~'OU were to wfiu' code with the new (orm above, you would refer to it as UserForml. You will wrile thaI kind of code in the next chapter.

Si nce the name UserForm I isn 't vcry meaningful. \'Oll will change it by setting the Name property in the Propcnics window.

D In the Properties window. type frmTax for the Name property. Press Enter.

Next YOli will usc the Properties window to change the fo rm's gray color to white.

CH,\I'TER J CR£ATIN9 ~ DIAIOO ijQl(

Page 48: Getting to Know Arc Objects

• "l,'l [Ion nne

D Click the BackColor property.

The property highlights and a drop-down arrow appears.

--.-•• ~

•• •

o In the BackColor property, click the drop-down arrow and click the Palette tab. Click the white square in the upper left corner of the (olor palette.

You see the form change color (rom gray to white.

O k k wIIlt~ :II •• • ••• • ...... ;. • •• • • " . •••••••• •••••••

II In the Properties window, set the following form properties by clicking on each one and typing the listed value.

- For Caption. type Tax Calculator

- For Height. type 192.75

For Width, type 255.15 and press Enter

The numbers you entered for height and width are in pixels. The size of the foml and its controls arc aU given in pixel uni ts.

Next you will add a city logo [0 the fo rm and SC t its properties.

D Click the form window to make it active.

o If the Toolbox has dosed. reopen it.

Sometimes, all you need to do to reopen the Toolbox is make the form window active. If the form window is active and the Toolbox is still nOi open, dick the Toolbox button on the Smndard [Qolbar.

Usi"H COl/trois /0 build t1 f orlll

,. , ,

;-yrl hl~ m nOli

Page 49: Getting to Know Arc Objects

( I ,

III Drag an Image (antral from the Toolbox to the form.

Don't worry aoout where you put the control on the form because you will set its position in the fo llowing step.

.... 1 ~ AoIIIlla

pr.-jIOIO ...

~.:J:.!IQ ..

., , , , , ,

...

m In the Properties window, set the following properties for the Image (ontrol.

The Top and left properties that you will set below refer to the (oordinates on the form where the upper left (orner of the image will be placed. like Height and Width, the Top and left properties are set in pixel units.

- For Name, type imglogo

- Cl ick BackColor. dick the drop-down arrow, dick Palette, and click white

- Click BorderColor, click the drop-down arrow. click Palette, and click white

For Height. type 60

For Left, type 18

For Top. type 6

- For Width. type 216 and press Enter

The image control is resized and its color is white.

&._---""

Next you will spec ify the location of an image file (0 draw in the rectangle.

CIIAI'TER J CREATING /I. DIALOG IIOX

Page 50: Getting to Know Arc Objects

scctlon onc

m In the Properties window, dick the Picture property and dick the Ellipsis button that appears.

, 5

• -,. Ellipsis butlon

ID In the load Picture file browser, navigate to C:\ArcObjects\Oata\Manhattan_KS and dick l ogo.jpg. Click Open.

The picture needs 10 be shnmk so you can see the entire logo.

To shrink it , you will set the Image control's PictureSizeMode property.

m In the Properties window, dick the PictureSizeMode property and dick the drop­down arrow,

, m Click 3-fmPictureSizeModeZoom.

The fmPictureSheModeZoom option forces the picture to fit inside the rccmng!c without stretching or distOrtion. The other options e ither clip or stre ich if.

ilpyoghl:!d ma I.

Page 51: Getting to Know Arc Objects

( , There is an apple in the logo because Manhattan is nicknamed the Little Apple .

Next you will add a text box, a combo box, and a label. Users will clUer parcel values ;n[O the text box, the combo box will display a list of zoning choices, and the label will be used to display the calculated taX amount.

III Make the form window active and open the Toolbox. From the Toolbox, drag a Text Box, ComboBox. and label and drop them anywhere on the form.

'.. _ ...

I

8-OJ Select each control. one at a time. and set the following properties for each.

TextBox

Name: txtParcelValue

- Height: 18

- left: 96

- Top: 78

- Width : 150 and press Enter

ComboBox

- Name: cboZoning

- Height : 18

- Left: 96

- Top: 102

- Width: 150 and press Enter

Label

Name: IblTaxAmount

- Height: 18; Width: 72

- Left: 96

- Top: 126 and press Enter

- Caption: (remove all text t o make the caption blank)

- Click Font and dick the Ellipsis button. In t he Font dialog bOIl:, dick Bold for Font Style. Click OK.

CHAPTER J CREATiNe A "IAloe: BOX

Page 52: Getting to Know Arc Objects

.\L'l tlon nnc;

You see the th ree controls with the properties applied . They're all a ligned bc<:ause you set their Left property to 96. I'

1 • 1 d • • • I I • • •

m From the Tool box, add three labels. Position them as shown below.

1 3

-• , .- 1

m In the Properties window, set the Name and Caption properties fo r the three labels as follows.

- Nam e: IblVa lue; Caption: Ente r pa rcel value:

- Name: IblZoning; Caption : Zo ning type:

- Name: IblTax; Capt ion: Estimated tax:

· • • • • • • • • •

.. .... ~

: ---, 1,====; : ...... - j- 3

• •

I

The purpose o( these three labels is to display descriptive tcxt next (Q the Parcel Value text box. Zoning combo box, and Tax Amount label. As they are JUSt labels (or thc o ther controls (they don 't do an\'thing), you won't be writing any code (or them.

Usill8 ccmtlUis to b/lild {f form pyright

Page 53: Getting to Know Arc Objects

I

i

• I •

• • • • •

I • I , , , ! I , I ,

. xc '(I~l i

Next you will select all three labe ls [Q right-justify them.

Ell Drag a box around all three labels.

n.r« jibe"

~","d

m In the Properties window, dick the TextAlign property, click the drop-down arrow, and click 3-fmTextAHgnRight.

You will now complete the form by adding a bunol1 [Q display the tax and a button to dose the dialog box when the user is done.

m From the Toolbox, drag two CommandButtons to the form and position them as shown below.

ComrnandBunon ---. --,- .. ..., CommandButton

CI1AI'TER J CR&i\TINQ" DIA LO(; BOX

Page 54: Getting to Know Arc Objects

.'iL'ctIOll (1)1('

m For each CommandButton, set the following properties.

TaK button (on the left)

- Name: cmdCa lcula teTax

- Caption: Calculate Tax

Quit button (on the right)

- Name: cmdQuit

- Caption: Quit

• • • • • • • •

: ___ rl------•

• • •

-- 1 3

T1\c form has all its controls and is ready for a tCS I run.

m Click the form 's window to make it active. Click the Run Sub/User Form button .

T1\c {onn appears as a dia log box.

___ rl-------- 1-1-----"3

" " ,., .. No code runs, bec.'luse you haven't wri tten any. You doa test run [Osee how the dialog box will look to the user, without any selected controls and without any grid dots.

Using COl/l IM to Imild lI/arm

, , ,

I

'I I , t l

Page 55: Getting to Know Arc Objects

fa Click the x in the upper right corner of the dialog box to close it.

Normally, you would also be able to clkk the Quit button on the dia log box. b UI

since you haven't added any VBA code, it doesn't work yet.

Cl Close Visual Basic Ed itor.

m If you want to save your work, click the File menu in ArcMap and click Save As. Navigate to C:\ArcObjects\Chapter03. Rename the f ile my_ex03a.mxd and dick Save. If you are continuing with the next chapter. leave ArcMap open. Otherwise dose it.

CIIAPTI!R J C REATlNG A DIAtqq »Q,X

Page 56: Getting to Know Arc Objects

Programming with objects I'rORTamminR with m .. (I\fId.~

G.:uing and JI."uin8 un Objl'Cf'~ pruf>l'rtil'~

You worked with objects in the previous chapter when rou made a user (orm and added controls [ 0 it. The (orm is an object and so arc its controls. (These are VBA objects, not ArcObjects. They come with any application that includes VBA. ) You didn't do any programming, ho wever, so the (orm and contro l objects do n 't wo rk yet. To get these objects to do what \'00 want, you write code for their evenu, methods. and properties.

An event is a user action (like a mouse dick) that happens to an object. An event procedure is code that runs when the action occurs. Yo u worked with events and event procedures in chapter Z when ),ou created thc He lp and Tax Calculator U IBunons and coded their click event procedures. When someone clicks either bunon , your code runs.

A properly is a characteristic or an attribute o( an object. In a way, properties are like variables because they both sto re a value that rou can change. You set an object's properties to make it look different (rom other objects. For instance, i( you had some otherwise identical buttons, you could tell them ap.1rt by setting each o ne's Caption property differentl~'.

In the previous exercise, you used the Properties window to set property values. Fo r example, after you added the cboZoning combo box to the (oml, you set its name , le(t, top, and width properties.

An object's propert~' , 'alues can also be set by writing lines o( code that look like a sentence mixed with a math equation. This programmer's grammar, sho wn in the sample code that (a llows, is ca llL-d the "object dot property" syntax. To set an object's property with a line o( code, you begin with the o bject's name, a do t. and the prop­erty you want lO set. Thcn you use the equals sign and the value you want to set the property to. It 's sim ilar to sett ing a variable's value.

ightw malCrial

Page 57: Getting to Know Arc Objects

Object. Pr operty '" ·SomeValue"

Instead of usi ng the Properties window to sct the cboZoning combo box's left. top. and width properties. you could set them with the fo llowing three lines of code:

c boZon i ng.Left = 96 c boZon ing.Top ; 102 c boZon ing.Width = 150

Methods , also called behaviors . are the thinb'S that an object can do. A (ann object. for exa mple, has the following methods: Copy, Cm, Hide. Move. Paste. PrintFonn, and Show (to name a few). E.'lch method is a block of code th:u rulls when called into action.

The syntax for call ing a method into action is:

Ob ject . Me thod

Suppose you have a form object called frmAddRecord and you want to run its Show method. (The Show method opens the given (ann.) You would write the following line o( code:

frmAddRecord. Show

When the linc of code runs, the form opens to the user.

I - !,mAddlle<ord -57 '-_0 I ~ - I -

Methods are like events in that calling them il\lo action GUIseS a block of code to run. The difference is that while event procedures arc empty until you write the cooe for them, the procedures that go with methods have already been wri tten for you.

For the time being. you will only call methods into 'Ict ion. In chapter 9. you will learn how to write the code for a method.

In the next tw O exercises, you'll work first with methods, then with properties.

CHAPTER 4 PROOIV.MMI NCl WITH O IJ)ECTS

Page 58: Getting to Know Arc Objects

• SL'C(I()Jl (Int!

Programming with methods

The captain of (he spaceship Atlantis sits on the bridge and gives orders: beam up some crew members. put the deflecto r shields down. go to warp sp«d. If you think of the spaceship as an object, then the various orders it carries out arc its methods. For example,

At l ant is. warps peed

is the method that makes the spaceship go faster than light. Of course, going to warp speed isn 't a one-step task. A whole series of things takes place-people in the engine room flip switches, push leven, and monitor temperature levels; other people in navigation check the route and lOCal e obstacles.

A method, in other words. enta ils a procedure-a list of things to do. h may be a long liS[ o r it may be a short list, but either way you a lways use the object,method syntax to call it into action.

Some methods have variations that you specify with arguments you add after the method. The spaceship's Shields method , for example, has an argument to control the shield status, which can be either up o r down. The Status argument has two set­tings. To put the shields down you would write:

Atlantis . Shi elds Down

O ther methods, like the BeamUp method, have multiple arguments. When you write a line of code with arguments, you separate them with commas.

At l antis .BeamUp Andrew, Thad , Michael

A page o r twO ago, you learned that methods arc procedures that have already been coded for you. You may be wondering- by whom! The methods that belong to VBA objects. like fonns and contro ls. we re coded by Microsoft programmers. The methods for GIS objects, like U1Contro!s, maps. and layers. were coded by ESRI· programmers. Regardless of who does the coding--cven if it 's you- methods arc always called with the same object.method syntax in VBA.

Exercise 4a In chapter 3, you created the Tax Calculato r dialog box by dragging controls OntO it and setting their properties. However, you didn't wri te any code there. In this exer­cise you are going to write code to get the dialog box to work.

Your first task will be to write code for the Calcu late Tax burton on the Parcel Viewer toolb.1f. so users can click this bunon to open the dialog box. Next, you will write code fo r the d ialog box's Quit bunon, so users can click Quit to d ose the d ialog box .

ProgrrlmmillB willJ metbods

, .,.",

ighled :nalc'ial

Page 59: Getting to Know Arc Objects

\ ,

Finally. yo u will wri te code 10 add the words Residential. Commercial, and Ind ustrial to the zoning combo box . These words will beco me sclecmble cho ices o n thc combo box's drop-down list.

,-----.. - cboZonlng

D Start ArcMap and open ex04a.mxd in the C:\ArcObjects\Chapter04 folder.

W'hcn the map opens, you see the Manhauan city parcels and the Parcel Viewer 1001OOr.

D On the Parcel Viewer toolbar, right-dick the Calculate Tax button and dick View Source.

The lllisDocument code module opens. You see severnl procedures that you coded in previous excrcist.'s. However, the C'1lculate Tax bunon 's click evcnt procedure is empty. In exercise 2e, you wrote code that used an inpUl box to do tax calculations. Since you crc:Hed thc Tax C., k ula[Qr dialog box , that code has become obsolete, so il was deleted (or ~·ou .

In chaplcr ), you crcated the Tax C 'llculmor d ialog box and named it frmTax. Th is is the name thm you will use in your code to refer to the Tax C alculator fo nn. In the next li ne of code, ~tOu wi ll usc the Show method to open the form .

D In the Calculate Tax click event, indent for a new line of code and type f rmTax and a dot.

frmTax .

Afte r ),o u type the dot, a drop-down list of the form object 's properties and methods appears (unless you've turned the Auto List Members option off under Tools> Options).

\cons to the left of each item ind icate whether il is a property or method. Properties look like a hand and finger pointing at a database rable. Methods look like a fl ying green brick .

• " . ... _ c . . . .... . f~ <'''' '' , .. 1.. . -.... ..

...... to ,

.-CHAPTER 4 P ROORAJ,.IMING W!TII OBJECTS

Page 60: Getting to Know Arc Objects

.''- [/(In (11l1'

II ScroH down in the list and double·dick the Show method. (You could also type Show.)

When this line of code runs, the Show method opens the [aX form.

...... , • •• .. , ... ,., ...... <"."11 .......... -

.. ,.,.,. , •

Now thm ~'ou have programmed a way for users to open the Tax Calcu lator, you wi ll also progrnm a way for them to close it. You will add code to the di:Jlog box's Qu it button.

U In the Project window, under Project (ex04a.mxd), double-dick frmTax in the Forms folder to open the Tax Calculator form.

D On the form, right-click the Quit button and click View Code.

The form's code window opens and you see the wrnppcr tines for the Q uit button's click event procedure.

o In the click event, add the following line of code.

frmTax.Hide

Again, you are using the object.method syntax, where frmTax is the object and H ide is the method. When a user clicks the Qu it bunon, this code will run.

Pro;:mmmillJ.: with /lie/bods

,

1 ,

I

I •

yrl hl~m n

Page 61: Getting to Know Arc Objects

Nexr, \'ou will wrire code to add the zoning names to the zoning combo box. The code will be wriu en in the form's initialize evell( procedure. In the fo llowi ng steps. ~'ou will navigate to that procedure and write code in it.

o In the code window for frmTax, click the object list drop-down arrow and click UserForm .

The object list contains the names of each object (contro l) on the fo nn . as well as the (orm object itself. You might expect to sec fnn"TIlx in the list-since that's what you named the form-but instead you see User Form. No matter what name \'OU give the form . VBA always d isplays it as UserFoml in the object list.

Before you have a chance to do anything, C lick is selected in the ProCl •. -dure d rop­down list and its wrapper lines are added in the code window.

Objen lin

." ... . •• _ . . ... _C II .. " ........

C lick is the fo rm's def:lllit e\'ent procedure, When you select an object in the object list. its dcfauh cvcnt procedure's wrapper lines are aUlOmatica lly added (unless they arc already there). You arc not going to code the UserForm's click event . so ignore these lines or remove them,

With UserForm se lected in the object list , if \'OU click the drop-down ,lITOW in the procedure list )'ou'll St."C the rcst of the User Form 's event procedures, You will add its initialize e\rem procedure next,

D Click the procedUre list drop-down arrow and click Initialize.

The initialize event wrapper lines are addl.-d .

....... .... .... , ... _<1 "."

. ........ .... ... " . . .. _t ... ""' ... ,,

t .. ...

C II Ai'T£R 4 PROGRAMMINO WlTII O"lijE<r1"S

Page 62: Getting to Know Arc Objects

· .'il'Clfllll nne

Normally. you can set an object's properties with Visual Basic Editor's Properties window. Ho wever, combo boxes do n't have a property to ho ld the values that a ppear h ~ ,

in their drop-down lists. For this. you have to write code.

You add values to a combo box's list with the Addlt.cm method. For example, to add the color choices Red. Green, and Blue to a combo box called cboColor, you would write the following three lines of code:

-, ...... " . ..... . -, ....... ,,--... . _ ....... ,,- '" .. '

You put these three lines of Addltcm code in a fonn's initialize evcnt, because code in the initialize event runs in the moments befo re the fo rm opens [ 0 the user. That way, the combo box is filled with choices before the user sees the form. When the user clicks the drop-down list, the choices arc there and ready to be selected.

m In the UserForm's initialize event. add the following three lines of (ode.

The Addltem method adds one value to the combo box's drop-down list. To add three values. you have to use the Addhem method three times.

cbozoning.Addltem -Resident i al" cbozoning.Addltem -Commercial· cboZoning.Addltem -Industr ial·

... _. _ _ " " •. ,.,,,,""11 -_ ....... ".- ............. ,. __ ' ....... ,,_ oc-• • •• ," --' ... _" .. ",-. ... ,"

m Close Visual Basic Editor.

You have wrinen procedures to help the user open and close the Tax C,\culator dialog box and [Q add values to the zoning combo box. Next you will test all rhree procedures.

Progmmmi"8 with ml'fI.JO(is opyrighl:!d ma ,.

Page 63: Getting to Know Arc Objects

m On the Parcel Viewer toolbar. click Calculate Tax .

. -.~ .~

The fonn's Show method mns and the dialog box opens.

m Click the Zoning type drop-down arrow.

The zoning types appear in the list and can be seiL'Cted. YOli sec the choices in the list, becausc thc)' were addL'(1 as the form initialized. (These choices don't actually do :m ything yet, because there is no code behind them.)

---_.-Ie Click Quit.

The form's Hide method runs and the form closes.

In the next exercise, ~'ou will cont inue (0 code the dialog box.

m If you want to save your work, click the Fi le menu in ArcMap and click Save As. Navigate to C:\ArcObjects\Chapter04. Rename the f ile my~e)(04a.m)(d and click Save. If you are continuing with the next exercise, leave ArcMap open. Otherwise close it.

Page 64: Getting to Know Arc Objects

'll(/flll

Getting and setting an object's properties

In the Propert ies window below, you see properties for the Q uit command hutton. The caption property is, naturally enough, the word Quit. Naturally, that is, if rOll

speak English . If your users arc Spanish speakers, you would want the button to say Tenn in:lr instead. And you could easily make this change juSt by typing Tenninar where Quit is now.

.. _. .... .

C.ptlon on commlrld button

But suppose your uscrs included both EI\gJish and Spanish speakers. You might want to creatc a bi lingual d ialog box in which captions switch (rom onc language to another depending on who's using the application. To do that. ~'ou would first have to write some code that asks the uscr (or their language preference and SlOres the value in a variable. You would then go on to set the appropriate caption property with a line o( code.

The code to sct a caption property would look something like ,his:

cmdQuit. caption = -Terminar -

t-. ",,,,~ 'N" n ,. T~mI'I#"

==~= In this example, you were concerned with .seuing the value of a property. In o ther situations, you may want to find out the value of a property that has already been set. It may be a property that changes according to uscr input, and you need to know what it is so that you can usc it in ano ther ca lculation. Finding out a property's va lue and sloring it in a variable is called getling a properry.

GeUill8 (I/J(J .. ~l'Ilillg (m a/1jecl s /J1'O/)crtil'S

I)nt!

,

Page 65: Getting to Know Arc Objects

Suppose you're writing a handy little tool ro convert fee l to melers. Your dialog has a few different controls-a couple of teX[ boxes and a bun on. The top text box is called rxt Feet and its Text property is SCt to whatever value the user types in. The bon om text box is called txt Meters and its Text properr~' wi ll be SCt programmati­cally after the user clicks the Convert to Meters burton.

_ ... ~ ... 1- txlFftt text bo~

--- I r,--- txlMetel'\ te~t box

To get a property, you use a variable and an assignment statement with the fo llowing syntax:

variable = object . property

Here, you want to get the Text property of the txtFeet object. In the nex t line, the variable is called Feet , but it cou ld be callcd anything.

Feec : cxcFeec.Text

After the line runs, the variablc will contain the valuc typed in by the user (5280 in this exa mple).

Now, where docs this line of code goexactly11t goes inside the click event procedure of rhe Conver! to Meten button.

Public Sub cmdConvertToMe ters_Cl i ck() Feet: txtFeet.Te xt txtMeters.Text = Feet· 0.3048

End Sub

When the user clicks rhe Convcn ro Mcters bunon, rhc first linc of code geLS (hc Text property from the rxtFeet object. assigning this valuc to the variable Fect. In the second line of codc, to the right of thc equflts sign, the vfl ri flb le vflille is multi ­plied by the conversion fac tor. The line as a whole sets the resuh as the Text property of the txtMeters object.

W hen the event procedure runs. rhe vfl lue ( 1609) displays in the DaMeters ten box.

_0 ._ ,_ cmdCOf'I~nToMeten _ , c-. -. I , , ...

txtFHt tUI box

txtM ele ,s lett box

An t!xperienced programmer cou ld bypass the explicit variable assignments and write the code more efficiently in a single line: rxtMeters.Text '" u:tFeet.Text • 0.3048.

C IIAn'IlR 4 PROG RAMMING ..... IT II OBJECTS

Page 66: Getting to Know Arc Objects

~L'ctl()n (lne

Exercise 4b In this exercise, ~'ou will write code fo r the Tax Calculator dialog box to get the user's parcel value, calculate its tax, and display that amount.

D Start ArcMap and open ex04b.mxd in the C:\ArcObjects\Chapter04 folder.

When the map opens, you see the Manhattan ciry parcels and the Parcel Viewer (ooIOOr.

o Click the Tools menu, point to Macros, and click Visual Basic Editor.

D In the Project window. under Project (ex04b.mxd), open the Forms folder, and double-click frmTax to open the Tax Calculator.

D On the form. right-click the Calculate Tax button and click View Code.

The form's code module opens to the button's c1kk event wrapper lines. You also see the events you added in the previous exercise.

You are about to create a variable to store the parcel va lues and you need to choose its data type. The C urrency data type can Store va lues up to 922 trillion, bur requires 8 bytes. The Long data type can sto re values up to 2.1 billion and takes up JUSt

4 bytes. S ince all the parcels in your area are well under 2.1 billion, you'll usc Long.

D In the Calculate Tax cl ick event procedure. add two lines of code to declare and set a long variable to hold the user's parcel value. To get the parcel value, use the text box's Text property.

Di m userValue As Long userValue = txtParcelValue.Text

". ,.. ... ...,

-----.O' ' . ...,

G£'lIiIlB (fud .Wllillg all object 's pmpel1i('s j:" right 0:0' "

Page 67: Getting to Know Arc Objects

l

II Add two more lines of code to decla re and set a variable to calculate and hold the tax amount.

Dim taxAmount As Long taxAmoun t : (user Value • 0 . 02) + 8 . 55 + 11

This is the same equ:nion you used in chapter 2 when rou crea ted the Tax Calculator button. There is a 2-percent residential zon ing charge (0.02 ), an $8.55 comrcntion center fcc, and an $11.00 fire truck fcc.

Instead 0( 0.02, it wou ld be ideal to usc a variable that changes to represent residentia l, commercial, or industrial tax f".ltes. In the next chapter. }'ou'lllca rn how [Q do this as you fini sh the Ta.x Calculmor dialog.

D Just above the two lines of code you added in the previous step. insert two comment lines to remind yourself and other programmers that you have assumed the residential loning rate until actual zoning values can be determined.

Comments begi n with an apostrophe and appear green in the code window. Since VBA ignores comments, they won't slow your code.

'zoning values will be determined later. 'Residential tax rate is a ssumed in calculation below.

Next you'll add a line of code to display the tax amollnt. You'll do it by setting the Caption property of the IblTaxAmollnt label, shown below with a value of 5020.

D At the end of the event procedure, add the following line of code to set the label's ca ption property equal to the calculated tax amount.

l blTaxAmount.Capt ion = taxAmount

The Quit burton's click event uses (he Hide method to close the dialog box. Hiding a dialog box keeps it, its controls, and all their property senings in memory. When a hidden dialog box is rffipened, the UserForm initia lize event procedure doesn '( run again. That means its most recent settings reappear. Were a user to select Industrial in the w ning combo box and then click Quit , Industrial would appear when the dia log box was reopened.

CltAI'TER 4 PROGRAMMtNO WITII OBJECTS

Page 68: Getting to Know Arc Objects

· 'il'((f'/l1 nne

You will write code in the Qu it button 's click event to clear the combo box's selection area, the text box's (ext area, and the label's caption, so that thc~' will be empty each lime the dialog box is reopened.

D In the cmdQuiCCl ick event, add the foHowing three lines of code.

This code sets the Text propcny of the combo box and (ext box and the G lption property of the label to a blank text string.

cboZoning.Text : •• txtParcelvalue.Text = •• IblTaxAmount.Caption : ••

The code is ready to tcsc.

m Close Visual Basic Editor.

m In ArcMap. on the Parcel Viewer toolbar, click Calculate Tax.

ID For parcel value. type 250000.

m For Zoning type, click the drop+down arrow and click Residential .

Your coded calculation uses the Residential tax va lue 0(2 percent, so even if you select Commerc ial o r Industrial the sa.me value will be calculated.

m Click Calculate Tax.

The estimated tax, 5020, appears.

---. 1--- I ' " 3 , ,~ -

GeItIIlS l/lUi .wllfllg fill objc:>ct s properti£'S

,

or right

I

,

,

A

0:0' "

Page 69: Getting to Know Arc Objects

\ l 1 l

Next you willtcst 10 see that the pared va lue, w ning type, and cstimmcd taX are cle<l red when the di <l log box is closed and reopened.

m Click Quit.

III On the Parcel Viewer toolbar, cl ick Calculat e Tax.

As the form opens, its init ialize event docs not run. The code that ro u addl.'d to the Quit button 's click event clears the parcel value text box, the zon ing combo box's selection area, and the tax amo unt label.

, .. . ~ ..... .

--- I -- I 3 • . ... '

m Click Quit .

II] If you w ant to save your work, click the File menu in Arc Map and click Save As. Naviga te to C\ArcObjects\Chapter04. Rename the f ile my_ex04b.mxd and click Save. If you are continuing with t he next chapter, leave ArcMap open. Otherwise dose it ,

C II AI'TER 4 PROG RAM MIN G WIT II OtiJ ECI'S

Page 70: Getting to Know Arc Objects

Code for making decisions Makin,!; u Ca.5e for branching

Coding 1111 If Then ~f(.Ircmel\t

Unless otherwise dircoed, lines of code in a procedure run, in order, from first (Q

last. Ho wever, lines of code can be grouped into blocks, and decision-making state­ments, called Case and If Thcn, can control which blocks run and wh ich don't.

Case statements handle multiple-choice situations. Suppose you have a dialog box mat asks "What layer do you wam to add to the map!'" A combo box after the ques­tion contains five choices: Roods. Rivers, Lakes, Soils, and Elevation. If the user picks Roads, a block of code runs [Q add the roads layer to the map. If the user picks Lakes, a different block of cOOc runs to add the lakes layer. Each choice callses different code tonm.

In a Case statement, you write a block of code IO run for each possible choice. Depending o n the choice, the appropriate block (and only that block) runs.

If Then statements handle true·false situat ions. Suppose you have a d ialog box that asks "00 you want to print the mapr' and conmins a Yes button and a No button. If the user dicks Yes, one block of code runs and a map is printed. If the user clicks No, no code runs and no map prints.

In an If Then statement, you write twO blocks of code. One runs when the statement is [rue and [he o rner runs when the statement is false.

ighted material

Page 71: Getting to Know Arc Objects

, • • ,

I , , I I

Making a Case for branching

Case statements process multiple-cho ice siruarions jusr like you do when you approach a tmffic signal: when the light is red, you stop; when the light is green, you proceed with caution; when the light is yellow, ~'OU slow down and Sl Op unless you can get into the intersection before the light rurns red. When the light is flashing n.-d , or when the ligh ts arc o ut, you treat th" interseerion as if it h ;ld a Stop sign.

A Case statement starts with the Select C 'lSC keywords and a variable Ihat conmins a va lue, which (or the status of a traffic light might be red, green, or yellow. For each possible value. there is a Case keyword and the value. After that, you add all the code necessary for that va lue. The End Select keywords end the statement.

Select Case theTrafficSignalValue

Case Red

Stop the car

Case Green

Continue with caution

Case Yellow

Stop the car if you can't make it before red

End Select

The Case stateme nt above assumes [hat theTrafficSignalValue has on ly three possibi lities: red , green, or yellow. But if there's a power failure in the area, the ligh tS won't work. To account for any odd or unexpected values, you can usc the Else key­word. Below, Case Else is a fourth case add" .. d to handle a traffic signal value other than red, green, or ~'e llo ","

Case Else Treat the intersection as if it has a stop sign

Exercise Sa Parcels in the ci ty have one of three zoning types, residential, commercial. or indus­u ial, and each zoning type h3s a different [aX rate. In th is e.xercise, you'll create. a C'lSC Slalement to determine the user's zoning type and apply the appropriate tax rate.

o Start ArcMap and open exOSa.mxd in the C:\ArcObjects\ChapterOS folder.

When the map opens, you see the Manhattan city parcels and Parcel Viewer toolhar.

D Click the Tools menu, point to Macros, and cJick Visual Basic Editor.

D In the Project window, under Project (ex05a.mxd), double-cJick frmTax under Forms to open it .

CHAPTER 5 CoilE fUM MA':IN{, IlECISIONS

Page 72: Getting to Know Arc Objects

't.'l (1011 flJlC

You sec the Tax C., lculator fonn.

EI On the form, double·click the Calculate Tax button to open the form's (ode wi ndow.

Double-clicking a contro l opens the fonn's cooe window (or brings it to the front if it's a lready open). It opens to the control's default even! procedure, which, for the C., lculate Tax CommandButton, is the dick event.

· lDo ... _, __ .," .......... _ , •••• •

, .. " ... "., .............. _ •• eo, ... ,"' .... ..... ..... , .. """" . ... _ • • _ ..... ,_ • 0 ." • I ." • U

. .... .

Now you'll add some cooe at the top of the dick event procedure to include the zoning type in the calculation. You'll need a variable to hold the faX rate (which changes) and a Case statement that assil.'lls a value TO this variable according to the user's selection in the zoning combo box. If the user picks Residential, (he variable value wi ll be 0.02; if t hey pick Commercial. it will be 0.023 ; and if (hey pick Industrial, it will be 0.0275.

D Insert a new li ne between the Private Sub line and the first Dim statement .

"" '''·0' - -+- 1 _ ..... , .. ......... ,.,., ...... .. . ....... .. ,_ .. II ............... ,,, .. . • _, ....... ' . .. , ........ _ d I ...... , ......

. .. . &>< . .. .. .... I,,' • • _ .... , ... 0.'" . .... . "

D On the new line, add the following (ode to declare a variable for the tax rate.

Dim sngTaxRate As Single

The Single data type only requires four bytes of space and can hold decimal values. h 's the most efhcien! numeric data type fo r storing small numbers that have decimal places.

Next, rou'li code the Case Statement. In exercise 4a, you used the Addh em method to populate the combo box with choices. When the user makes one of these choices, it is set as the combo box's Value property. The possible values of that property deteml ine the cases you nt.-ecl to cooe.

Maki llg a Case/or l; /"tll/cb illR ~Yfl hl~ m n

Page 73: Getting to Know Arc Objects

• • I

In each branch of the C , se statement, sngTaxRatc will be set lO the tax rate (or the selected zoning type. (The Industrial type is selected in the graph ic below. )

-----'= " .. ,

II After the line of code declaring the sngTaxRate variable, add the first and last lines of a Case statement. For the Case statement's value, use cboZoning.value.

Select Case cbozoning.Value

End Select

Next you will add thrcc blocks of code, one for each type of zoning.

D Inside the Case statement, add a Case to (heck for Residential value. Add a second line of code to set the tax rate varia ble to 0.02 .

Case "Residential " sngTaxRa t e ; 0 .02

Each case is indented from the main Select Case statement and each case's block of code is indented to make it easy to read.

D Add two more Cases to check for Commercial and Industrial values and set the tax rate variable for each.

Case 'Commercial " • I sngTaxRa t e = 0 . 023

1 Case • Industrial" s ngTaxRate = 0 . 0275

. .. ......... to ... . , .. , _

.. ,..,. c ___ ' ... v .... Coo- ..... , .... , . , •

......... _ •• 0.0. c ... "Cooooo .. ,. , '

• ..,. ...... . G. G" C .......... . , . , •

......... _ •• •. ou, ..... , .. ,

CU"P'TRK 5 CoOl' fOR MAKINO DECISIONS

Page 74: Getting to Know Arc Objects

.'ill!/') till

m Scroll down in the code to find the two comments about resident ial zoning and delete them .

.... _., ..... ... ...... , .. ......... , .. , ...... . • ..... • .... • 11 .... ,

m Locate the line that calculates the tax amount. Replace 0.02 with the variable, sngTaxRate .

.... _ .... ,- .. '"-_ ..... , .. . . . . . ..... ' ... ' ... T • • '

.... .... , .. '"-, .. , . • • _ .... , _ • _ . I.U • "

• , u '

The code is now ready [ 0 [est.

m Close Visual Basic Editor.

T .... v.lue c.kul.ted her~

m On the Parcel Viewer toolbar, click the Calculate Tax button.

m For parcel value, type 400000.

m For Zoning type, click the drop·down arrow and click Industrial.

'.0 ~ .,~ . ....,-

---, --, ". , ... ,

.\fakIIlM (I Ctl$(' for brtlllclJlng ( yrl hl~m n

Page 75: Getting to Know Arc Objects

,

II] Click the Calculate Tax button.

TI\e estimated tax, 11020, appears. To t CS t rour Case smu~mem with the other zoning types, you will switch zon ing types and recalculate the tax .

m For Zoning type. click the drop-down arrow, and click Commercial. Click Calculate Tax.

The cstimatt:d tax, 9220. appears.

m For Zoning type, click the drop-down arrow, and click Residential. Click Calculate Tax.

TI\e cst imau.od tax. 8020. appears.

Depending on the user's loning, your C1.SC statement runs the ::Jppropriatc block of code 10 calculate the tax rate.

m Click Quit.

m If you want to save your work, click the Fi le menu in ArcMap, and click Save As. Navigate to (:\ArcObjects\ChapterOS. Rename the file my_exOSa.mxd and click Save. If you are continuing with the next exercise, leave ArtMap open. Otherwise close it.

CHi\PTfR 5 CoilE FOR Mi\t:ING 1lE(:ISIONS

Page 76: Getting to Know Arc Objects

, I I ) \ ! I n ... -

Coding an If Then statement

Out driving, you approach a fo rk in the road where going left takes you into the city and right takes you into the countryside. You need to make a decision on which way [ 0 [urn and to do that you ask yourself a t rue-or-false question. Is today a work day! If it 's a work day you go left to your offi ce in the city. If it's not a work day, you go right and take a relaxing drive in the countryside.

You can writ e code to process this decision with the If Then statement below. The first line in an IfThcn statement contains an expression (below. it's Today · aWorkDay) between the keywords If and Thcn. 1f the expression is truc. the block of code between If Then and the Else keyword runs. If the expression is false, the block of code between Else and End If runs. The End If keywords end the statement .

If Today = aWo r kDay Then

Tur n l eft t o work i n t he city

Else

Turn right to drive i n the countryside

End If

The essentia l thing about If Then expressions (also called Boolean o r logical expressions) is that they are either true or fa lse. For example, 4 < 5, 20 > 40, 2 <- 2. and "He llo" - "Good bye" are all logical expressions, because when you evaluate the ir logic they result in either a true o r fa lse answer. But 4 + 5, on the other hand, is nOt a logica l expression. When }'OU evaluate 4 + 5, you get 9, and the number 9 is no t the S;lme thing as true or false.

Logical expressions can compare twO values using math symbols called comparison operators. These include the equals sign ( . ), gremer than (», less than « ) , greate r than or equal to (>- ), less than o r equal to «-), and not equal to « ». In the expression below, if x is 10 and y is 5, the expression is true. If x is 2 and y is IS , the expression is false.

x > y

Logical expressions can be combined with logical connecm rs, which are English words like AND and OR. Below, AN D combines two expressions into one larger expression. In o rder for the full expression (Q be true, both smaller expressions must be true.

x>y ANDa: b

With OR, only one of the expressions must be true for the full expression to be true.

x >yORa= b

ClJ{IiII)l, lIIl l/7bell staf(!IIIl'm ighled :natcrial

Page 77: Getting to Know Arc Objects

Another way to create an expression is with a function. VBA comes with a v,uiery of predefined functions including a group that are named with the Is prefix: IsDatc, IsEmpty, IsError, IsMissing,lsNull, IsNumerk, and IsObjecl. The Is (unctions all result in tme or fa lse. Fo r example, the IsNumcrk function ICSlS a variablc to sec ifil contains a number. If x contains a number, the expression below c\'aluates to true; otherwise, it's false .

If IsNumeric(x) Then

A third way to creatc an expression is by gening an object's propcny. CommandBunons havc many true or false properties, as shown in the Properties window below .

...... ,~. ... ....... .'

:;]

'I - ... • ",,",",,0'''' ~- •• "''''il - .-s. ".". ~- -~ ,-

The En.abled Pfopeny ~d ,-is set to True - .-- ,-

'.of ..-.0.'''' Quit button --- '- '" You can use the objl"cl .propeny s)'max to create an expression. Whl"nlhe Quit button 's Enabled property is True, thc following expression is true:

If cmdQu it .Enabled Then

An If Then statement can eva luate multiple expressions wilh the Elself keyword. Below, twO Elsclfs arc ust-d to evaluate expressions fo r a lkaline and nem ml pH Icvels. If the If The n expression is true, o r if either of the Elself expressions arc lrul". the code after that expression runs. If a non-pH value is entered (less than zero or greater than 14). the code after the Else keyword runs.

If intPHLevel < 7 And intPHLevel >= 0 Then MsgBox "You have an acid"

ElseIf intpHLeve l > 7 And intPHLevel <: 14 Then MsgBox "You have an alkaline"

Elself i nt pHLevel : 7 Then MsgBox "The va lue is neutral"

Else Ms gBox "The value is outside the pH scale "

End If

C HAPTER 5 CoOl! FOR ~I"KINO QEC ISIONS

Page 78: Getting to Know Arc Objects

.\l'l"ll()n Clnt!

Exercise 5b If users enter nonnumeric values in the Parcel Value text box , they get a rype mismatch error ..... hen they click the Calcul'lle Tax bun on. Bela ..... , the user types "$200.000" (with qumation marks) inlO the text box, clicks C alculate Tax, and gets an error message.

' - ~,'. ,.

-_.-, --.. - ... _---

The error appears be<:ause me quo tation marks make $200,000 a string instead of a number. VBA c.·mnot multiply a string and a number:

"$200,000" • 0 . 02

In th is exercise, you will code (he Parcel Value text box's C hange event. E'ICh lener or number that the user types intO the text box causes code in the C hange event procedure to run. Whenever the user makes a change to the text box, the code runs.

You'll put code in there to determine if users are typing letters o r numbers. If they type letters, your code will disable the Calculate Tax bunon by setting its Enabled property to false . When a button is disabled, it is grayed out.

D Start ArcMap and open exOSb.mxd in the C:\ArcObjects\ChapterOS folder.

When the map opens, you see the Manhattan city parcels and the Parcel Viewer toolOOr.

D Click the Tools menu, point to Macros and click Visual Basic Ed itor.

COt/iIlJ.l (1II1f7bell ~Ultl!l1Il!lII

~ ,.,

Page 79: Getting to Know Arc Objects

I • • •

I

• I t

I • I I ,

\ e , D In the Project window, under Project (ex05b.mxd), double-click frmTax under

Forms to open it.

You see the Tax Calculmor. You will wril e code that validates the valucs thm are typed inro the Parcel Value {ext box .

.. ~ ... • I , , • • • -;---I -- 3 , • , • .. ... ,

D On the form. double-dick the Parcel Value text box (txtParcelValue) .

The form 's codc module opens ( 0 the text box 's change event procedure. C hange is the dcfauh event for text boxes and it 's the one rOll will wrile codc in.

.. ......... .... ' ..... L ••• "

........... ........ ·.,.,,,· ,, .. u --' ........ ,,- _., .... ,.,. D Inside the change event, start an If Then statement. For the logical expression,

use the IsNuffieric function to evaluate the Parcel Value text box's Text property.

If IsNumeric (tx t Parce l Value. Text) Then

The IsNumcric function is truc whcn the user enters a number "nd (" Ise when any olher values are entered.

D Indent and add the following Hne to set the Calculate TaK button 's Enabled property to true.

cmdCalculateTax .Enabled = Tr ue

As long as the user types numbers into the P"rccl Y"luc lext box, the C.,lcul,,[e T"x button will be enabled.

o Outdent and add the Else statement.

El se

CUAPTER 5 Colli; FOR MA"INO DECISIONS

Page 80: Getting to Know Arc Objects

Sl.-l(11

D Indent and add the following line to set the Calculate Tax button's Enabled property to fa lse.

cmdCalculateTax. Enabled = False

When the user types anything other than a number imo the Parcel Value lext box, the Calculate Tax bunon will be dis.'lbled {grayed o ut}.

o Finish the If Then statement with the End If keywords.

End If

F,,_~~ .-., ... , ... , ...... , .... ro,_ "

TIle If Then statement is ready [Q test.

m Close Visual Basic Editor.

m On the Parcel Viewer tool bar, click the Calculate Tax button .

m For the parcel value, type Hello.

As soon as you type any text , Calculate Tax is disabled.

.. I m Change the parcel value to 250000.

As soon as you type numbers, the Calculate Tax button becomes enabled.

m Select Residential zoning and click Calculate Tax to see the button work correctly.

The estimated tax of 5020 d isplays.

m Click Quit .

You type a lot of variable, method, and property names. To help minimize typing mistakes, you can let VBA's code completion option type fo r you. For example, you type

emdC

as if rou arc going to type cmdCalculateTax.

Codillg fill If 1bcII sftllel1WIlf

I I 11 l

,

yrl hl~m n

Page 81: Getting to Know Arc Objects

\, , But afle r typing juSt emde, ~'OU press Como! + spacebar on the keyboard. TI)is calls VBA's code completion option into action. II fini shes the typing for you:

cmdCa lculateTax

Use code completion to reduce t ~'ping mistakes in ,·:.t riable. method, <lnd property names.

III If you want to save your work, click the File menu in Arc Map, and click Save As. Navigate t o C:\ArcObjects\Chapter05. Rename the file my_cx05b.mxd and click Save. If you a re continuing with the next chapter. leave ArcMap open. Otherwise close it.

C H"I"TER;; CoOl! FOR MAK ING DECISIONS

Page 82: Getting to Know Arc Objects

CHAPTER 6

U sing subroutines and functions CaHing a Helln-outinc

Pwsjfl8 l,«iues to a 51lbrollfinc

Mukillg set'eral c(.Ilb 10 a 3ingle,ubulUtillc

Rerllnli)!.': t'{ll«eJ with functions

Up ( 0 this poim, you've been working mostly with event procedures, which run in response to a user acrion o r a change in the system state. In this chapter, you'll take a closer look :u subromines and functions.

Like an even[ procedure, a subroutine is a liSt of instructions that carries out a task. The task may be to print a map. buffer a feature, add a field to a rabie, or any number of things. What distinguishes a subroutine from an event is the cue that sets it in action. An even! procedure runs when irs event occurs. A subroutine runs when it is called by anmher procedure. A call is a line o f code that says, "ProcL"Ciure So-and-so. . , " It S your rum to run.

The ca lling procedure may be nn event o r it may be another subroutine. Forcxamplc, an event procedure could call Subroutine A , which calls Subroutine B, which calls Subroutine C, and so on.

like a subroutine, a nmcrion is a procedure that waits to be called. It's different from a subroutine in this respect: when it's finished, it returns a value to the line of code that ca lled it. A subroutine might assign symbology to world coumries based on their population values. A function might sum the population value for each coun­try and return the earth's popu lation.

Instead of having lots of different procedures calling each other, you might be wondering why you couldn't put them a ll inw one big block. In the example above. why not take all the code fo r Subroutines A, B. and C and put it right inside the event procedure! That way, when the event occurs, all the code runs and nobody has to call anybody.

Page 83: Getting to Know Arc Objects

• •

In fuC l , you could wrile code that w'ly-it 's just not efficiem . Writing code in discrete blocks that call other discrete blocks has severa l advantages. For o ne thing, it makes if easier to reuse the code. Suppose you've made three buttons with different dick event procedures. O ne draws buffer zones, another intersects tWO layers, and the th ird uses o ne layer to dip another. In each case, you wam to print the map after the operntio n. You could copy and paste your m:lp-printing cod!;' into all three event procedures, but it's simpler to write the code once and run it with a call from c:lch of the event procedurcs.

Suppose you decided to do the copy and pasting anyway, and then found that your map-printing code had an error. Instead of debugging it o nce in a subro ut ine or fune­[ion, you'd have to debug it in three different cvent procedures. The same goes for updat ing it. Say you want to change the way maps are printed-you'd have [ 0 make the change in thrl.'C places instead of one.

Subroutines and functio ns also keep your code o rganil!ed.lf you have several tasks to perform in sequence and you code them all in a single lo ng block, it's easy to lose track of what a particu lar line of code is doing and what has already been done.

In this chapter's four exercises, you will call and modify subroutines and write a (unction .

(.·UAI"TI!R 6 USING SUHIIOUTINFS ANn I'UN(.'TIONS

Page 84: Getting to Know Arc Objects

· \lL"(Inn (Inc

Calling a subroutine

You tell a subrolltine to run with the Call statement.

Public Sub GetMessages() Call Message

End Sub

The subroutine above is called GetMessages, and it does only onc thing: it teUs another subroutine, called Message. to run. When called, the Message subroutine runs and displays a mcss..,gc box .

Public Sub Message() MsgBox "Geography 15 terrific·

End Sub

A ny procedure that wants [Q display the words "Geography is terrific" can call the Message procedure. Below, the DailyQuote subroutine calls Message.

Public Sub DailyQuote() Call Message

End Sub

One procedure can call many others. Below, MakeMap_Click is a button's click even! procedure. It tells three subroutines to run. As one fini shes, the next one begins.

Public Sub MakeMap_Click() Call AddCartographicComponents call CheckForPrinter Cal1 PrintMap

End Sub

A procedure may call a procedure that calls another procedure. Below, cmdMcss..1gc_C1ick calls Test2, which calls Tesu.

Public Sub cmdMessage_Click() Call Test2 frrnGIS.Hide

End Sub

Public Sub Test21) Call Test3 MsgBox "VBA is fun"

End Sub

Public Sub Test3 ( ) MsgBox

End Sub

CalliuS (/ slIlJrf)lItilU!

"I'd rather be writing procedures"

, ..

ighled material

Page 85: Getting to Know Arc Objects

The chain of called procedures begins with an event. As each procedure is called. its code runs; when it fini shes. comra l returnS to lhe calling procedure.

Below. commems identify the order in which the lines of code run. To begin with. the first twO lillC5 0( the click event nm. The second line of the click event ca lls Test2. and its tim two lines run. The second line of Test2 calls Tesu. and its three lines run . When Tesu fin ishes. control returns to Test2 and its last two lines run. When Test! /i ll ishes, contro l returns 10 the click event and its last tWO lines run.

Public Sub cmdMessage_Clic k () Call Test2 frmGIS.Hide

End Sub

Public Sub Test2() Ca ll Tes t3 MsgBox ·VEA is f un"

End Sub

'1 '2 '10 , 11

' 3 '4 '8 , 9

Public Sub Test) () • 5 MsgBox "I'd rather be writing procedures" '6

End Sub '7

This means that the message " I'd rather be writing proct.-dures" displ.1YS before the message "VBA is fun ." The "VBA is fun" message d isplays before the Hide method runs on frmG IS.

Exercise 6a You work as a programmer on the Washington, D.C., Police Department 's C rime Analysis team. E.'lch week, your team mects with the mayor, police ch ief, and prc­cinct captains to d iscuss how to reduce crime.

During the meetings, analysts display maps showing where crimes have occurred . But as rhey zoom in on a cri me, everyone elsc loses their scnsc of where in the cif)' it 's locared. They'd like a second window that displays the ('mire city. with a marker showing whe re they' re zoomed to.

You have been reading the book Exploring ArcObjects (parr of the ArcG lS software documentation available at www.esri.com!ExploringArcObjects). In the 1:xJok, you have found a sample subroutine called C reatcOverviewWindow that docs just what you need. Part of being a good programmer is being a good thief. Stealing this code will Sl.we you a lot of programming time.

In this exercise, you will import the C reateO verviewWindow subromine and call it from a click event.

C IIAI'TER 6 USING SUBROUTINES ANI) fUNCTIONS

Page 86: Getting to Know Arc Objects

(llelll ,Inl'

D Start ArcMap and open ex06a.mxd in t he C:\ArcObjects\Chapte r06 folde r.

When the map opens, you see Washington , D.C., layers and the C rime Anai\'sis toolbar. which contains severnl buttons that you will code in this chapter.

Cnme AAi!ylIS toollMI

0 " 0

" __ Ot, __ -.

• C o ..

-Ii'! CI,~ w

, • • •

. , , If rou havc worked th rough the fi m fi \·c chapters o( the book. most o( yom lOolbars rna}' be tume<1 off.

D If they' re off. turn on the Standard. Tools. and Draw toolbars.

D On the Crime Analysis toolbar; right-d ick the Overview button and d k k View Source.

In the ThisOoc.ument code window. you see the Overview click event. This is where rou wi ll write the line o( code that calls the C rcateOvcrviewWindow subroutine. First. however, you will impon the subroutine.

I .. . ...

Ca lfillg {I slI lmmrl1le OPYflCJhl"':d a 'I

Page 87: Getting to Know Arc Objects

I

In the Project window, right-d ick Project (ex06a.mxd) and dick Import File .

The code you ilrc going to import was obtaiIH.-d from the Explorillg ArcObjeces book. Since some people may not have the book, the sample code to create an overview window has been provided with this book's data CD.

In the Import File dialog box, click the Files of type drop-down arrow and click All Files. Navigate to C:\ArcObjects\Oata\Samptes\ExploringArcObjects and click CreateOverviewWindow.txt. Click Open .

You didn't see anything happen, but a new standard code module has been added to the project . Code modules arc the windows in which you write and s[Qrc procedures. When you impon: code, ,I new standard module is automatically created 10 ho ld it.

In the Project window, under Project (ex06a.mxd), click the plus sign next to the Modules folder to open it .

--- Nf:W modulo: Iddt'd here

In the Modules folder, double-dick Module1 to open it .

You might recognize, in a general way, what the code in C reatcOverviewWindow docs. The first lines are comments fo llowed b\' several Dim statements for declaring variables. The next lines set those variables with the Set keyword. (You will learn how [0 set object variables in chapter 9. ) The last lines use the fami li rl t object.property syntax to set properties for a blue out line symool on the rectangle that shows where [he ArcMap display area is zoomed to.

The subroutine uses some ArcObjects code that you won't learn about umil chapter 10. It 's O K if you don 't undcrs«,md the details. In this si tuation, all YOll need to know is thai when you (ell the subroutine to run, it runs and opens an overview window .

... ....... <Y . .. ... ,_"", .. I .. """rv, ... ,_ . ... ,_ ... , ... , _ _ I ..... , •• ,_.,.0,0., ... 1 ..... '_.'.0.0.' I ... . " 11 • .-' ... ,._,.,,,u_,

C HAI'TE R 6 US INC SU BROIITINES ANI) FUNCTIO NS

Page 88: Getting to Know Arc Objects

, lll(lll (Jnl'

o In the Properties window, replace the module's name, Module1 , w ith CrimeAnalysisTasks. Press Enter.

In the other exercises of this chapter. you will add more subroutines to the C rimcAnalysisTasks modulc. You could store every subroutine in irs own module, but since these arc a ll about the s.,me topic, it's logical to store them together.

The event procedures for your UIControls (like the Overview bu tton 's click event) are stored in the 1l1isDocument code module. This means that procedures in one code module (Th isDocument) will be calling procedures from anmher code module (CrimeAnalysisTasks). For thiS to work, the ca lled procedure must be declared Public. C reateOverviewWindow above is already declared Public. Procedures that arc declared Private can only be calk-d by other procedures in the same module.

D Make the Th isOocument code window active .

You are ready to code the click event procedure of the Overview UlBunon.

m In the Overview click event of ThisOocument, add the following line of (ode.

Call CreateOvervieWWindow

The Call statement tells the Create{)verviewWindow subroutine to run .

_ • • _ .. ... _ ..... o_cuun ca. , C ••• ~ro •• o"odo •

. ... 10&1

You could have copied all the code in the C realeOvef" iewWindow subroutine into the click event procedure, dispensing with the Call statement. BUI by keeping the subroutine and the click event st'parare, the cl ick event stays uncluttered.

A nother benefit of keeping the procedures separate is that ~'ou can ca ll C rcatcOvef',jewWindow from procedures other than the click event.

Coffing fI slI/)fTml il/(!

,

:)J:ryngh _ m

I

Page 89: Getting to Know Arc Objects

1

m Close Visual Basic Edit or.

There have been several recent burglaries ncar the Holy Name College. You will t.est the subroutine b~' examining the area around the college.

m Turn the Landmarks and Burglaries layers on.

m Click t he View menu, point to Bookmarks, and click Holy Name College.

Because you're !oom~-d in, it's hard to [ell where in lhe District the colll'ge is located.

-J (

- - -~ L ~ I. '=0000w - -- • --

ED On the Crime Analysis tool bar, cl ick the Overview button.

You Illay have to move or resi"e rhe O verview window to sec ArcMap. In [he Overview window, you see a blue box thm shows you are zoomed in on a northeast sect ion of the Disnict.

To see crimes in other parts of the city, you C:In move or resize the blue box in the Overview window. Any ch:mgcs y OIl make to the blue box a(fect the ArcMap window.

CH" I"TER 6 USING SUBROUTI NES "ND I'U NC710 NS

Page 90: Getting to Know Arc Objects

. .\I.'L (Inn (Jill'

m In the Overview window, d rag the blue box to the eastern corner of the District. as shown.

The ArcMap display pans to the new area. The extem of the blue box in the O verview window always matches the extem of the ArcMap display. When \'OU

make a change 10 one, the other rcacts .

.,.., ..• ,-.... ..... -

·iiI""' .... iii .., ....

r

. --• A •

--

-, . , , In this exercise, you imJX)ned and called a subroutine wriuen by someone else. Programmers do this all the lime to make life easier. Sharing code can be as easy as copying it and calling it. Of course, you'll have to alter the code sometimes, hut as you become more flucnI in VBA and ArcO hjecls, that will gCI easier. You'll do more copying and calling in the following exercises.

GET MORE FREE COOE SAMPL.£S

In Close the overview window.

m If you want to save your work, click the File menu in ArcMap and click Save As. Navigate to C:\ArcObjects\ Chapter06. Rename the f ile my_ex06a.mxd and click Save. If you are continuing with the next exercise, leave ArcMap open. Otherwise close it.

Cal/fllj.l (I SI//JlTJIIIIIU'

I. " '

opyrighl:!d ma I.

Page 91: Getting to Know Arc Objects

Passing values to a subroutine

Sometimes procedures pcrfonn their task without any arguments. In the last exercise, you ca lled the C reatcOvcrviewWindow subrout ine and it opened an Dv('ndcw window. That subroutine has no argumen tS. When called. it runs [he s.'l Il1C way every time.

Arguments pro,.jde information to a procedure so mat it can run with some variation. S uppose you want to creatc a subroutine that prints a map at a page size specified by the user (letter-, legal·, C-, D-, o r E·size paper), When you code the subroutine, you define an argument with a namC' and data type in parentheses. It's like dedarill!:: a variable. but without the Dim keywo rd.

Public Sub PrintMap (aPa geSize As String)

End Sub

When rOll ca ll the PrinrMap subro utine . you musr enter a value for its nrgument. Th is is called passing a value [Q a subro utine. The code bela ..... passes the "Lcttt"r" p.1ge size to the PrintM3P subroutinc.

Cal l Pr i n t Map ( "Lette r" )

A.s the PrintMap subro utine runs, the variable declar\.od in its argumen ts list is set to hold the p.'lSSOO value. Code inside the subroutine can use the variable to respond differcntly according [Q which value is passed. Fo r example, yo ur code might use a Case statement to evaluate the variable and run d ifferent blocks of code .

Public Sub Pr i ntMap (aPageSize As Stri ng ) Selec t Ca s e aPa geS i ze

Ca s e "Letter" Ms gBox "The page S1ze 15 " & aPageSi ze

Ca s e "Legal" Some o the r code runs

End Select End Sub

When PrintMap iscallcd and p.'lS5e<l the Lcncr value , rhc COOl' in its LCHcr C'lSC runs.

T!oo __ .~

r 0< I

CIIAPT£R 6 U SINO SU 8 ROUTINES.ANIl f U NCTIONS

Page 92: Getting to Know Arc Objects

, , r

Exercise 6b Up to now, crime analysts have used the ArcMap graph (001 to make bar charts. However, (0 use the graph tool. an analyst must fi ll out three dialog boxes. They have made a request to speed this process up.

Instead of writing the nelV code yourself, \'OU go to ESRl's ArcObjccLS developer help Web sitc (arcobjectsOnline.esri.com). There you do a search and find a sample subroutine called C rc3tcNcwCh:m , wh ich has code ( 0 make a chart with one but­ton dick. When you get a free sample of code, it probably won't do exacd y what you want . This one's Oaw is that every chart it produces is c"lIed My C hart.

In this exercise. you will import [he CreatcNewehart subroutine and modify it to accept an argument for the chart title. That way. anyone making a chart can give it the name they want. You'll test the new subroutine by making a chart of aoons per precinct.

D Start ArcMap and open ex06b.rnxd in t he C:\ArcObjects\Chapter06 folder.

When the map opens, you see the District layers and the C rime Analysis toolbar.

II On the Crime Analysis toolbar, right-dick the Chart button and cl ick View Source.

In the ThisDocument code module, you see the empty C hart click event procedure. First, you will import the s.'lmple code (or creating chans, then you will tell it to run from this click event .

....... , . . ... _ .... ' .. _C ll .. 11 c • • , c ••• ,_ ....... ,,_ • ..... ....

D In the Project window, right-dick Project (ex06b.mxd) and dick Import file .

The code yOll are going to import was obtained (rom the developer help Web site. Since some people may not have an Inte rnet connection, the sa mple cod e to make chans has been provided with this book's data CD.

D In the Import File dialog box, click the Files of type drop-down arrow and dick All Files. Navigate to C:\ArcObjects\Oata\Samples\ArcObjectsOnl ine and click CreateNewChart.txt. Click Open.

A new standard code module is added to the project. To see it, you will open the Modules fo lder under Project (ex06b.mxd ).

o In the Project window, under Project (ex06b.mxd), click the plus sign next to the M odules folder to open it.

~ ••

Passi/lg ' ·(lhU's /0 (l SlIlm:JII /;II l! ""·:·yrighl:!d ma ,.

Page 93: Getting to Know Arc Objects

o In the Modules folder, double-dick Modulel to open it.

II Highlight the ent ire subroutine from the Public Sub line to the End Sub line. Then right-dick the code and dick Copy.

You wi ll open the Crim~Anal ys isTasks code modul~ so you can past~ the code in i[.

o In the Project window, under Project (ex06b.mxd), under Modules, double-click CrimeAnalysisTasks to open it .

You sec [he sa mple C rcateOverviewWindow subroutine (rom the last exercise.

D With the cursor at the top of the module, above the CreateOverviewWindow subroutine, right-click and click Paste.

I., .a.Dee . ... " • • , .... Dee_., U . a._.k,.., .. ","",.. , ,. ,.,n, ... Tk. h " lob a "," "fTpRQ< . ..... Dee ... ,." .. _,... ,. ".",,,,,.~.,..

·c ...... _ . .. . .. s.t '~<I'C;" " - 110. 'MM." ... , , .. "" ... .. ' ''''' .• " _a!> . . .. , • .,.." •

The C rcaicNewChfHt code is now in the Crim~Ana lysisTasks module. You will edit the subrout ine and add the chart title variable to its arguments list, but before you do. you will remove the module thai was added to ~'our project when you illllXlrted the C reateNewC hart sample code.

m In the Modules folder, under Project (ex06b.mxd), right-click Modulel and click Remove Module1. Click No on the dialog that asks if you want to export the module.

m In the CrimeAnalysisTasks module, inside the CreateNewChart subroutine's arguments list (between the parentheses), type strTitle As String. This declares a str ing variable for the chart title.

Public Sub CreateNeWChar t(strTitle As String )

Next you will find nnd edit the line of code thai setS the chnrt's Title property. You will replace M~' C hart with the sunde variable.

m Scroll down in the CreateNewChart subroutine and locate the following line.

pDataGraphProperties.Title : · My Chart -

C"AI'TER 6 USINO SUI.lRottrll'O'M ..... NU P1JNC'nONS

Page 94: Getting to Know Arc Objects

~ll'CII111 (1)1L'

m In that line. change " My Chart" to strTitle.

pDataGr aphProperties. Title = strTitle

Make sure lO usc only the variable name and no quotes. Now when any procl"<iurc calls C reatcNe"-C hart and passes it a text string, the subroutine will sto re thai string in the strTidc variable and use it to set the chart 's Title property.

m Make the ThisDocument code window active.

m In the Chart click event procedure. add the following two lines of code to declare a string variable and use an Input Box to get a chart title from the user.

Dim userTitle As St r ing userTitle = !nputBox ('Ente r a char t t i tle ' )

II] In the click event. add one more l ine of code to call the CreateNewChart subroutine and pass it the user's title.

Call CreateNewChart(userTitle)

.,,""'" I'*' C .... " _C HU Il ... .... n<l. u I", ... ...... " .. ' ......... ·1··· .. · .. """. ,,<I • • , COl' c ....... .n.u.'_.T' ... '

The code is now ready to test.

m Close the Visual Basic Editor window.

m In the ArcMap table of contents, click the Precincts layer to select it.

-• • c_ , .c_ • Ii '" (I,,. 7

0 ... , .. • Ii! I:IC_ a 0 __

-. •

PassltlM {,flluC's to {l SUI)lT)lItine yrl hl~m n

Page 95: Getting to Know Arc Objects

TIle C re1ltcNewC hart code runs 011 the .selected layer.

m On the Crime Analysis toolbar. click the Chart button.

m In the dialog box. type Arsons in 2002 .

......... 1001

m Click OK.

The C re:l teNewC hart subroutine uses the selected layer's amibute rable to make the c hart. The ch[lrt \'[lhICS, sho wing the number o f arsons, a re mken fro m the fi rst numeric field in the table. The chart labels, identifying the precincts, arc taken from the fi rs t string field in the table.

The ch1m shows the number of arson cases bv prec incL PrecillCt 4 (the red bar) has twenty cases and Precinct 6 has none. If it had [lny. yo u would sec a yello w bar.

Arsons in 2002

Arsons w. Precinct

m Close the chart.

m If you want to save your work, click the File menu in ArcMap and click Save As. Navigate to C:\ArcObject s\Chapt er06. Rename the file my_ex06b.mxd and click Save. If you are continuing with the next exercise, leave ArcMap open. Otherwise close it.

Page 96: Getting to Know Arc Objects

Making several calls to a single subroutine

Sometimes you design a user interface with two controls thai do the same thing. ArcMap, (or example, has the Layout Vicw menu choice on the Vicw menu and the Ul~'out View minibunon in the lower left comer of the map display. Both switch the vicw [Q Layo ut Vicw.

Since thc~' do the s..,mc thing, you don't have to write the same code twice. You can write a single "Switch to Layout View" subroutine and call it from the event proce­dures of the twO controls.

••

Exercise 6c:

-­I .. -:iii , ..... , .. . --g .... ..---Ill' 5 ,

Switdl '.l~'"

.... ",

Arsonists commonly don't stop with sctting just one fire , and , oddly enough, they don't generally go very far afield . So the people who anah'ze arsons typically smn by drawing buffer !Oncs to sec if there arc similar arsons ncar each other.

Insl'cad of writing the code yo urself, a search of the developer help yields a sample subroutine called BufferFeatures. It buffers each selected feature in the focus map and stores the results as polygons.

In this exercise, you will import Ihe subrouline into Visual Basic Edilor and call it from three different bunons. O nce again , you will modify the code to accept an argument. This time, each button will pass a d ifferent buffe r va lue: 500. I ,0Cl0. o r 1.500 meters .

. 11f1kiIlR Si..'Ir!rtll calls /cJ fI siIlN!(> slIbro/llfll(>

, ..

ghl~ m n

Page 97: Getting to Know Arc Objects

, ,

D Start ArcMap and open ex06c.mxd in the C:\ArcObjecu\Chapter06 folder.

When {he m;lp opens. you sec the Disn ict \<lYcrs and the C rime Analysis lOolbar. The Arsons l a~'c r is turned on.

D On the Crime Analysis tool bar, right-click the 500 button and dick View Source.

In the ThisDocumem code modu le. you sec the empty Buf(cr500 click ('vent procedure. After importing and copying the procedu re fo r dr:.lwing buffers, you will call it fro m this dick event.

U In the Project window. right-click Project (ex06c.mxd) and click Import file ,

The code you arc gOill g [0 import was obtained (rom the ArcObjects developer help. Since some people using this i:xxJk may nor have rhis help system installL-d on their computer. the sample code to buffer selected fearures has been provided with this book's data CD.

11 In the Import Fite dialog box. click the Files of type drop-down arrow and click All Files. Navigate to C:\ArcObjects\Oata\Samples\ArcObjectsDeveloperHelp and click BufferFeatures.txt. (lick Open.

A new code module is added 10 the project . To sec it . you will open Ihe Modules folder under Project (ex06c .lUxd) .

D In the Project window, under Project (ex06c.mxd), click the plus sign next to the Modules folder to open it .

o In the Modules folder, double-click Module1 to open it .

o Highlight the entire subroutine from the Public Sub line to the End Sub line. Then right-click on the code and click Copy.

You will open the C rimcAnalysisTasks code modu le, so rou Clm paste the code in it.

D In the Project window, under Project (ex06b.mxd). under Modules. double-click CrimeAnalysisTasks to open it .

You sec the subrout ines from the previous exercises.

C HAI'TIlR 6 USING SUBROUTINES ANI) FUNCTIONS

Page 98: Getting to Know Arc Objects

o With t he cursor a t t he to p o f the CrimeAna lysisTasks mod u le. a bove the Create NewCha rt subro utine . right-click and click Paste.

, .. h e , .. . d ... ' .... ..-... ,o<.h ........ _ .. . ... 0\1', ' .... . ,..- .. ,,..- _ .. ~ ... . k ..... n •• u U .. , .... v ••• ~ ... ,o.-..... ~ • • •• • _. u ,a. ... . . oe.. ... . ... . ... , 1 • ..r...... .. I l • ..r ..... . . ... • , . ...... .. 11 ..... . . ... • ? o _ ... . ..... . _ .... , _ • • • • • .... • 11_ •• u IU_ • • . ... • • •• R< . . .... ........ .... _

.... ... _ . .. "u ....... _ _ ...

... . ........ V, .. . . .. _ . , _ ...

... ,o.-. .... oe..OL • • _ • • • a .. _. ' .........

. .... I • • 'oo' ''' ' .. ' ",," 0 0

The fi rst line of the subroutine has an empty arguments list. You will add an argument to allow the passing of a buffer distance. The 500, 1000 , and 1500 buttons on the C rime An alysis toolbar will each call this subroutine and pass it different distance values.

Befo re you adjust the code lO su it your needs, you will remove the module th at was addl'Cl to your project when you imported the BufferFeatures sample code.

m In t he Mo d ules fol der, u nder Project (e x06c.mxd ), righHlick Module1 a nd cl ick Remove Mo dule l . Click No on t he d ialog t hat a sks if you want to expo rt the module .

m Insi de the arg ument list o f the Buffe rFeatures sub rout ine (between t he parent heses), type s t rBuffe rDista nce As String . Th is d eclares a string va riable to hold the b uffer d ista nce.

Public Sub BufferFea tures(s trBuff e r Dis t a nce As String)

Recall that the chart title argument from the last exercise g<lVe the user more freed om: here, your buffer d istance argument will be used to restr ict their freedom. Instead o f giv ing the user an input box to em er a d istance, rour cooe will pass one of three predefi ned values.

By the way, it may seem odd to work with d istance as a string, but the existing code is written to expect a su ing. You could ch an ge it so that it expects a number, but leaving it as a str in g is easier and will get the job done just as well.

You have to make o ne other ch ange. The BufferFearures subroutine already h as two lines of code that dec lare and set a buffer distance variable. S ince you have put your own buffer d istance , 'ariable in the argumen tS list, yo u will find and delete these two (non adjacent) lines of code that arc no longer m.'Cdcd .

.llaking S(J/.'('m/ r:(lIL.~ 10 tl sl1lgle $lIbrolllllW

,

! I •

o yrl hl~m n

Page 99: Getting to Know Arc Objects

''Xt,: I

m At the top of the subrout ine. locate the following l ine of code.

Dim s trBufferDis tance As String

......... v... ::~ o<)<~ .. e.CO." 'M' » .. . Ia_ •• < .... .... 11_ . . . ...

, .., .,. . .... ... Ir •• <._ » ... . To ...... ... ITo ... . ...... ' .......... , ... . 1 1_ ....... 111_ ••

' ... . . .. . ... . 11 • • _ .. ' u .... M . ... .0"" . .... "eo"o •. _ _ •• M . ......... VI ...... _.r ....... . $0. oO<."Ueoo;o ....... . , ....... . .... ,.. ....

'VU", . .. . ........ "' ••• Iocc .o.

This is the line that declares a buffer distance variable.

m Delete the line of code.

m Scroll down in the subroutine and locate the following line of code.

s trBuffe r Di s tance : InputBox ( "Enter Di s tance ; " , "Buffer ")

...... _ • _"" •• ,,0.. _ _ ..

... , ..... wv ....... _.r ......... . ,,'" oO< o •• • e.co.c. , .. < . . .. _ .r"" ... ..." ''10' ''' ...... .. . .......... '..,"0. If ....... . ...... ...". 101 .., .. 0...:0 .... ' • 0 n... 0. .. I .

This is the line where the user setS a buffer distance. In your code, the buffer distance will be ptlSSt.>d in from other procedures,

II) Delete this line of code. too.

m Make the ThisDocument code window act ive.

CHAPTER 6 U!H~r: SUkROUT1Nts AND " U NCT10 NS

Page 100: Getting to Know Arc Objects

. . 'i('ll/(JH /flll'

Next you will go ro the cl ick events of the three buffer buttons and add a line of code that calls the BufferFeatures subrout ine. '

m In the ThisOocument module. add the following line of code to the Buffer500 click event to call the BufferFeatures subroutine and pass it 500 as a text string .

Call Buf f erFea tures(-SOO &)

P ....... I ... c .... _cu n n ... ..... Tnl .... t .... .. ..... T .. 10 • 1o . . .... I·r •••• • ¢ ........ "." '

II] At the top left of the ThisDocument (ode window, click the object list drop-down arrow and click Buffer ' 000. In the Bufferl 000 click event, add the following line of code to call the BufferFeatures subroutine and pass it 1000.

Call Buffer Features("lOOO"j

m Click the object list drop-down arrow and click Buffer' SO~ . In the Butfer1500 click event, add the following line of code to call the BufferFeatures subroutine and pass it 1 SOO.

Call Buffe r Fea tures( -1500-)

Em (lose Visual Basic Editor.

In the past year, many arsons have occurred near Howard University. You will use the buffer buttons to ana ly!c them.

ED In ArcMap, click the View menu, point to Bookmarks, and click Howard University to zoom to it.

You will select the universi ty and buffer it.

m If your Tools tool bar is turned off, turn it on now.

:\faking sc!L'('ral c(I/1s to 1I single sl/brom/III!

, •

,a'

Page 101: Getting to Know Arc Objects

\

m On the Tools toolbar, click Select Features. Then click on Howard University (the long yellow feature) to select it.

--_ ... _--~ "" ... _ :10 -_ ... "g. " • , ,

• 0_

" " J • • --, 0_ , • - • ,

• Ii!! (>: •• , •

·mLo' .. ..... . I .. .. -.-- • • Ii! • = ... • • - • , , , , , •

• • • • • , •

~..!l I . _. • • • il'" O!J 1'~ ""

, • , " . , . d. ' • • -

m On the Crime Analysistoolbar, dick the 1500 button. Click the 1000 button. Click the 500 button.

The buffe r zones dmw in blue. In later chapters. you will write code to control the symbols ~nd colors used for drawing. For now, yOli wi ll select the thrcc buffer graphics and change their symbology manually.

m Click the Edit menu and dick Select All Elements.

m Right-click inside any buHer zone and dick Properties. In the Common Properties for Selected Elements dialog box, click Change Symbol.

m Scroll to the bottom of the Symbol Selector and double-click the symbol called Crime Reporting Sector. Click OK on the Common Properties dialog box.

Scvcml arsons havc occurred within each buffer mnc around ,he un iversi tr.

CIIAPTER 6 USINC SUHH.OUTINE' "HI) "tJ"'~NS

Page 102: Getting to Know Arc Objects

• . '\l'Ctlll71 (JJll'

._.- ................. Q rUiHi

•• • 0_. ,

D ~_ -B Ii!. g,.

• Iii'! ... • .. -B i'l _ _

Iii'! ....... -It'_ O _ ,::;j O ' A'

, •

• " •

• , •• • • • • • •

ED If you want to save your work, dick the File menu in ArcMap and cl ick Save As. Navigate to C:\ArcObjects\Chapter06. Rename the file my_ex06c.mxd and (lick Save. If you are cont inuing with the next exercise. leave ArcMap open. Otherwise close it .

.lit/killS 5e1'i!ml c(l/L~ 10 (I sillg le SUb rollt i ll('

, ,

ial

Page 103: Getting to Know Arc Objects

• •

• ,

,

, •

I ,

Returning values with functions ----~~---------------------... ----

• • •

In the previous exercises in this chapter, you called subrouTines and passed values to them with arguments. Functions work similarly, except that (as mentioned :1( the start of the chapter) a function returns a value. To be more specifi c. a function returns a value to the 5o'lffie line of code th tl t calls it. You'll sec how this works in a moment.

A function is like a calculalOr. You push buttons on a calculator 10 pass va lues to it, such as 1 and 2, and to define an operat ion, such as addition . The calculalOr then docs some arithmetic. and returns a new value (with any luck. it will be 3) . When you call a (unction, you pass it a value with a line of code. it carries out some opera­tion on that value, and it passes a new , ·aluc back.

You have already worked with a couplc of VBA (unc tions: MsgBox and Input Box. The line of code below ca lls the InputBox funct ion. You pass the InputBox function a text string inside its parentheses. The suing d isplays in a dialog box that prompts the user to type in a value. Once a value is entered, it is passed back out of the Input Box (unction and assigned to the strValue variable.

strValue = InputBox ( "Enter a Parcel Value" )

This line of code ca lls the (unction and passes it a value (to the right of the t.'<jua ls sign ), and it receivt.'S a new value b.1ck from the function and holds it in a variable (10 the left of the equals sign ).

The code behind VBA's built-in functions is hidden from you. When ~'ou make your own funct ion , you have to write the code yourself (or steal it ).

Suppose you want 10 make a function that converts kilomcters to miles. The function will rece ive an input value in kilometers, do some :u ithmetic, and pass back the equivalent in miles. To code a funct ion, you stan with its wrapper lines:

Publ ic Funct ion Ki lomet ersToMiles (km As Doubl e ) ~ Double

End Func t ion

The fi rst line inc ludes the name of the function ( Kilometers ToMiles); an argument dt.'Claring a variable and data type for the input value (km As Double ); and the As keyword fo llowed by a data type for the returned value (As Double, shown he re in boldface) .

Although they are of the same data type herc, the input value and the returned value do not have to be. Say you were creating a function to calculate somcone's age b.'lSCd on the date they were born. The input value might be of the data type Date and the return value might be of the data type Integer.

Public Function Age I nYears (age As Date) As I n tege r

End Func tio n

CHAPTER 6 USI NG SUM II.OUTINI'.5 ANIl FUNCTIONS

Page 104: Getting to Know Arc Objects

I (11lL'

To complete the code (or the KiiomerersToMiles (unction, you need a conversion (onnula to change kilometcrs into miles (lldlomefcr equals 0.62 137 1 miles) and you need to pass the new value out o( the function and back to the line that ca lled it. You can do all that with one line of code.

To pass a value out o( a (unction , you use the (unction's name like a variable. The line of code below sets Kilometers ToMiles equal to [he miles equivalent of kilometers.

Public Function KilometersToMiles (kID As Doublel As Double KilometersToMi1es : kID • 0.621371

End Function

Setting KilometersToMiles as if it were a variable allows the line of code that calls the function to receive the returned value.

When you call func tions you don 't usc the Call keyword as you do with subroutines. Instead, you typicall\' use two lines of code. The first declares a variable to ho ld the ,'alue that the function will rerum. The second sets this variable equal to the func­tion name and passes a value into the function (1 0 in the example below). The st."Cond line is the one that actually calls the (unction. In the example below, the variable's data type is Double because the function's return value is a Double.

Dim x As Double x = Kilomete r s ToMi1es (10)

The followlllg diagram illustrates the process. The function is coded in the ConversionTasks modu le and called from the ThisOocul11cnr module, where the value lOis passed into it. In the function, this input value is SlOred in the km variable and converted to 6.2 137 1 miles. Then Kilometers ToMiles is set equal to 6.2 137 1, which causes the " alue to be passed out of the function back to the line of codc that called the function. There the returned value is set equal to the variable x. When all is said and done, x ho lds the value 6.21371.

~Ze~".·~~,,,", .. .,..,~, from tM function 10 th~ Uliling li~

of code

A ~alue Is pa~ from 1M Uliling Ii code 101M funct ion

Declari ng and setting a variable isn't the only way to handle a functio n 's returned value. Since a function returns a value, the function can be used anywhere that that value is accepted. Fo r example, mess.'1ge boxes display a value, so you can use the

,

Re/ll nI ;"8 l'lIIIl(,S u'llll filllelfolls "-';/ighl:!d ma I.

" • •

Page 105: Getting to Know Arc Objects

KilomctcrsToMiles (unction as a mCSs.:lge box's first :lrgument as shown on the line below.

MsgBox KilometersToMiles (10)

Exercise 6d During the c rime analysis meetings, the group reviews recem drug busts. TIle amount of drugs confiscated is typically reported in kilograms, and someone always asks, "How much is that in pounds!"

In this exercise, ~'ou will make a (unclion to convert kilograms to pounds. You will call rhe func tion fro m a button on the C rime Analysis toolbar. O nce the (unction is wrincn, you will be lIble to call it from any o ther procedures that havc a use fo r it.

o Start ArcMap and open ex06d .mxd in the C:\ArcObjects\Chapter{)6 folder.

When the map opens, you sec the fllm iliar District layers rmd the C rime Analysis toolbar.

o Click the Tools menu, point to Macros, and dick Visual Basic Editor.

o In the Project window, expand Project (ex06d .mxd) and expand the Modules folder underneath it. Double-click CrimeAnalysisTasKs to open the code module.

In the C rimeAnalysisTasks module. you see the mher subroutines that you have worked with in this chapter.

II With the CrimeAnalysisTasks module active, click the Insert menu and click Procedure.

o In the Add Procedure dialog box, type KilogramToPound as the name. For the type. click Function. Leave the scope set to Public.

. "

-r II ..... ,. It .. _

D Click OK.

to. I -I

The new function is added to the bottom of the CrimeAnal~'s isT.'15ks module. You'll define its arguments and returned value data type in the nex t two Sfeps.

Ctli\PTEM 6 USING SU8ROUTINES Ar-:r) fUNC"TI(lN~

Page 106: Getting to Know Arc Objects

.... ,-' ... o In the function's arguments list (between the parentheses), type dblKilos As

Double.

This defines a variable to ho ld the value that is passed in to the function and specifi es its dam type as Double.

Public Function Kilogr amToPound(dblKilos As Double)

D Define the data type of the function's returned value by typing As Double after the function 's arguments list.

Public Function KilogramToPound (dblKilos As Doublel As Double

Next rou will code me conversion formula. There are 2.2046 pounds to a kilogram, so the formula is pounds· kilograms· 2.2046.

D Inside the function, set t he function name equal to the formula to (onvert kilograms to pounds.

KilogramToPound : dblKilos • 2.2046

dblKilos holds the kilograms value that is passed into the {unction. This value is converted into pounds by multiplying it by 2.2046. To return a value from the func­tio n to the line of code that called it, you set the function 's name equal to a value. Here it's the formula's resul t value.

_'"~ '_ ,o. ." ... _ ... '(.'" ...... _ ,., .. 1 ..... _.... , - .,." .. . ...... .

,

The function is now complete. All that remains is to code the KilosToPounds button's click event procedure to call the function and pass it a value.

1m Make the ArcMap application window active. On the Crime Analysis toolbar. right-click KilosToPounds and click View Source.

You will use an inpurBox to get a kilogram value from [he user. Whatever value the user types into the InputBox is the value that will be passed to the KilogrnmToPound func­tion. Since this value is nor prl'detemlined, you will declare and set a variable for it.

ReIn nt jl/g I'(Iltli'!i Uti//) JIII/clfo/I.~

• x • "

n hl~m nal

Page 107: Getting to Know Arc Objects

m Inside the KilosToPounds click event, declare a va riable for t he user's kilog ram value and set it usi ng t he Inpu tBox function.

Dim user Kilos As Doubl e userK i l os ; Inputbox ( "Enter t he numbe r o f kilogr ams-)

You are ready to call the KilogmmToPound function. This includes declaring a variable to hold the function's returned value.

m Decla re a variable f or t he KilogramToPound function's returned value and set it by ca ll ing t he Kilog ramToPound funct ion.

Di m user Pounds As Double us e r Pounds = Kil oq r amToPound (user Kil os )

m Add a final line of code that uses a message box to report the converted value.

MsgBox us erKi l os & - ki lograms i s • & use rPounds & • pounds·

........ _, " .. ,-~.--" ....

~ ....... ............... PO'*I • .... , ... _ • • ,' _ _ To· ...... C_.~ I ' ... 1

" Ok ...... u le. < • U J __ •• • • _

.... .. -I •

.... Of . . ......... ......... .

TI,e button and .he function arc read~' to test.

m Close Visual Basic Editor.

m On the Crime Analysis tool bar, click the KilosToPounds button.

£] In the input dialog box, type 14 and click OK.

You sec a message box that shows the kilogmm value compared to the pound value.

=- . 1·_-.... --o;w I

OJ Click OK on the message.

m If you want to save your work, click the File menu in ArcMap and click Save As. Navigate to C:\ArcObjects\Chapter06. Rename the f ile my_ex06d .mxd and click Save. If you are cont inuing w ith t he neKt chapter, leave ArcMap open. Otherwise close it .

CH ArTER 6 USINO SU8ROUTINES "NO FUNCTIONS

Page 108: Getting to Know Arc Objects

Looping your code Coding" For 100/1

Coding a Do 10011

In VBA programming, tasks can be run repeatedly with looping statements. Loops can be as simple as "Print ten copies of the same map," or as complex as "For each vacant parcel in the city, get its acreage, add that (Q a running sum, and repan the toral acreage of vacant land." VBA has two kinds of looping statements: For loops and Do loops. For loops run a given number of times and Do loops run until the value of a logical expression changes.

You arc going to make lunch fo r yourself and tWO friends. All three of you will have a peamn butter and jclly sandwich. To make the sandwiches. you repeat the follow­ing process three times: get two slices of bread, spread pcanul butter on one, spread jelly on. the other, slap them together, cut them in h3lf, and put them on a plate for serving.

The sandwich loop above is a For loop. You are making one s.·mdwich for each person, and so the loop runs a specified number of times. When everyone has a s.'1ndwich , (he loop ends (and the eating subroutine begins).

A Do loop evaluat.es a logical expression and then decides whether to run its block of code. A Do loop will run its code until the expression's true or false status changes.

You arc so good at making peanut butter and jelly sandwiches that now iI's ~'our job to make them from 8 to 5. When the expression "time> 5:00 P.M." changes from false to true, your sandwich-making stops for the day. So every time you fin ish a sand­wich, you look up at the d ock [ 0 check the time. If it's not yet five o'clock, you have to make another s.'lndwich. If it's fi ve, you get to stop.

ighted material

Page 109: Getting to Know Arc Objects

Coding a For loop

TIle mechanics of a For loop arc simple. You set a \'ariable equal to a stan value. like 1. Each time \'our block of code runs. the variable value increments by 1 umil it reaches an end value , like 10.

A For loop begins with the For keyword and ends with the Next keyword. The For kt!~'word on the first line is fo llowed by the variable and its srart ;md end values. The block of code bt>tween this lin .... and the Next k .... yword runs repeatedl}, until the vari­able exceeds the end value.

Fo r variable = Start Value To EndValue Block of code here

Nex t

The For loop below would print a map ten times. The first time through the loop. {he vadabll' x is set equal to 1 (the srart valul') and the block of code rullS to prim the firs t map. The second time through the loop. x is set equal ro 2 and a second map prints. The third time. x changl's to J and a th ird map prints. Thl' loop stops nmning after the tlmth map is primed.

FOI" X "" 1 to 10 ' Code here to p rint map MsgBox ·Printing Map • & x

Next

It is common to begin with 1 and end with the number of times that you need the loop ro run: however, you can use any start ing and ending values you like.

If your loop is processing a list of items, you can also skip ovcr iTcms using the StCP keyword. Suppose you have a database of 10,000 customers and }'ou on ly have enough money to mail a coupon to 5 percent of them. Your oldest customer is customer 1 and your newest is customer 10,000. You want the coupons to go to a mixture of new and old customers.

The loop below is designed to go ro every twentieth record starring with record \. For cvcry twCmiefh record. rh .... customer's address is printed on a mailing label.

For x ; 1 t o 10000 Step 20

Next

'in the customer table go to record x ' get address f or x ' prin t a mail ing label

LO(lping statements are also useful for populming lists, like those in combo boxes. TI,e only wa~' to add valucs to a combo box is with fh .... Combo&x's Addltcm method. Suppose you wanted to make a combo box in which the user can choose a number from on .... to ten .

CII APTER 7 looPING ,·OUR COUll

Page 110: Getting to Know Arc Objects

. S 1..' l" r I () n () n (!

"'-'-- ;:;;;;~ , • , • • •

To put the numbers one through len in the combo box, you could write ten lines of code with the Addltcm method.

cboFavoriteNumber.Addltem 1 cboFavoriteNumber.Add.ltem 2 cboFavoriteNumber.Addltem 3 cboFavo riteNumber.Addltem 4 cboFavoriteNumber.Addltem 5 cboFavoriteNumber . Addltem 6 cbaFavoriteNumber.Addl t em 7 c boFavoriteNumber.Addltem 8 c boFavo riteNumber.Addltem 9 c boFavoriteNumber.Addltem 10

Lucki ly. there's a faster way- you can write a For loop and reduce those tcn lines of code to three. The loop below increments from 1 to 10, addi ng those values to the combo box's list.

Fo r x '" 1 t o 10 c boFavoriteNumber.Addltem x

Next

ExercIse 7a As a GIS programmer for the U .S. Census Bureau, you are developing an application to help people view county-level population trends. Your application will display population values for each census year from 1930 to 2000. When a user chooses a year, and picks a number of population classes for rhe legend, a map is creatoo.

The Quit and MakeMap buttons on the dialog box below arc already coded; the two combo boxes, however, are not. In this exercise, ~'ou will code two For loops to add values to the combo boxes. The box called cboYears will com .. '1in a list of the census decades from 1930 to 2000. The box called cboClasscs will contain a list of numbers that sets the number of population classes in the legend.

<--..0--_.c-_ I

-.--- I :OJ -----t- (boYU" :OJ ----+-,""""'"

It: ,... I

C()(lIl1g (I Por loo/J

,.

Ighl:!d ma I<

Page 111: Getting to Know Arc Objects

,

,

'\ " , .

,

l~nd with J d .\.W$

8 ~ I_ e Iii!! c.. 5

,m 0 0·_ _ _ ·,,,.., ,0 . ,11 .. ,0 · :M;;I IZl

ltgt'nd with 5 d"l~ .oo-•• ~~~'=-" ,m 0 0.71135 II:I IIlJS ·:snu . ;sm: . .,.". . ""'".. -u ... ,g . "11""0 ·:M;!,D

D Start ArcMap and open ex07a.mxd in the C;\ArcObjects\Chapter07 folder.

When the map opens, you sec a layer of U.S. counties. On the Standard toolbar, to the right of the Add Data bunon, is a button called CensusMaps.

D Click the CensusMaps button.

On the Census Population Maps dialog box, you see the cboYears and cboClasses combo boxes. If you clicked their drop-down arrows, you would sec that both are empty. You wi ll write two loops to fill these combo boxes with values.

D Click Quit to dose the dialog box.

D Click the Tools menu, point to Macros, and click Visual Basic Editor.

D In the Project window, under Project (ex07a.mxd), under Forms, double-dick frmCensus to open it.

Befo re writing any code. you will make a property sening fo r the twO combo boxes [0

help eliminate user typing errors.

-~ .. o-oc.-_ ;::1 ==;"' ----,-----0-0_"_ '1--"" ____ _ cboCluws

8 ' ''' I I

D On the form, dick the combo box cboYears to select it. In the Properties wi ndow, set its Style property to 2-fmStyleDropDown list.

This option forces the user to pick a decade from the drop·down list. Otherwise, they could (ype in any value (he~' liked . Since you only ha\'e data for the census years between 1930 and 2000, you don't want the user to type in a number (like 198 1 o r 1920) that will cause an erro r.

CUAI"'l'ER 7 LooPINO YOUR COllE

Page 112: Getting to Know Arc Objects

SL'ctl()ll ,IHe

Next, you will set the same Style property for cboClasses to keep users from making maps with fewer than three or more than e ight classes. h 1" I

D On the form, dick the combo box cboClasses to select it. In the Properties window, set its Style property to 2-fmStyleDropDownlisl .

Now you will write the cexle for the looping statemems.

D At the top of the Project window, click the View Code button.

The frmCensus cexle mexlule becomes act ive. It has cexle in it for the MakeMap and Quit bunons. The Quit bunon's click event has code ro close the fonn. The M<l keMap bunon's click event h<ls code to ca ll the RenderMap subrouti ne.

The RenderMap code uSt.'S the selected combo box values to get census data from the Coumies layer attribute table and create a legend for h . You'll learn to write this type of code using ArcObjects later in the book.

D In the object list, click the drop-down arrow and click UserForm (unless it is already selected). In the procedures list. click the drop-down arrow and click Initialize.

Since the initialize event runs JUSt before the fonn opens to the user, this is where you will add the two loops to fi ll the combo boxes with years and numbers.

II:) In the initial ize event, declare the For loop's variable as an integer.

As the loop runs, this variable will ch<lnge its , ·alue for each imeger in the range between (he start and cnd value. You'll set up that range in the next step.

Dim intClass As Integer

• •

• •

C()(Ii'I~ fI For loop opyrighl:!d ma ,.

Page 113: Getting to Know Arc Objects

m Add the following For loop. Use 3 and 8 for the start and end values.

A legend with fewer than three classes doesn't convey much information, and a legend with more than eight is hard to interpret. Visually, the shades of a color start to look alike, and conccptuall~', the distinctions betwcen classcs becomc less mcanin~.'fu l .

For i n tClass = 3 To 8

Next

Whcn a lIscr clicks 3 in cboClasscs, a legcnd with thrcc classes will be created , like the one below.

m Inside the loop, add the following line that uses the Addltem method on the (ambo box to add the numbers from three to eight.

cboclasses . AddItem intClass

This line of code will run six times, adding the numbers J, 4, ; , 6. 7. and 8 as choices to (hc combo box's drop-down list.

'u"". ~ ... tIO .. ' o"'.'a .... , ... n D ... , •• CIo ..... , ....... ,

, •• , • • C .... - ......

k .. .... .....

Now you will codc a sccond For loop to add census dccadcs to the cho Years drop­down l iS!.

m After the code for the first loop, declare an integer variable to hold the For loop numbers for each year.

Dim intYear AS Integer

Page 114: Getting to Know Arc Objects

.. l' l' f / ( 11 (I n c:

m Add the second For loop. Use 1930 and 2000 for the start and end values and make it step every 10 years.

For i n tYear = 1930 To 2000 St ep 10

Next

m Inside the loop, add the following line that uses the Addltem method on the combo box to add the year for each decade.

cboYears. Addltem i ntYear

This line of code will run eight times because there are eight census years from 1930 to 2000. Each year wi ll be added to the combo box's drop-down list.

So far. when the dialog box opens. the combo boxes arc empty until the user clicks the d rop-down arrow to make a selection. You will set a property fo r the combo boxes so they have initial values.

' 0 . , .... ... . ",0 ." .to! I .. , 10 _,. ..... _.<_ .. U.u

11 .. < .... "-

m After the two loops, add the following two lines of code to set the default values for each combo box.

You will set the number of classes to J and the year to 2(X)(). Users can accept these defuul ts or usc the drop-down lim (0 change them.

cboClasses.Va lue = 3 cbovears . Value = 2000

The code is ready to test.

m Close Visual Basic Editor.

m Click the Census Maps button .

The Census Population Maps dialog box opens with initial values in each combo box.

m Set the year to 1930 and number of classes to 7.

m Click MakeMap. Move the dialog box so you can see the map.

CadillS (/ For fOOl)

,

, , 1 '. • "

,- yrighl:!d ma I

Page 115: Getting to Know Arc Objects

\C"/\O

I •

Many western counties arc yellow, which means they arc in the lowest population category for 1930. Next you will look at the populations for 2000.

m Change the year to 2000 while leaving the number of classes set to 7.

m Click Make Map_

More western counties arc now red and more midwestern counties arc yellow. Maybe there was a migration from the midwest to the west. For a more specific analysis, you could zoom in to a specific state and compare population values for different decades.

In the next exercise, you will work with a combo box that docs jllst [hm. You will populate the combo box with a list of Slate names and, when (he user picks a stale, the vicw will zoom to it.

m Click Quit.

m If you want to save your work. click the File menu in ArcMap and dick Save As. Navigate to C:\ArcObjects\Chapter07. Rename the file my-ex07a.mxd and click Save. If you are continuing with the next exercise, leave ArcMap open. Otherwise close it .

(:HAI"rER 7 Lool'lNG YOUR conE

Page 116: Getting to Know Arc Objects

· sectltln

Coding a Do loop

Do loops come in two types: Whi le and Until . Do While loops run while a logic-'ll expression is truei Do U ntil loops run Imril a logical expression is [rue (which amounts to running while an exprcMion is fal se).

Do Loops begin with the 00 keyword and end with the loop keyword. On the first linc, the Do keyword is followed by either While or Until and a logical expression. These logical expressions arc just like the ones you learned about with If Then statements.

Do While EXpression 'Code here runs a s long as the expr ession is true

Loop

Do Until EXpr ession 'Code here runs a s long as the expression ~s false

Loop

The Do While loop below uses a vhYesNo message box in its expression. MsgBox is a VBA fu nction; when used with the vbYcsN o aryument, it offers a cho ice of some kind and presents the uscr with two buttons. Depending on which button the user clicks, the function returns the value vbYes or vbNo.

-~-1 ,.. 1 No

Thc following expression checks to see if the value rcturned by the MsgBox function is equal to vb Yes. If it is, the expression is true and the loop's block of code runs.

Do While Msgbox ( "Print the map?", vbYesNoJ = vbYes 'Code here to print map MsgBox "Printing Map"

Loop

In the previous exercise, you created For loops to add lists of numbers to combo boxes. For loops arc good at building lists of this kind, but what if you want to build a list of words, such as a variety of color choices a user can pick for a legend 1

To add color names to a combo box. you would have to use the Addltem method for each color. So to put fi ve colors in a drop-down list, roo would use Addltem fi ve times.

cboColor.Addltem "Red" cboColor.Addltem "Green" cboColor_ Addltem "Blue" cboColor.Addltem "Gray" cboColor.Addltem "Purple"

() n e

Coding (I Do loop ial

Page 117: Getting to Know Arc Objects

With fi ve colo rs, th is isn't a problem. But what if yo u w,lOtcd to bui ld a combo box list o f o ne hundred colo rs ! You could type in one hundred Addhem lines of code, but thaI would take a while.

A better way is to access a text file that has all the color namcs in it. You could then write a Do loop to read rhe text file, get the names from it , and add them to a combo box.

The process for rending values from a rext fi le goes like this:

open the fi le check to see if there is a line i n the file read the line, do something with it r epeat these two steps un til the end of the file

close the file

let's analyzc this process in detail. To open a fil e, you use VBA's Open function, which has fi ve arguments:

Open "c: \ names . txt" For Inpu t As '1

The fi rst argument is a string with a path 10 the file. The second argument is the For keyword . The th ird argument is ano ther keyword: e ither Input, Output, or Append . (input is lIS<.-d to read a file . O utput to write values to a new file , and Append to add lines to an eXisting file.)

The fourth argument is the As ke~'word . The fifth argument ( ... ) is a fi le number you assign. In an~' given session , your code may read informatio n (rom many different fi les, so you need a simple way to tel l them ;Ipart .

When ~'our loop is do ne re<lding v<llues, you usc the C lose function to d ose the file . The C lose functio n has <ln argument 10 specify which fil e to close.

Close n

Howdo you know when ~'our loop has read all the values1 You usc the VBA functio n called End of File (EO F) . EO F returns True when the end of a fil e is reached and False as long as there arc more lines to read. Because it returns True or False, it can be uSt.-d as the Do loop's expressio n.

In the e xample below, [he Do U nrilloop applies the EO F (unction [ 0 file num1x>r I. The loop runs as lo ng as EO F is false:. When the last line has been read, the EO F function returns True and the loop ends.

Do Until EOF (1) 'Rea d lines from t he file

Loop

Inside the loop, you use the Input statement to read the fil e. Input has [wo arb'tunents. the file number and a variable. As each line is read . its conte n ts arc put into the va riable (strNa me, in Ihis e xample).

CHAPTER 7 looPING " OUR COll I!

Page 118: Getting to Know Arc Objects

'Ll£/"ri ~li)L

Input .1 strName

Suppose the line being read from the text fi le consists of the word "Blue." After the line of code above n ms, strName will ho ld the va lue uBlue." The variable holds wh:ltever text string it fi nds in each successive line of the file . In a list o f co lors. it wi ll ho ld values like "Blue," "Orange," and "Maroon." In a list of businesses, it would ho ld values like "ESRl , 380 New York S t, Redlands, 92373 ."

With each iter-uion of the loop, Input goes [0 the next line in the text fi le , gets the value from that line, and sets the variable with that value. W hen the end of the fi le is reached, the process stops.

Once you have read the value into the variable, you can do whatever rou wam with it. In the fo llowing example, you use it to add a cho ice to a combo box.

The code opens a fil e c., lIcd names.txt and loops through it. Each line of the ten fi le is successively stored in the variable stTName. The Addltem method then takes the variable va lue and adds it as an item to the combo box. When the end of the fi le is reached, the loop ends and the text fil e is closed.

Open "c : \ names .txt" Fo r Input As ' 1

Do Until EOF II I

Loop

Cl ose U

Exercise 7b

I nput '1 s trName cboName.Additem strName

In this exercise you will wri te a Do loop to read the fi fly U.S. state names from a texl file and put them in a combo box 's drop-down list .

a Start ArcMap and open ex07b.mxd in t he C:\ArcObjects\Chapter07 folder.

W hen the map opens. you see a layer of U .S. counties with each state outlined.

D Click the CensusMaps button. Move the dia log box. so you (an see it and the map a t t he same t ime.

Most of the code beh ind the d ialog box has already been written. When the user picks a state from the States combo box. the vicw will zoom in on that state.

Th is combo box itself, however, has not been coded, so its drop-down list is empty. Its d rop-down style hasn 't been set either, so you can st ill type into it . Before add ing items to the combo box , or setting its Style property, you will make sure the zoom functionality is working.

C()(UI/B aDo loop material

Page 119: Getting to Know Arc Objects

In the Choose a state box, click the drop-down arrow to confi rm that it is empty, then type Utah.

,---o...tr.M_ 1- ::J 0-. .-",,,,, 2 _ 1 ' ::J -.- mo511 tes

~ -TI • I I

Click MakeMap.

MakeMap gets Utah from me combo box. zooms to it. and draws its out line.

Click Qu it to close the dialog box.

Using a file browser, like Windows Explorer, navigate to C:\ArcObjects\ Oata\ USA. Double-click StateNames.txt to open it.

This is the text file your Do loop will read. Each line in the text file conta ins a single srfl[e name.

f. , ...... .,..,. ""' .....

Close the text file and file browser windows.

Before writing the Do loop. ~·ou ' ll SCt the combo box's Style property so that users can't type in the box.

Page 120: Getting to Know Arc Objects

· S(,C(IOn one

D In ArcMap. click the Tools menu, point to Macros, and click Visual Basic Editor.

D In the Project window. under Project (ex07b.mxd), under Forms, double-click frmCensus to open it.

The combo box (o r state names is called cboStates.

_.c-_ I 3 ,boYUI'J _ . ..-.. - n cboCI.sws

-.~ I ::J cboSt.tH

m Click the cboStates combo box to select it. In the Properties window. set its Style property to 2-fmStyleDropDownlist.

m At the top of the Project window. click the View Code button.

The fmlCensus code module opens and you see the code (rom the previous exercise. Thc in itial i.e even[ contains your two looping statements for thc year and class combo boxes. Now you'll add a third loop to build the Stales combo box drop-down lisl.

_ .. ""'...... , .. 0_ .(' .. 0 11 ( . 1' ............... _, ....

c. " lo.T ...... "-To ... ' . ' ............ v . ... ,

.. "',,,. I<&. _".C"._ II ~"o'" .""' ......

•• , .... to I,., V"c'''''_'.'''.'''.11 ~ ... 'M~'U' ... '0«00' ' 0' , .. <'u • • • T • •

.-.c'u •••. 1dd .... ''''Cluo k ..

Inil illiu _nl

m At the bottom of the UserForm_lnitiaHze event, just before the End Sub line, add the following two lines of code to declare and set a string variable to hold the text file's path. (If you have loaded your data in a different location, you will have to alter the path below.)

C()(/illR (J Do loop :. yrighl:!d ma I

Page 121: Getting to Know Arc Objects

This is the ful l palh to where the text file is local l"<l and it includes the name of the (ext file and its .txt extension. Quolation marks are pur around the path to indicate that it is a string.

Dim s trFile As String s trF i l e = "c ; \ a rcobjects\data\ u s a \sta tenames . t x t "

m Add a line of code to declare a string variable to hold the state names.

This variable wi ll hold one stale name at a time. it's value will change with each run of the loop.

Dim s t rSt a t eName As St ri ng

III Add a line of code to open the text file strFile. Use the Input option and Nt as the file's identificat ion number.

Open s trFile For I npu t As . 1

lEI Add a Do Until loop that continues until EOF is true.

The EO F function uses the fil e number as its arguml'nt; in the previous step, you designrned the file number as I.

Do Until EQF(1)

Loop

p ", ou' '' ... . ,""" ... et " •• · e' I ........ ' ..... I ... " ' .... ' 0 .. ' . _ •••• ~.

",."

ENDLESS LOOPS

An Mdless loop means that for some rl'ason the logic bi'hind your loop has no way out Consider the fol· lowing loop. ThE' logicall"Xpression will never bE- I~ because five will ~ equal len. Sincl' this loop's expt"ession is always false, il will run forever.

Do Unt il 5 '" 10 Loop

The question is. if you accidentally put yourself inlo an Mdless loop. how do you escape? Ortl' way out is 10 simulta~ly press ~ (111 and Brl'ak keys on your k~rd. This operation is called Conl101-Bruk..

Page 122: Getting to Know Arc Objects

\L'Lllr)l1 I III

II] Inside the loop add the following line of code.

I nput '1, s trStateName

As the loop oms , this linc of code processes each line in the state names text fi le. The first time through, the strSrateName variable is set to hold the fi rst name in the tile (Alabama). The second rime, me variable is reset to hold the second name (Alaska). The loop ends when rhe EOF function returns true (there arc no more Hnes to read) .

OJ Add one more line of code inside the loop that uses the Addltem method to add the statement to the combo box.

cboStates. AddI tem strSta teName

II] Outside the loop, after the loop keyword, add a line of code to close the file .

Close il

~ .. ....... _ .. I.""" 0000 . . .. , ,,. , .... , ,,., .. ..

.. ,,, .. ,, I CO'III , .. _ " .... ho._ ~ ...... ~., ... , .... , .....

~.

,,- .,._-----------+ _ .. m Add one last line of code to set the combo box's default value to Alabama .

cboStates.Value ; °Alabama "

m Close Visual Basic Editor.

m Click CensusMaps. Move the dialog box so you can see the map.

ED Set the year to 1930, the number of classes to 3, and the state to Nevada .

Cot/IIJH (/ Do loop -~-----------------------:?-OPYright

• •

Page 123: Getting to Know Arc Objects

m Click MakeMap.

All Nevada counties are ;n the lowest population C:HC!,'Ory (}·cllo .... o) , except Washoe counry in lhe nonhwest. It has a high population because Reno, Sparks, and L'Ike Tahoe arc located there. In 1930, a lot of people were there lx.'Cause of the mining industry.

Next you'll compare the 1930 and 2000 populations.

m Set the year to 2000. Don't change the state name or number of categories.

m Click MakeMap.

Three cou nties are in the highcsllhird of all U.S. counties (red) and scvcml counties fall in the middle third (orange ). Nevada's population is on the risco

m Click Quit.

m If you want to save your work, dick the File menu in ArcMap and dick Save As. Navigate to C:\ArcObjects\Chapter07 . Rename the file my_ex07b.mxd and dick Save. If you are continuing with the next chapter, leave ArcMap open . Otherwise d ose it.

Page 124: Getting to Know Arc Objects

Fixing bugs Using rhe dcbllg loo/..s

Wo rk ing through the exercises in this book, you have very like ly gOllen a few error messages. h was probably easy enough to fix your mistakes by comparing what you typed with whal was written in the book. As you begin to write your o wn code, fi x­ing mistakes may nO[ be so simple. Ho wever, VBA comes with a Debug toolbar that has several buttons to help you find and fix bugs.

In VBA there aTC three types of errors: Compile, Run-time, and Logic. In (his chapter you will learn what they are, why they hnppen. and how to find and fix them.

Before \'o ur VBA code runs . it is automatically translated into machine language (3 language consisting cmirc ly of zeroes and o nes, which is all your computer really understands). This translation is called compiling. When there is a problem in the tra nslation, you get a co mpile error and the code docs not run. Compile errors occur because you make mistakt:s with VBA syntax- forgetting to include the Next key­word in a For loop. fo r insrance. o r typing a merhod without the name of an object and a dot. as in the example below.

Show

If you run code with syntax mistakes. you get a compile error message .

......... _ .... •

~ --. ..... _ ... -.. I -I

Ighl~ m n

Page 125: Getting to Know Arc Objects

Besides givi ng you the error message, VBA highlights the offend ing procedure in yellow and the error itself in blue.

::J I'" " I _U._C_ .... lI '''': ... ""._w _I ... ..,

b ......

• / I

In commst to compile e rrors, nm -time errors occur after the code has successfully compiled and is being run . A nm-rime e rror means that your VBA code is syntacti­ca lly correct, but that the instruCtions themsekes are impossible to carry Olt t .

The following line of code compiles, Ix.-cau:.e therc arc tWO numbers on either side of the d ivision symbol:

Acres = 40000 I 0

When the line of code runs, however, it causes a run-time error. Division by zero is acceptable syntax, bUi illegal math.

(:0. 1_ 1

The following line also compiles, but causes a run-time e rror:

Acres ~ · SquareFeet" I 43560

Here , the type mismatch error appears, because a text string can 't be div ided by a number.

VBA can't miss compile and run-time errors, and it kind ly alen s you to them wi th error messages. Unfortunately, VBA cannot detecr the third type of error, which is a flaw in your program logic. Code that has a logic error compiles and nlllS, but pro­duces incorrect results--or at least no t the results you were aiming for. It 's son of like telling rour dog to ferch a ball when you really wanted it ( 0 fetch a stick.

Page 126: Getting to Know Arc Objects

\L'Ctf()ll OHL'

Earlier, you saw that trying to divide by zero produces a run-time error. Not all math mistakes will stop your code from running. The line of code below attempts to con- I, r' ,. , ven a parcel's square footage to acres. The code compiles and runs, but has a logic error th ~H produces the wrong result every time.

aParcelsAcres : aParcelsSquareFeet I 4356

The correct formula fo r acreage is square feet divided by 43560, not 4356. This is an exmnple of a logic error. The syntax is good, the math is legal, but the result is incorn:ct.

The looping statement below tries to loop until 10 equals 100. S ince a Do Umilloop runs umil the logical expression is true, this loop will run forever.

Do Until 10 : 100

MsgBox x

Loop

Si mple errors in logic can often be caused by typing mistakes. In chapter 2, you learned that Option Explicit can find typogmphical errors in variable names. Unfortullmely, Option Explicit won 't help you with the logic errors above, since no variables are involved.

Logic errors are pesky. The only way to catch them is to test your code with several different inputs fo r which you already know the correct output. Then have someone else test your code with input values and resul ts that they know.

ighled material

Page 127: Getting to Know Arc Objects

Using the debug tools

When you get a compile or 11m-time crror, or when a wei rd resuh suggests a logic error, yOu usc VBA's Debug toolb.'lT to find and fix your mistake. Sometimes, lifter n:'ading an eTrOT lIl<."ssage, ~'OU know cxacdr where the problem is and how to fix it. When you don't, the Step Into hunon (the Step hutton, for short) is a good place to sr:m the debugging process.

The Step hun on nlllS one line of code :I t a time, while highlighting rhe line that is aOOul 10 be nm. Suppose you havc a tcn·lill\~ procedure thm n:sults ill a nm-time error. As you step line by linc through the code. you will eventually hit the bid line thm gen­erotes the error message. so you know right where the problem is. C licking the Run SubJ UscrForm button (the Run hun an, for short) at any time will nm the rest of the code .

..... >Au .. ...... . ... U ... ~ .. .

.. _ .. < .... ~ . ... " U;fO'

.... _., .. , • , ., . . ... , . . . ..... u .... cpu. , . ".,

......... . ... 1 ....... ,. .. I 0 -'0' 0. ~ •• ~ • .c ••• , •• , ...... . .

.... , ...

Bm what if )'ou have a procedure with more than a hundred lines! Steppi ng through each line could wke a long rime. You can speed things up by using breakpoints. which pause your code at a specific line. If rou suspeCt :m crror on or afu' r linc 50. you can put a breakpoint at line 49. \Vhen you click the Run button, all the code runs up 10 that brcakpoilll . 111cn the code pauses and line 49 is highlighted. From there. you could use Step to run one line at a time until YOli see the error.

You add a breakpoint by h ighlighting a line and clicking the Toggle Breakpoint button on the Debug toolb.u.

• II •

T099I~ B'~~kpoinl

You C:ln also add a breakpoint by clicking in the code window's margin. Ei ther way, a r('(\ c irclc marks the spot and thc linc of code turns red.

C HA I"T'ER a FIXING alio s

Page 128: Getting to Know Arc Objects

L' l 1 () n (l 11 L'

Oid; in margin to.cld 10

bo-ukpoint - /01

.... ... ... "" .. ,

Whcn trying to locatc an crror where a looping statcmcnt is involved, you use a combination o( stepping, running, and breakpoints. The loop below runs (rom 0 ro 1000. Su' pping through it line b\, line would take abom tWO thousand clicks. (For each iteration o( the loop, you would have to click once to enter it and again to fini sh it. )

Putting breakpoints be(ore and after a loop avoids this problem. C licking Run on the code below runs it to the fi rst breakpoint. C licking Run again runs the code to the second breakpoint. C licking Run a third time runs the code to completion.

FirJt b!'~.kpolnt - 101

..,. ... , ..... . " ..... ".~ .... .. A t a breakpoint, you can either dick S tep [0 run the present line and highlight the ncxt line or click Run ro run all the code up to the next breOlkpoint.

Sometimcs, seeing 01 line o( code and an erro r mess., gc isn 't enough to detcml ine the cause o( thc crror. Whi lc your codc is paused on a line, rou can view the contents o( a variable by hovering the mouse cursor ov('r thc variable.

Below, as the mouse is hovered over the intSquareFect variable in the paused rcllow linc. a tip appears with thc variable's current valuc o( 3200Cl. You can hover over any variable in the procedure, not just those in the paused line o( code. J( the variable's contents don't match what you expect, rou have (ound the pou:ntial cause o( an erro r.

~ -...., --(._, ...... _ ore .. u 10'0\>0 ' . .. ,.t k ... ... ",_ <

• ~ .. . , ,

Lsl".~ /be ddJIIB tools

• .... -..

,

,

,al

,

Page 129: Getting to Know Arc Objects

Exerdse 8 After a two-week "ac::nioll , you rerum ro your GIS programming job ::n the U.S. Census Bureau 10 find Ib::n a coworker has triccl to customire your Census Popula­lion M<lps d ialog box . UnfoTtun::nely, many mist<lkcs were made and the d ialog box no longer works.

In th is exercise, you lire going to find and fix the compi le, run -time, and logic errors introduced by your coworker.

D Start ArcMap and open ex08a .mxd in the C:\ArcObjects\ Chapter08 folder.

When the map opens, you see U.S. counties and the CcnsusMaps burton on Ihe ArcMap Standard loolbar.

This exercise lISSllmcs \'Oll are using Visual Basic Ed ito r's defauh c rror-rra pping option , so you will confirm your setting.

o Click the Tools menu, point to Macros, and click Visual Basic Edit or.

D In Visual Basic Editor, click the Tools menu and click Options. On the Options dialog, click the General tab. Make sure the Error Trapping option ;s set to Break on Unhandled Errors.

p-~

~- ~-~"~ - -- I-p .... - .. -

pc' __ .. ",

c. .... ea" • r ___ _

""''' . r _ .... _ _~cr.o_ ,_ ........ --1:1_0;0._ P' a_~

~I

D Click OK. Then close Visual Basic Editor.

o Click CensusMaps.

Befo re your code could compi le, a VBA syntax error was locat('-<i . When a compi le error is located , an error mcss..1ge appears, the code stops runn ing, and Visual B..1sic Ediror opens .

.n --......... , , ... -CIlAl'TER S FtxlISO "lI("o5

Page 130: Getting to Know Arc Objects

.'i .. ' l t , () 11 (J n l'

II Click OK on the error message.

The error is highlighted in blue and its procedure in )·cllow. For some reason, the Show method is on a line by itself without a corresponding form. What can this mean! Is the line supposed to display a form ! Was the word "Show" accidenta lly typed in, or is it a remnant of a previous line of code?

Some comment lines here might have helped answer these questions. It doesn't look. as if this Show method has any purpose. but for IlOW, )'ou'li turn if into a comment instead of deleting it.

_I .. _C 51 II 1<...:._ ...... _I ••• -. .., ....

D Comment out Show by putting an apostrophe in front of it .

'Show

The commemcd line turns green. Normally. )'OU usc comments to make nOtCS [Q

yourself and o ther programmers. Comments are also useful if you want to leave in optionallincs of code. For example. )'ou might have three blocks of code that do the same task in different ways. You can keep all three, and comment out tWO of them . On ly the uncommemcd block will run.

Now that you've fixed the compile error, you'll run the code again.

D Close Visual Basic Ed itor.

D Click OK to stop the debugger .

..n "" -. .. -.. ~'-

II:] Click OK on the User Interrupt message.

Your code was trying to compile and run . You arc imerrupting that process so you can return to ArcMap and retest the CcnsusMaps bunon.

( sillg the del)llp' tools .- yrighl:!d ma I

Page 131: Getting to Know Arc Objects

,

m Click the CensusMaps button.

Another error appears; this t ime, it 's a run -time error. The mcssal,.'t" indicates an erro r in the Project .ThisDocumcm..CcnsusM<lps procedure.

II ,,.. 77 __ ~Coo"

(10 I

The type miSmatch error means your code uses a data type that VBA is not expecting. Fo r example, rou may be using a number where VBA needs a string.

VBA usually highlightS the line of code that contains the errOf. Some errors, however, span more than one line of code and more [han one procedure. When that happens. all VBA can do is sho w yo u the procedure where it had to stop running.

m Click OK on the Type mismatch error.

m Right-click the CensusMaps button and dick View Source.

VislI<lll11.sic Editor opens to the CensusMaps macro. To help find the error, ~'OU will tum on the Debug toolbar and step throllgh the code.

ID In Visual Basic Editor, click the View menu, point to Toolbars, and make sure the Debug tool bar is checked to open it .

m In the ThisOocument code window, click your cursor inside the CensusMaps procedure. Then, on the Debug tool bar. click Step.

. "" " • II • • •• '!II!' •• ;'-"

Step

Th~ first linc of code in the m .. cro turns )'ello w. This line will run as soon as you click Step .. gain .

...... ... ...

CHAlorttA. a FIXIN'f1 ~(J(ls

Page 132: Getting to Know Arc Objects

Ell Click Step.

The procedure's fi rst line runs. The second line is yellow and ready to run.

I ... . ..

m Cl ick Step.

After you dick Step. a fonn's code window opens and the first line of code in its initialize event procedure turns ye llow. Your stepping has taken you intO a Sttond procedure in a second code window. The Show method opens a form, but before the form opens, irs UserForm_lnirialhe event must run. So the first line of the initialize event is now rei low and ready to run with the next step.

'Yo ,.< .... .. '.,.go, ,~, • • <To ... . '.,0 y. ,_

You now see that this error is a bit complicated. For some reason, the Show method was unable to run to complet ion to open the form . That's why the error mess..'lge gave the error location us Projccr.ThisDocument .CcnslisMaps. However, there isn't anything wrong with the Show line of code. T1\e bad line is actually inside the form's initialize event.

( 'si t/g the delmg tools

-,

,.,

Page 133: Getting to Know Arc Objects

When an erro r spans multiple procedures, ),ou c;m .see a list of them by clicking the Call Stack button. C.'l ll Stack lists the procedures that ~'Ou arc currently stepping through. The iniriall!e event proct.-durc (the current procedure) is at the tOp of the list.

• Debuq I:i

' ....... - I - I

II] Click Step.

The fi rst line of the initialize proct.-dure TUns and the first line in the For loop is highlighted. (Di m and other declaration statements are skippt.-d.)

0 .... m • •• ..- .. I . ..... . fe. , . . ...... "'0 .... 1000

III Click Step.

A type mismatch appears because the code tries to use a string where an integer is expected. The Start Value is 3, but the EndValue is "Eight". The EndValue should be a number, no t a string.

For a deta ik-l:l description of this error, you can click the error mess.'lgc's Help button. T he type mismmch error ~lbovc is error number 13. Common ('rrors like rhis have an identification number that you call look up. You can sec a list of all errors by search· ing the Microsoft Visual Basic online help for T rnppable Errors.

Page 134: Getting to Know Arc Objects

m Click OK.

m Change NEight" to 8.

You have f1x ed the run-time erro r. The code is now ready to test again.

m On the Debug toolbar. click Run . (This Run button works just the same as the one on the Standard toolbar.)

ArcMap and the Census Popubtio n Maps dialog box appear. If you click MakeMap. it will make a map. However, some people have complained that they b'Ct an error message when they pick certain years .

,----- • • -.-- 1-0.-• ...-__

II: P'u J 000'-

W Cl ick the Choose a Census year drop-down arrow to see the years that can be selected.

---- . o-.c..._

-.-I

In your original code. only the dl,."Cadc years were add(.,,(\ [0 the drop-down list, but now every year between t 930 and 2cxx) is there. The Counties larer att ribute table. however, only has data fo r each decade. Having all those extra rears in the drop· down list is a logic error-a flaw in the program design- but it leads to a run-time error. If the user picks a nondecade year, there is no corresponding data [0 display. (It would be a pure logic error if inCOTTCCI data was shown and no erro r message was generated.)

m Cl ick Qu it .

Usillg fix- delJl/g foots

I ,I •

opyfight:K:: ma I<

Page 135: Getting to Know Arc Objects

Next. you will add a breakpoint and step through the code to find the logic error.

m Make sure the code module for frmCensus is active.

m In the UserForm~lnitialize event, add a break point by clicking in the marg in, to the left of the first line of the Years loop.

The line turns red.

-= ........ . 1d<I!t_ •• '~1 .. . . "

Now you will nm all the code up to that line.

OJ On the Debug toolbar, click Run.

Your code runs to the breakpoint. The code pauses and that line turns yellow. While it's paused you can run. ncp, or view variable values.

tIl Click Step. Then hover your mouse over the intYear variable.

n,c variable co nrains 1930. the firs t value in the loop .

... . ~ ......... , .... ~,.-.

....... ., ,. .. , .',

." Evcryth ing looks normal so fa r. You'll run the loop again.

Page 136: Getting to Know Arc Objects

\ 1 f

ED Click Step twice to run through the loop again. Hover your mouse over the intYear variable.

Yo u expect to sec 1940. but you see 193 1. A logic erro r is adding every year to the cboYcars combo box. The loop is running as to ld, but it's not incrementing b~' 10, because the Step keyword and 10 arc missing from the loop's first line (the red line).

St~p 10" misiing .....

m Add Step 10 at the end of the first line of the For loop.

For intYear = 1930 To 2000 Step 10

m In the margin. click the red circle to remove the breakpoint .

m On the Debug toalbar, dick the Reset button.

The codc is reset back to its firs t line.

m Click the Run button.

The dia log box appears.

I

m Click the Choose a Census year drop-down arrow and click 1950.

Now, only the decade yt."3rs appear as cho ices.

CsllIg Ibe debuglro/s

n (lnt?

~Yfl hl~ m ",

Page 137: Getting to Know Arc Objects

m Set the number of classes to S and the state to Texas. Crick MakeMap.

o-.~_

0..._"_ j t 3 0........ j ,.,..

---= Y OlL h<lve fixed the errors introduced by your coworker while ~'OlL weri.' on vacation. Tactfully, ~'ou leave il copy of Gl'tting 10 Know ArcObjeas on his desk.

m Click Quit.

The suggestions below can minimize errors in your code.

• Tum on Option Explicit [Q identify typi ng mistakes in "<lriable names.

• Run the code and decipher tlny erro r messtlges.

• Usc the Debug toolbtlr to isolme bad lines of code.

• Test for logic errors by enterillg va lues for which you already know the corrcct resu lts.

• Try all combinat ions of options on d ialog box canITa ls.

• Have someone e lse lest the logic and try all the controls.

m If you want to save your work, click the File menu in ArcMap and click Save As. Navigate to C:\ArcObjects\Chapter08. Rename the tile my_ex08a.mxd and click Save. If you are continuing with the next chapter, leave ArcMap open. Otherwise close it.

Cl lAmRS FIXINO Beds

Page 138: Getting to Know Arc Objects

Making your own objects CreUling dtlHC:!

CTI!ul ing obje(:h

At an earl ~' age children inevitably ask, "Where do babies come fromr' In VBA years, you arc at that age and ready to ask a similar question, namely, "Where do objects come from !" Fortunately, it's less awkward to answer the second question than the fi rst. O bjects come from classes.

You can make a new object with two lines of code. The ones below make a new dog object.

Dim dl As Dog Set dl = New Dog

Late r in (he chapter. wc'llmlk about this code in more detail; right now, the point is that you can make a dog object because somebody somewhere has a lready made a Dog class. Your dog object comes out of that class. The person who made [he class defined what dogs aTC and what they do. They may have decided that dogs have a Name property and a Bark method. That allows you to wri te code like;

dl.Name : "Sparky" dl.Bark

A class is like a blueprint or template-you can make as many objects from it as you like. Every new object that comes from the Dog class has the same collection of propenies and runs the same methods. The code below makes a second dog, seLS its name, and makes it bark.

Dim d2 As Dog Se t d2 : New Dog d2.Name : "Rex · d2 .Bar k

ighled material

Page 139: Getting to Know Arc Objects

Ma~'bc you're thinki ng thm if objccts come from classes, that just raises another question: where do claSSt.'S come from l Programmers make them, of course-but how!

A class is basica lly a container full of propenies and melhCKls. TIle container is a code module and the properties and methods arc procedures.

You already know about sto ring procedures in code modules. In chapter 4, you " 'rotc procedures for a Tax Calculator form and Sl or(."{\ them in iI module called a fo rm module. In chapter 6, you wrote procedures fo r a C rimeAnalysis tOOIb..1T and stored them in a module called a standard module. It's the same thi ng with classes. You declare variables and write procedures Ihm become Ihe propenies and methods of the class. and you Store them in a module called a class module.

The following gmphic shows the code module for the Dog class, along with irs properti t!S and methods:

, •• " ••• ,., .... II "ato, -_f, _f. _f­

f"" .,.,

To creale a property. you declare a variable and specify a dara type. The first line of code in the elwmple creales a Name propen~' that ,lCceplS any text string as a value.

Dim Name As St ring

To creat e a method. you write a subroutine or function . The next lines in the example c reate a B.1rk method .

Public Sub Bark!) MsgBox "Roof, Roof , Roof"

End Sub

Running this method dispbrs a mcssage box .

Every object you make accl.'SSCS the code in the class module it comes from. Whcn you create a dl dog and SCI its Name property to "Sparky," VBA looks at the Name property code in the Dog class module and makes sure Ihal a string is expecuxl. When you lei I the dog 10 bark, your code call ~ the Bark() subroutine in the Dog class module and runs il.

You can think of object -oriented programmi ng a~ havi ng two rie~: a lower lier of crl'ating and using objl"cts from existing classes, and an tipper lier of creating the classes Ihemselvcs by wriling Ihe code fo r propenies and mel hods in a dass module. ProgrammerS refer 10 these lieI'S as diem and server programming. A dass is called a server since it provides services to cl ien t.s. When you m3kc a dass. you arc do ing

CtlAM'ER I) MAKINO , 'OUR OWN 0IYEC1"S

Page 140: Getting to Know Arc Objects

server-side progrnmming, When you write code (0 create an object (rom a class and use its properties and methods, you are doing client-side programming, Your code is like a client receiving services,

This book is mainly abou t client-side programming with ArcO bjects servers, However. knowing a bit about server-side programming Co.'!.n onl}' help make }'OU a better client-side programmer,

-,:,£ , ,,,1 ,

Page 141: Getting to Know Arc Objects

I I I

, , I ,

! • ,

Creating classes

Microsoft programmers have already created classes for all the YBA objects like forms and controls. ESRI programmers have already created classes for all the GIS objects like maps and layers. You may wonder if there's anything left (o r you. Luckily, there arc plenty of classes to be created that arc specifi c to the problems you must solve in your work.

Say you work for a city and you are building an application to help manage tax assessment and collection. It migh t be usefu l to model the city's land parcels in A rcMap. Nei ther YBA nor ArcG IS has a parcel object . S ure, you cou ld make a Parcel layer from a Parcel Feature Class in a geodawbase and query its attributes. But sti ll , there is no programmable o bject called a parcel. So you couldn 't write a line of code like the onc below to d isplay a parcel's value:

MsgBox myParcel . Value

A nd you couldn't write a line to display a parce l's zoning code:

MsgBox myPar cel . Zoning

Thar may give you a reason to create a parcel class of your own. Befo re you do the programming. however. you need to do some planning. Whm pro perties should parcel objects have and what methods should they nm ?

Say you decide that parcel objects should have a Value prope rty. You want th is property to have the C urrency data type (since the p.'lrcel "alue is monetary) and you want to be able to get or set it. You also decide that parcels should have a Zoning property. This property wi ll have a String data type (to ho ld values like "residential" or "commerc ial" ) that you a lso want to be able to get o r set. Finally, YO li want a method that calculates the tax on a parcel.

At firs t, you migh t skNch your ideas on paper, but sooner o r later it 's a good idea to represent them with Unified Modeling Language (U ML). U ML is a d iagramming technique that programmers use to draw classes, properties, and methods with stan­dard symbols. For example, classes (like Parcel) arc d rawn as rectangles, propen ies (like Value and Zoning) appear next to b.'lrbells. and methods (like C"iculareTax ) appear next to arrows. These UML pictures arc called object model d iagrams .

In the d iagram, data types arc list.ed to the right of propert ies and methods. Fo r example . you see Zoning: String which means m at the Zoning property is stOred as a string.

CIIAJ'TER 9 MAKINO \'OUR OWN OllJECTS

Page 142: Getting to Know Arc Objects

SL'Ct/Ul1 Cllll

There are several software packages that draw UML symbols. If you code applications with [he parric ipation of o ther people especially other programmers-it's probably wonhwhi le to buy one of them. Whether you use UML or not. it 's essentia l to

diagram your class before you begin coding it.

The diagrams are most useful after your cod ing work is done. People who arc new to your classes can look at your diagrams lO understand how they work In the fo llowing chapters. you will look at A rcObjC(:ts diagrams lO learn how those classes work.

In VBA. you create a new class by making a new class module. You can store the module in any of the three projects: the currem map documem , the normal tem­plate , o r a b.."lSC template. If you c reate the class in the currem map documem, like the Parcel class module below, client-side programmers will only be able to create parcel objects in that map documem. If you wam the class to be available lO any map document, you should SlOrt' the class module in the Normal project.

To make a property for a class. you simply dC(:lare a variable with a data type. You've dC(:idL'Ci that the Parcel class will have two properties. You creale them by by declar­ing variables in the class module.

""". V., ...... t ........ ,

U nlike the variables you've worked with so far, these variables are declared outside a procedure and with the Public keyword , instead of inside a procedure with the Dim keyword. Variables declared With Dim can only be used in the procedure they are declared in . The Va lue and Zoning variables, however. do not belong to a specific procedure. Declaring them outside a procedure and with Public allows them lO be

Crt'flrillB clas.~·

Page 143: Getting to Know Arc Objects

used by an~' procedure in any code mooulc (as long as {he proc('durc is in (he current map document , since that 's where you arc storing the class).

Propenies can also be cremed by the more advanced method of wriling properr~' procedures. (In chapter 2, you rcad thm there arc four types of procedures: event. subrout ine. function . and property.) \'(Iith property procedures. you call write morc detailed code to comrol the gcrt ing and sen ing of propcnies. For example. you might wrile a procedure that retrieves property values from a database roble. Wh ile this book does nm go into the subject of properly procedures, you can learn more aoour them h)' searching the Visual Bask online help for the Property keyword.

To make a method for a class, yOli code a subrominc o r a (unction, depending on whether the method returns a value. The CalculateT:lx method wilt re turn a tax amoum , so it would be coded as a function. (The code would be similar to the code you wrote in chapters 4 and 5 (Q c<llculate t:,xes. The difference is that instead of puu ing it in a cl ick evem procedure, which requ ires user interaction to run, you lI'ould make it one of the object's methods, so it could be run beh ind the scenes. )

O n the U ML di<lgr:un of the Parcel class, thl' dara type rl'lurned by thl' method is listed after its name. Ca\culatcTax() : C urrency translates to "The C, lcul::!teT.'lx method returns the C urrency dolta type." So you add As C urrency to the function 's ccxlc itS shown below. The method has no argumcn LS, so its parentheses arc empty.

l'HAI'T£R I) MAIUNO YO~R OWN OBJECTS

Page 144: Getting to Know Arc Objects

'\ ((!

Classes are code modules. properties are variables (or property procedures), and methods arc subroutine or func tion procedures. The objccts that come out of the class may be simple or complex, depending on the code )'ou write for each property and method. C lient-side programmers never know the d iffe rence, because they get all of that code to run by using the object.property and objt.'Ct.method syntax.

Exerc:ise 9a As a programmer for a wildlife conservation project . you work with biologists who observe elephants. C urrently, the scientists use notebooks to keep track of the ir ele­phants. They also record each e lephant's trumpeting sound in a .wav file . Your job is to create an ArcMap environment fo r their work. S ince elephant objects don't exist in VBA or ArcGIS, you will program a new elephant class.

The biologists want to store and retrieve elephant names and ages. They also want to be able to hear an elephant's trumpet sound. You can use that information to make a UML diagram of the Elephant class.

El:;r.1t

I In this exercise, you will do the server-side programming to make an Elephant class based on the diagram. Your e lephant class will cOllSist of twO variables and a proce­dure that plays a sound fi le. In the next exerc ise, you will do the client-side program­ming and write code to create e lephant objects out of the class and use their properties and methods.

D Start Arc Map and open ex09a.mxd in the C:\ArcObjects\chapter09 folder.

The map is empty because the Elephant class you arc about to create won't be linked [Q any geographic location. In later chapters. you willieam how to c reate geographic features like points, lines, and polygons, and assign their geographic coordinates and attribute values.

D Click the Tools menu, point to Macros, and click Visual Basic Editor.

D In the Project window, right-click Project (ex09a.mxd), point to Insert. and click Class Module.

C lass l opens and looks just like any other code module. This one will store your Elephant class and the code for its properties and methods.

C rr' lItillR cllISSf!S

11 (leU

pyrighted mate'ial

Page 145: Getting to Know Arc Objects

o In the Properties window, for the Name property, replace Class 1 with Elephant. Press Enter.

The Elephant class is created. Now yo u will add its properties.

D In the Elephant class module, add the following two lines of code to declare age and name variables.

Public Age As Integer Public Name As Str ing

Notice that you do not write code 10 scllhese variahles. That's because they will be set by client-side programmers (including you) who make elephant objects out of ~'our Elcpham class. Fot e xample, aft er creating a new elephant, a cIiem-side programmer might write

myElephant.Name = "Benny "

0 '

my Elephan t.Age : 10

Now that the propenies arc done. you will code the Tnmlpct method .

o With the Elephant code module act ive, click the Insert menu and click Procedure.

o In t he Add Procedure dialog box, type Trumpet as the name. Make sure the Type is set to Sub and the Scope to Public.

If the Trumpet mcthod wc re going to return a va lue. like a dec ibellc"el. ~'ou wo uld make it a function. Si nce it JUSt pla)'s a sound file , you' ll make it a subroutine.

- """.=.,., --- J CI' I '*' ~I .~ . -,. .. I,

,.. ..... " I ....

Page 146: Getting to Know Arc Objects

, 'i L' l ( 1 () 11 t tt' f)

D Click OK.

10 Inside the Trumpet subroutine. add the following (ode. (If you have insta lled the data at a different location, you wi ll need to mod ify t he path accord ing ly,)

s ndPl aysound _ · C : \ ArcOb j e c ts \ Data \ e l ephant .wav · , _ SND-p5 YNC

This code is a hi t d iffercni from anything you've seen before. The sndPlaySound function does nO( come from either VBA or A rcObjcclS, bur is a Microsoft Windows A pplication Progmmming Interface (API ) function. A PI functions carr)' out operat­ing system operations like playing sound fil es, fi nd ing out who is logged on to a computer, or rcrriev ing the path to the Temp folder.

To cal\ an API fu nction in YBA . ~'ou fi rs[ have to declare il in another code module. (You d id this in chapler 6 when you dedaTl-d the KilQb'f'amToPound function in onc module and ca lled it from ano ther.) In this exercise, the funcrion has already been decl:m .'CI for you in the standard module called PlaySounds.

The sndPlaySound function has two llfb'llmem s: the fits[ is a path to a .wav sound fil e, and the second is a consmm, which can be either SND_SYNC or SND_ASYNC. The SND_SYNC option pauses the code umil the sound fil e has finished playing. The SND_ASYNC option le ts more code run while the sound fil e plays.

Functions return a value . but you don 't always have to use it. The sndSoundPlay function returns True if the sound plays and False if it doesn't. To keep the Elephant code simple. you aren 't going to use the returned value.

To learn more about the sndPlaySound func tion and its options. go ro msdn. microsoft .com and search for sndPlaySound.

Your elephant class is now complete. G ramed. it 's a pretty simple class. but it relics on the same cod ing principles you would use to create more robust classes. You are now ready ro make e1epham objects.

IIiJ If you want to save your work. dick the f ile menu in ArcMap and dick Save As. Navigate to C:\ArcObjects\Cha pter09. Rename t he file my_ex09a. mxd a nd click. Save. If you a re cont inuing wit h t he next exercise, leave ArcMap open. Ot herwise close it .

C rt!fllillg c/1I.>.S('S pyrighted material

Page 147: Getting to Know Arc Objects

I

Creating objects

Up to now, yOIl have created o bjectS with the aid of a lIscr interface. For example, in chapter 3, you created a new form object from the loser! menu. and you then created CommandButton objects b)' dragging them (rom the Visual Basic Editor Toolbox o nto the (onn.

Now you will crcatc obje<: ts with code, by declaring and scHing variables. Variables represent not o nly basic data types like numbers. dates, and srr ings. but can also represcnt objects.

Variables that represent basic claw types arc called intrinsic variables. YOII dcclaTl! and set them with code like the following:

Dim X As Integer X '" 365

Then you usc them.

MsgBox X

Variables that rcprcsem objects ;lre called object variables. TI1Cse \'3ri;lblcs <ITC .. Iso dcclart.-d ,md set, but the code is a little dif(crt'm. When you declare an object vari · able, yo u uS(' the class name as the data type. For an elephant object, you would declare the variable as Elephant.

Dim E As Elephant

TIle line of code to S(' t an objeCt variable begins with ,he $ct keyword. If you arc creating a new object , you also use the New keyword between the equals sign and the class name. So to creale a new e lephant object, you would write the following line of code:

Set E = New Elephant

Now th,lt you ha"e an object variable called E, which refers ro a new elephant. you can usc (he variable to set the elephant's propert ies and run its methods.

E. Name = "Mark" E. Trumpet

Then, if you want, you can creare some more elephants.

Dim E1 As Elephan t Dim E2 As Elephan t

Se' E1 • New Elephant Se' E2 = New Elephant

C II AJ'T£R 9

Page 148: Getting to Know Arc Objects

SLcrlu71 ta'l)

After creating them, yo u can set their propert ies so that each one is unique.

El.Name = "Jerry" El.Age = 24

E2.Name = "Ron" E2.Age = 28

W hat about objecrs rou creatc thro ugh the user im erfnce! You don 't hnve to declare nnd set object variables for them because VBA docs it for you. When you use Visual Basic Ed itor to c reate a form objcct, for example, and you SCI its Name property in the Properties window, thai name becomes the form's variable name. Suppose you name the fo rm fnnXYZ. You can no w proceed to set its properties and run its methods with code like the following:

frmXYZ.Show

Exercise 9b In the previo us exerc ise, you made an Elephant class and programmed its properties and methods. In this exercise, you will make new objects o ut of this class and use their properties and methods.

D Start ArcMap and open ex09b.mxd in the C:\ArcObjects\chapter09 folder.

O n the S tandard [oolbar you see the AddElephant bunon next to Ihe Add Data bun on.

o Right-click the Add Elephant button and click View Source.

You see the AddElephant button's empty click event. You will write code there to create elephant obj~ts fro m the Elephant class.

o In the ThisDocument code module, in the AddElephant click event, add the following line of code to declare an object variable.

Dim theElephant As Elephant

U Add the following line of code to create a new elephant object.

Set the Elephant = New Elephant

After the Dim and Set lines run , a new objeCl is in yo urcomputcr's mcmOf)' and you h,lVc a variable (theElephant) to refer to it .

• •

Page 149: Getting to Know Arc Objects

D Type t heelephant. (including the dot).

Your Elephant class is recognized by VBA as a full · fledged class. As with any other object \'ariable, after YOli type the dot YOli see the drop·down list of its prop<'rt ies and mClhods .

. ~ .•. , .... . ,-,.".~ ..... ,,-)

.... !O ...... , .

l OCI . .... ~!i' I --,,-Next. you will wrile COOl' to SCl this new elephant's properties.

D Finish the l ine of code you started above by using an input box to set the elephant's name property.

theElephant.Name : InputBox ( " Enter name:" )

D Then set the elephant's age property.

theElephant.Age = InputBo x( "Enter age:" )

When rhese nvo lines om, inpur boxes itppear to you r biologist -users. Next, you will write a line of COOl' that displays the values back 10 the user.

o Add a line of code to display the new elephant's name and age.

In the mess:.lge box, the clcph.mt's namc will be on the top linc. "bCrLf (carriage retum line feed) wi ll put the elephant's age on the second tine.

Ms gBo x " N~me: " & theElephant.Na me & vbCrLf & "Age: " & theElephant . Age , _ vblnformation, "Add Elephant"

So, , ........... " .... I

' .. 01 ....... ' .• _ • ' ... .0 • • 4· ...... _, ' , ''''"01 ....... '._ " ' .. »too, , "b, .. _ , ",

.. ~oo. "M_, ..... U ........ N_ • o&C<~ 1 • "Age' " .... ~,. , .... ,.-. -"" "'_" •• , "UoO ., ...... , •

.... .....

Page 150: Getting to Know Arc Objects

· Sl'ClIU)1 rw()

II At the end of the Add Elephant procedure, just before the End Sub tine. add the following line of code to run the Trumpet method.

theElephant,Trumpet

Now you will test the AddElephant button.

II1J Close Visual Basic Editor.

m On the ArcMap Standard tool bar, click AddElephant.

m In the f irst input box. type Jack for the name. Click OK.

m In the second input box, type 35 fo r the age. Click OK.

You see the new clepham 's data display.

! 0' I

III Click OK on the Add Elephant message box.

After clicking O K. you hear the elephant trumpet. If you don't hear the trumpet, check your compurcr's volume, speakers. and sound card.

m If you want to save your work, click the File menu in ArcMap and click Save As. Navigate to C:\ArcObjects\Chapter09. Rename the file my_ex09b.mxd and click Save. If you are continuing with the next chapter, leave ArcMap open. Otherwise close it.

Crefltillg OiJji'CIS yrighled mal(rial

Page 151: Getting to Know Arc Objects

Programming with interfaces U~ing lApplinltion and IDOCllm ... nl

Using IIIl1ifiplr ilUcrfucn

In the last chapler, you saw thai objccts come from classes and you leam<.'CI how 10 make a VBA class of your own. In this chapler, you'll make the transition from ..... o rking with VBA objccts, like fonns, combo boxes, and your own custom objccts (the elephants), to working with ArcObjccts. like maps and layers. To do that. you have to learn a new concept- the concept of a programming interface. This is something very different from a user interface.

S uppose you added a couple more properties and methods to the Elephant class from the last chapter and then decided to group them in some Jogical way. One group consists of properties and methods that are specific to elephants and the other gro up applies to animals in general.

An inrerface is a logical grouping of properties and methoos for a class. It might be based on the level of generality or on some o ther similarity of use or purpose.

The Elephant class in this example has tWO interfaces. By convention, interface names start with the letter "1," so these interfaces might be called IElephant and IAnimal. On a U ML diagram, interfaces are shown with lollipops.

ighted material

Page 152: Getting to Know Arc Objects

You may be think ing that i( that's all there is to an intcrf;lce, it 's pro.'tty simple. In fact, there 's more to it, but for this book, you don't need all the dewils. Briefly, inter­faces are pari of the Component Object Model (COM), a set of programming stan­dards developed by Microso(t. A major benefit of COM is that it allows code wrinen in one language, like Visual Basic. to work with c.ode written in another language, like C ++ . The ArcObjects interfaces and classes, for example, are created with C ++ and you can program with them using YBA.

In th is book, you'll work with existing A rcObjects classes and interfaces, but ~'ou won't make any of your own. When you're ready to do that, you'll need a deeper understanding of interfaces. You can get that (rom the book Exploring ArcObjccLS.

Programming with classes thal have interfaces is just a bit di((erent (rom programming with classes that don't . Here's how you made an elepham object and ~t its Name properly with the int erface less Elephant class from the last chapter:

Dim e As Elephant Set e : New Elephant e .Narne : "Ethan"

You didn't have to know anything about interfaces to usc the elephant's Name property. As you work with classes that have interfaces, you have to fi nd out which interface a property or method is on be(ore you use it.

The Map class below has two interfaces: IMap and lAct iveView. As you declare a Map va riable, you have to choose one of its inte rfaces.

' .... o-f

C tli\I'TI'R 10 PROGRAMMING Wln l ll'o'TFRFi\CES

Page 153: Getting to Know Arc Objects

"LCfton [H't)

Say you wam to create a map and set its Name property. juSt as you did with the elephant a moment ago. The Name property is on the IMap interface. When you declare the Map variable. you use the interface name (IMap) instead of the class name (Map). So you declare the variable as IMap. The rest of the code is the sa me as the elephant code. The variable is set with the New keyword, and the N ame prop­erty is set equal to a string.

Dim p Map As I Ma p Se t pMa p : New Map pMap .Name = ·Ryan'S Map·

Had you wanted the Map class's Extent propeny, you would have declared the variable as IActiveView. since Extent is on the IActiveView interface.

Dim pActiveView As IActiveView Set p ActiveView = New Ma p p ActiveView. Extent = someNewEx ten t

You only have access to the propenies and methods of the interfuce to which a variable is declared. So with pMap you only have access to IMap's properties and methods. and with pAcriveView you only have access to IActiveView's properties and methods. For now you will use one interface at a time. In the second exercise of this chapter, you'lilcam how [ 0 use more than one interface at a time.

Variables like pMap and pActive View are called pointer variables because they JXlint to a specific interface. You can say that pMap points to the IMap interface and pActiveView JXlints to the IActiveView interface. By convention, pointer variable names have a "p" prefix.

You may be wondering why you haven't had to use interfaces with VBA objects. Don't they have them ~ As a matter offact they do, but whereas ArcObjects inter­faces are exposed, VBA interf3ces afe hidden by the programmers who created them. When you usc VBA objects, variables point to interfaces, but it's done (o r you behind the scent."S.

That 's an advantage in one way, because you don't have to think about it, but it 's a disadvantage in another way. When interfaces arc exposed, they can be shared. That means you can create your own custom classes and have those classes use interfaces created by someone else.

Page 154: Getting to Know Arc Objects

For e xample. rou can create a class and tell it to use the A rcO bjeC[s IContentsView interface. The robs in the ArcMap table of colllems CilCh have the IComcntsVicw inter­face. When your class uses that ArcObjects interface, it fi ts in with other ArcObjccts. lContenrsView on your object is recognized by ArcMap and becomes another tab in the ArcMap table of contents. The custom tab shown below also has some A rcC.-ualog imerfaces. TIle re.sul l is a new tab that cOnlains a fu lly funel' ion .. 1 ArcC.'ltaIOS tfCe .

. .... __ ... - ....... ~ '"" ... - I , ~ - '-~~~==2-.i.!:C!'-. __ __________ ~ o 16 iii .. r.I ~ :::J :1. ,... I{/

.'­- ... " . ~­. ~--• ...J ."... ..

. ~­...J ,,·,h • ::..J <I ' .. • ...J "'""'_ • ...J 00l000,0 ·",J a-n · ",J ~1l

• ",J .,....,n • ...J Ooooloo" • ..;l a-II · ..J ~" • W <I>00l00.1 • .:J a.... .. ' U ~IO • .,J ....... .20

U _ -

(USlom lab

I A '

'1

• • •

When interfaces .. re h idden . yo u can 't use them to make )'our o wn custom c l .. sses. In th is book, you won ', reap the benefi ts of exposed ime rf .. ccs-rhat harvest wi ll have to w .. it until yo u start programming your o wn A rcObjeCls.

CII AM'I!.R 10 PROGRAMMING ~Inl IN11ORFACE$

Page 155: Getting to Know Arc Objects

"i\.'(llllll lll',1

Using IApplication and IDocument

Normally, when you use objects, you declare and set variables for them. When you start ArcMap and open a map document, however, a couple o( objects are already in use. This is because you can 't do anything at all until you have a document open in ArcMap.

The two special objects a lready in use are the Application object and the MxDocument object. Since these objects are in use, it (allows that variables have already been declared (or them. The name o( the Application object variable is Application. The name of the MxDocument object variable is ThisDocumcm. These two are the only predefined object variables there are.

Thi"""ume-nl -

AppIiUltlon

I . ""' ..... -- _.... . I"I ~""_ I' '"* __

I'p . • .

cp_ . It

All ArcObjects classes have interfaces; therefore, a ll ArcObjects variables are pointer variables that point to interfaces. Application and ThisDocument poim to interfaces on the Application and MxDocument classes. (These two special vari­ables don't observe the convention of beginning with a lowercase "p.")

The Application variable points to the IApplication interface on the Applicmion class. The variable has access to all the IApplication propenies and methoos, among which is the Caption property.

Usi"g ItIpplfctlliOl1 ImtlII)OCIIIIII.'''' ghl O~' "

Page 156: Getting to Know Arc Objects

I Application

Appliut ioo - tAo>-.... 1ion ~I Cilption property

The code below uses the pn.:.-dd lni..·d Application variable to set the A rcMap window's caption.

Appl i c a t i on. Capt ion = · Save El ephants·

In class diagrams, the barbells next [0 a property tell you whether you can get or set the propert~'. A rwo-sidL-d barbell , like the ont! by the Capt ion property, means that you can bmh get and Set the property. A left -sided barbell, like the ont' by thl' Name property, means you can get the property, but you can' t set it to something new. A righ t-sided barbell means that you can set the property but not get iI .

The ThisDoculllent v;l riable JXlints 10 the IDocu ment intcrt.lCe on the MxDocument class. The ,'ariable has access to al l the I Document propert ies and methods. among which is the Title propeny.

ThisOoc:umen t - ~

Title property on 1000l.lrnent

CHAPTER 10 PROO RA MMINO WITIt tNT\!.RFACE.$

Page 157: Getting to Know Arc Objects

.... i L ( r I () n t tt' ()

In the diagram, all of IDocument's properties h:tve left -sided barbells. which means you can only get their values. Say you W3nt to displa~' me tide of the current map document in a message box. The Title property is shown as Tide: Srring, which means that the Title property returns a string. You can display the map document's fil e name with the following code. No need to declare o r set me ThisDocument variable.

Msgbox ThisDocurnent .Title

Exercise 10a You have been asked to make some changes to the Washington. D.C. , Police Department's C rime Analysis toolbar (the one you worked on in chapter 6). In this exercise, you wi ll add some security to the mapdocumcnt---5ince it contains sensitive data-and you'll give the application a more meaningful title.

Because the c rime map conm ins dam that should only be seen by certa in dett>(; tives, you'll write an If Then statement to check the user's identity. As the c rime map opens, your code will ask for a password. Users who know it are authorized to open the map; o thers will get a warning and be scm to a less sensitive dty street map.

W hen A rcMap starts up. its title bar contains three elements: the name of the .mxd file, the name A rcMap, and the name of the current software license (Arc View, ArcEd itor. or Ardnfo). Your first msk will be (Q use the Appiicmion object'sC.,ption property to set a t ide that wi ll be more meaninb.{u l to police personne l.

Appllcltlon tll~

~ "" ~ - I 5 I~-:'::'=":":;-L=::::::~L.;!",!~!,,~~ ____ ~_---; ~~~~O;;,.~~~f! ~ + I' - ::I :l. ,.. r(I •

F _ ,. , ' 0 _

o 0 _

0 .. ., • • II! ... ,.

· 0 1M _ .. -0--.­-, • • • • • • 0 0 • ,..

USl1/g /I IPplic(ltiOll {l/u/IDoc/lIll/!1/I

n, i 4

• 0wI _

:!I (i13 • I I A' b · .t. • .:.'

~oht >d m,-,,' ,al

Page 158: Getting to Know Arc Objects

I

D Start ArcMap and open ex10a.mxd in the C:\ArcObjectsKhapter10 folder.

You see the District crime map. and you see that the ArcMap title is "ex 100 .mxd • Arc Map • ArcView" (or ArcEdit or A rclnfo depending on ~'our license),

U Click the Tools menu, point to Macros, and click Visua l Basic Ed it o r.

D Unless the Th isDocument (ode module is already open, go to the Project window. Under Project (ex10a.mxd), under ArtMap Objects, double·click ThisDocument .

Thc ThisDocumcnr code window opens, and rou sec the code you wrote in chapter 6 fo r the bunons on the C rime Analysis toolbar.

D Click the object list drop-down arrow and click MxOocument. Click the procedure l ist drop-down arrow and click OpenDo(ument.

The OpcnDocument even! is to the map document as the In itialize event is to the UserFo rm. These tWO even[S happen just before the user sees a map document or a dialog box.

The code you arc about to write in the Open Document ('vcnt will ask the user for a password. If they know the password, the map will 01X'11 and the A rcMap title will be repl;lccd by a new one. O therwise, a warn ing will appear, and ;l less sensiti ve street map will olX'n .

D In the Open Document event, add two lines of code t o declare a string variable and set it with an input box that asks the user for the password.

Dim strPassword As Str ing strPa ssword = InputBox{" Enter password")

You wiUser up an IfThcn smtcment TO ver ify the password.

II In the Open Document event, enter the following If Then statement.

If ·Carter " = strPassword Then

Else

End If

Nest, you will wri te code to nm when the st:uemcnt is truc. You will use the predefi ned Application variable and its C"\ption property to change the ArcMap application title.

D After the Then and before the Else, type Application . (including the dot).

Page 159: Getting to Know Arc Objects

,

,~ I.. C [ I tJ 11 t tV 0

After typing the dot, you see a list of Application 's properties and methods.

Duo . «h .... r~ .. . " • .., • 1.,. ... 0 .. , ............... · 1

1I ••

Since the Application variable points ( 0 the LApplication interface. the properties and methods in the drop-down list above match those in the lApplication diagram.

Appliuotion Application

varl.ble - IAppo;. tion Csptioo Plopefty

II Finish the line above by setting the Caption property to District Crime.

Appli c ation. Caption = "Dis tric t Crime"

When the wrong password is entered, your code will warn the unauthorhcd user that they a m 't open the crime map's .mxd file. To make the warning mess.'lgc, you will usc the IJ::locument interface's Tide property to get the .mxd file name.

ThlsDo<ument MJ;DocUi1I.nt

varl.ble - IClocunerI:

USIIl,~ IApplicfIIloll (/lId IDocIl Illt'1/I

" ,

:-yrl hl~ m n

Page 160: Getting to Know Arc Objects

D After the Else keyword, add the following code to concatenate the map document's t itle with the warn ing instructions.

Msgbox Th isDocument. Ti tl e & • is a s ec ure map . • & _ "A st ree t map wi l l be opened fo r you. "

To send unauthorizt."tl users into another map, you will use the IApplicaiion's NewDocument method. Given (l path 10 a map template ( .mxt fi le), this ml'thod opens the spec ified map. Because New Document is on the IApplication intert.'1ce, you can still use the predefined Application variable.

Appliut ioo AppIle.Uon

v,ri.blt - 1AWic.1ion

m Add the following line of code that uses the NewDocument method and a path to the map template file. (If you installed the data at another location, type the appropriate path.)

The streets. mxt fi le in the Data folder contains the District's boundaries and streets but no sensitive crime daw.

Application.NewDocument _ Fa lse , _ "C : \ ArcOb jects\Oa t a \ dc\str ee t s .mxt "

New Document's first argument is either true or false . If true, the New template dialog box opens before a map opens. Your users don't need to sec any dialog boxes, so you use fa lse.

CHAPTER 10 PROGRAM MING .... ·ITH INTERfACES

Page 161: Getting to Know Arc Objects

St!C[I071 twu

The second argument is the path to the template .mxt file. Whenever rou type path and file names in code. you should double-check rour typing and use a file browser or ArcCmalog to confirm the file's location. Second only 10 typos, incorrect path and file names arc probably the greatest source of VBA crrors.

' . 'Yal' ,~.~. tx'

. UO ... Pa .... 'd ... ".n..,

.u' ..... 'd ' " ,.U"i·"'" _._d·1 " ",,_, •• ' . .......... d ..... .

' nH.o<,o •. C.~ .. o •• "'","C<. c .... • u "

....... "".' , . . 1 . Tl U •• • I • • _ . _ • ••

-0 ...... _ , . ,11 ... O .... d ' ''' ,..~ . '

••• "".'.0 .... __ ., ,., .. , · 0 ' \ .. .;.,) • • ,.\ .... \ ... \.".« •. _<'

l "" If

The OpcnDocumcnt event procedure's code runs when a map document opens. So to test it, you will save your work. dose the map document, and then reopen it.

m Close Visual Basic Edit or.

m In ArcM ap, click the File menu and click Save As. Navigate to C:\ ArcObjects\ Chapter10. Rename the file my_ex10a.mxd and click Save.

Inslcad of quirring and restaning ArcMap, you will open a blank map document and then reopen the crime map you JUSt saved.

m In ArcMap. click the New Map File button on the Standard tool bar.

A new map document opens. To simulate an unauthorized user, you will try to open the crime map with an incorrect password.

m Click the File menu and cl ick Open. Open my_ex10a.mxd in the C:\ArcObjects\Chapter10 folder.

IE) For the password. type ArcObjects. Cl ick OK.

A mcss., ge warns that a Streets map will be opened .

...... ,0._ •• _._. __ .... _ .....

Usillg IAppliCflriol/ (III(( IlJocullle'"

,I, ,,.

Page 162: Getting to Know Arc Objects

II] Cl ick OK on the warning message.

A new map opens with the strcelS and prccinclS layer. No sensitive data layers are shown .

. ........ -- .... -.

i! ....... -, , , • , • ,

Next. you will open the crime map with the correcl password.

m Click the File menu and click Open. Open my_ex l0a.mxd in the C:\ArcObjects\Chapterl 0 folder.

m For the password, type Carter. Your If Then statement is case sensi t ive, so make su re the "C" in Carter is uppercase. Click OK.

The crime map document opens. TIle application title is now Disrrict C rime .

. -'.'''-. ~ I

m If you are continuing with the next exercise, leave ArcMap open. Otherwise close it .

If you leave ArcMap open, the application title wi ll remain District C rime. The title stays unt il you nlO code to change it. or until you quit ArcMap.

Page 163: Getting to Know Arc Objects

· .'\L'Cl/!)ll [tt'O

Using multiple interfaces

In the previous exercise, you used the Application and ThisDocument predefined variables. The interfaces they point to, IApplication and IDocument. don't have many propert ies o r methods. It's great to have these twO variables as starting points, but there !lfe o ther interfaces out there with lots of orher properties and methods that you might find useful.

As you know, ArcObjects classes can have several interfaces. If you have a variable pointing to onc interface on an object, you can write two lines of code to declare and set a second variable to point [Q onc of that object's other interfaces. You end up with two variables and access to the properties and methods of two interfaces. 'I' , <,

In the example below, you are working with the Dog class. You want to creale a new dog and get it to bark. The Bark method is on the IDog interface. so you declare a variable to that imerfuce. In accordance with convention, you name the variable pDogI. Then you use Set and New to create a new dog object. Finally, you run the Bark method with a 2 to make the dog bark twice.

Dim pDogl As 1Dog Set pDogl = New Dog pDogl.Bark 2

pDog I - Dog 0--

,,,.

Say you want to create a second dog and name it Rex. The Name property is on the IPet interface, so you declare a variable to that intemce and you call it pPet2. You use Set and New to create the second dog and then . with a third line of code. you set its Name property to Rex.

Dim pPet2 As IPet Set pPet2 = New Dog pPet2.Name = · Rex·

""0--

pPo.U - IPeI 0--

H.-Illg mll/tlpl!! iulc'ifaces IhI'~ material

Page 164: Getting to Know Arc Objects

Yo u no w havc tWO dogs. The firs! dog. re ferred 10 wilh the pDogJ variable. is name lt'ss but bark t"d twice. Tht' St'cond dog. referrt"d 10 with the pPcrZ variable. is named Rex and has nO( yet barked.

.., No w what if you want Rex to bark ! The pPCIZ variablc points 10 the IPel interface. which o nly gets you to the Name and IDTag properties.

Yo u might be wo ndering if you can uSt' the pDog J "ariable . and write:

pDogl.Bark

Yo u can, but that will o nly make the nameless dog bark. What you need 10 do is set up a st.'Cond variable that poinlS to Rex's JDog interface. This switching of interfaces takes two lines of code: one to dedare a variable to Ihe second interface and another 10 set that variable equal to thc variable you al rc<1dy havc. Switching interfuces is calk-d Qucr.,. lnterface. o r QI fo r short.

To get Rex to bark. rOll dcc!:! re a second pointer "ari<1blc to the I Dog im crfacc. which Ims Ihe B.'uk mel hod.

Dim pOog2 As tOog

Inslead of sen ing the variable equal 10 a New Dog (which would creale a Ihird dog), you SCI it equal to pPCIZ.

Set pDog2 ~ pPet2

Now the pPetZ and pDogZ v<1riables both refer to the same object (Rex); each. however. points to n different interface.

pOog2 -1Dog ~

pM -

Since pDogZ poin LS to the IDog interface. you can use the Bark method. The next line o f code geLS Rex to bark three timcs.

pDog2 . Bark 3

Page 165: Getting to Know Arc Objects

,etll(Jl\ lit·"

The pPetl variable points to Rex's IPe t interface. So you could use pPell to set Rex's IDTag property with the line of code below.

pPet2.IDTag : 714

You have created a dog, named him Rex, gOt him to bark, and given him anlDTag number. N ow how about getting back to the other dog and giving it a name! The variable pOog \ points to the nameless dog's IDog intc rfuce, bu t the Name propcrty is on the IPet inlerface. So to set I.he dog's name, you have to switch interfaces. This time you have to dec lare a new variable that points to the IPet interface, then set that variable equal to the one you already have.

Dim p Pet1 As IPet Set pPet1 = pDogl

&th pDog I and pPetl refe r to the nameless dog, but point to different interfaces. You can now set the nameless dog's Na me property with the pPel l variable.

pPet1.Name : "Rada r"

And. of course, you can still make Radar bark (again) with the original pDog 1 variable.

pDogl.Bark 4

In all, you have four variables referring to the twO dogs. You can use any of the four variables with the propert ies and methods on their respective interfaces.

pDog2 -

ppeU -

{ Isillg lilli/HpJi' fllferjilcN

i'W i ~, , r :t I 1

:!d ma ,.

Page 166: Getting to Know Arc Objects

Exercise 10b Over time, the crime map will be updated and used by many differem pt."Oplc. In this exercise, yo u will wri te code to keep track of which users open it. This will help you see wh ich members of the department are getting the most value from the map.

You 'll SlOre the information in the mapdocumem's Properties dialog box, which has input boxes for things like the map's title, subject , and amhor. Specifica lly, your code will write each user's password and access time into the map's CommentS area.

-,-----( "

• r •

'- _ .. P .......... _-- 11-._- I

The CommetIU IIU of the Pl"opertie1 di.,og boo

Also. for the benefit of people silt ing in the back of the room. you'd like to make the crime map as big as you can. At the Start of this exercise. you' ll write code to make the ArcMap window Rll thc d isplay screen .

D Start ArcMap and open ex10b.mxd in the C:\ArcObjects\Chapter10 folder.

S For the password, type Ca rte r. Click OK .

You sec the District Crime map.

o Click the Tools menu, point to Macros, and cl ick Visual Basic Ed itor.

TIle current passwo rd code is located in the OpcnDoc.ument event procedure in the ThisDoc.ument code module. You'll go there to write more code.

D Unless ThisDocument is a lready open, go to the Project window under Project (exl0b.mxd) and double·dick ThisDocument under ArcMap Objects.

The ThisDocument code window opens and you sec your code (rom earlier exercises.

CIIAI'TER 10 P ROCRA)'IMINC WITt! INTI;:RPACES

Page 167: Getting to Know Arc Objects

l' l l I

o Click the object list drop-down arrow and dick MxDocument. Click the procedure list drop·down arrow and dick OpenDocument.

You see the If Then statement that checks for the user's password .

..... • uPo ...... .. ... '~

. .......... " ' ....... c-..... ........ · 1

If -c ..... - - .u, ..... " •• _ . UH

1 •• lIoo .... . C . ... u - -., . U,C< t r_-

_. n .. _ _ .~ . T .. I •• - I ...... "'. _ • • •• • ~ . ..... _ • .. II ... " " .. d t o • ..... .

... 11 . . ......... • • • • ' al •• • " •• \ .... I .. I ..... u . ... "

" ,

In the laS[ exercise, r Oll used the predefined Application variable, which poi nts 10

the Appl k<ltion class's IApplication interface. In this exercise. you will switch to the IWindowPosit ion interface. also on the Application class. IWindowPosition has propert ies for controlling the size and position of the ArcMap window.

When class diagmms arc shown in this book. some of their interfaces. properties, and methods mOly be omitted to save space. For eX<lmple, the Applic<ltion class has ten interfaces. but only two are shown in the following d iagram. Also. all of the IApplication interface's methods have been omitted.

lWindowf'ol,illon I nl~rfau, - IW .... Poaltioto

To get to the properties for setting the window size, you need a variable that poims 10 the IWindowPosition interface. You can start (rom the prl!defined Applica tion variable. bur then you'll [leOO (Q use Querylnterface ( 0 swilch from IApplication (Q

IWindowPosirion. This means declaring a variable for IWindowPosition and setting it equal to the Application variable.

Udll~ lIIf1fIiP/£' 11/1('Iftla'S

11 11l'O

Page 168: Getting to Know Arc Objects

D After the If Then line, but before the Application.Caption line, add the following line of code to declare a va riable that points to the IWindowPosition interface.

Dim pWindow As IWi ndowPosition

I .. ''''M .. ''.'' U .<" .... ......... ""'~ • , • .",_,'10 .. , _."",d". Dec:lare II -cw .. ,' " ............ _.

---'~ ~ .. ... _. " 11.-......... . ••• " " ...... c ....... ·D ....... c,,_'

u " _ .... Tto •• I>oo_ ••• T .... . " . . . ....... _ •• • •

" •• " on _. _u, oe . ....... r<>r 7<' •• '

. ,.' IC •• I ... ,.,ol>oc:_.< ,., .. , -• .. \ ..... \ d<I ."n ... _.·

1.1 Below the Dim statement, add the following line of code to set the variable equal to Application.

Set pWindow ::: Application

You now havc tWO vMiablcs pointing to twO diffcrcnt Appl ic:nion interfaccs. as shown in the following graphic:

D Add the following line of code to set the Application window's State property to esriWSMaximize.

pWindow.State : esriWSMaximize

This code will maximb~c the ArcMap winclow for the District C rime appl icat ion. To leam more about the options for the Stal e property. you could highlight State in the code window and press Fl to open the ArcObjL'CtS developer help window.

Page 169: Getting to Know Arc Objects

s e L t I (J n r tt' ()

Next you will write code to track the map's users. N you recall, you' ll do this by writ ing the user's password and access rime into the map document's Properties dialog box. All the input boxc:s on this dialog box ~lre controlled by properties on the MxDoc:ument class's lDocumentinfo interface, shown below. You will set the Comments property.

Th isDorurMnt vu(,ble --,_ o-{

IDocumentinfo Interi.ce - IOon' ,. O dO 0---

=-=

" " -

~o.""

O nce again, you will st:lrr with a predefined variable and use Querylnterfuce. This time, the predefined variable is This Document and you are switching from the IDocument interface to the lDocumentinfo inlerface. To make the switch, you'll declare a variable for lDocumendnfo and SCI it equal to the ThisDocument vari3ble.

f 'sillR IIIII/Ilp/e ',,'etj(/C('$.

'9 10 ~

ighled mate ial

Page 170: Getting to Know Arc Objects

-• •

I

• , U In the Open Document event, after the strPassword variable is set with the input

box and before the If Then statement, add the following line of code to declare a variable as IDocumentlnfo.

Dim pInfo As IDocumentlnfo

••• • , •• &O.oo.G .. ""'00 ........ _ .......... ., ...... "' .......... . It "CO".," • • « ......... . n.o.

II • •

D ... .. , _ _ u 11'_'_"',0 ... ,,,_ •. "'U~'"'' ... -..................... . • "ue." ... ~ •• u •• • "D ... no:< c._'

_too n" ___ ,.T,,' • • • I •• oO'C'Uo ....... ", aU"' _ , '11 ... o .... ~ ' 0' ?"o,"

• •• I' • • "o .... _ _ ~

m After the Oim statement, add a line of code to set the variable equal to ThisDocument.

Set pInfo : ThisDocument

You now have rwo variables pointing to two different interfaces. As shown in the simplilled MxDocument class diagram below. Th isDocument points to the IDocument interface and plnfo points to the IDocumendnfo interface.

MIlDoculMnt

plnfo-I~

m In the If Then statement, after the pWindow.State line but before the Application.Caption line, add the following tine of code. It writes the current time, the user's password, and the word Authorized into the map document's comments area.

pInEo . comments : pInfo.Comments _ & " "&Now_ & " • & strPassword & " Authorized" & vbCrLf

The empty quotes sepamte the entries and put spaces between the t ime and the user name. You won't sec what [he full commem looks like umil after the code runs and you have a chancc to open lhc Properties dialog box.

CUAI'TER 10 PROORA.I~UN(l WITIIINT(RPACES

Page 171: Getting to Know Arc Objects

• • '. , ,l.lllrJ

... ............. . , .. ... • ' ......... d· , .. ", ... t "Ia,", ....... d·, .... . "" ... ,-_.<."". h' , l aC • • n •• _ _ ...

I. ""'0'" •• , ......... ~. DO. .................. _.u .. So • • ,._ •• ' •• 1I~ .... .. •• ,_.1,., . ... , ............ . ,1.,o.C_ ••• . ,''''o.C_'''. · . . . .. . .

• • ••• "PU ..... _

• • , ... Il00,,,"" • we,Ll

To guarantee that the comments arc savl.-d into the .mxd fil e, you will add a Iinc o( code to 5.1Ve the file 3utom.n ically. Otherwise. a user could open the map document and quit without saving, and their name wouldn't be added to the comments. You will use IApplication 's SaveDocumcm method, shown below.

Application

-

SilveOocumeot ~thod

III Add the following li ne of code to save the map document.

Application.SaveDocume nt

You would "Iso like comments to be added when an unauthorited user tries to open the map. You'll add (hat code next .

m After the Else keyword, but before the ThisDocument warning message. add the follow ing ti ne of code. It writes the current time, the user's password. and the word Unauthorized into the map document's comments area.

plnfo.Comments : plnf o . Comments _ &··&Now & . • & strPassword & . Unauthorized- & vbCrLf

Us/liB IIIlIltip/e illleif{lC('S

-... •

,- yrighl:!d ma ,.

Page 172: Getting to Know Arc Objects

Ie Add the following line of code to save the unauthorized user's information.

Applic a tion . SaveDocument

When thc uscrenters an incorrect password, thcir password and time are added to the comments arca and the SaveDocumellt method rullS 10 sa\'(' the .mxd file. TI1en the warning appears and thc NewDocument method runs to open the strecrs. mx[ fil e.

II •• · ... ,... -• - •• o<r ....... G · - ~oa~.~. ,.oG- . ~.~ . ••• "CO" ... --. __ ••

a>v .... TIoI. _ _ .'.T,,'. ' - .......... _ •. - , - . . .... .... . , IL ...... _G 1M ..... -

• • • he • ., ••. IIo _ _ o. _ ..... , · " \ "';\ Ge\ ." ~' . '''' -.... "

Because rour code is in the map document's Opcn Documem evcnt , you need to open the document to tcst it. So you'll save your work, close the map document, open a new one, and then reopen th is one.

m Close Visual Basic Ed itor.

m In ArcMap, click t he File menu and click Save As. Navigate to C:\ArcObjects\Chapter1 0. Rename the file my_ex10b.mxd and click Save.

m In ArcMap, click the New Map File button on the Standard tool bar.

A new empry map document opens. Next , rou will try to open the crime map. but with an inco rreCt password to Simulate an unauth orb;.'(1 user.

m Click the File menu and dick Open . Open my_ex10b.mxd in the C:\ ArcObjects\Chapter10 folder.

m For the password, type ArcObjects. Click OK.

E:l Click OK on the warning message.

A new map opens with the streets and preci ncts from the Srreets.mxt template. Next , you will open the document with the com.'Ct password.

m Click the File menu and click Open. Open my_ex10b.mxd in the C:\ArcObjects\Chapte r10 folder.

m For the password, type Carter. Click OK .

Page 173: Getting to Know Arc Objects

The District C rime document opens and its window is max imized.

m Click the File menu and click Map Properties.

" l' L t f fJ 11 t It' CJ

In the Comments area, you see that the fir.;[ user was the unauthorizt .. d ArcObjects and the second user was the autho rized Carter.

So -',- I ~ .

-C" I '4 or

t •

"" a_ Ir---------

'- --P-.-· 001 __ _

User access l!mH and pauwords arc ~r~

m Click Cancel to close the Properties dialog box.

Now that you have programmed with interfaces you are ready to learn about anmher COM rule: Once an interface is publish .. -d it won't be altered in future releases of the softwa re, That means an interface will ah,Io'ilYs have the same properties and methods. Properties and methods will always have the same arguments and return values. Arguments and return values will always be of the same dam type.

If ESRI programmers want to enhance something about the IMap interface in a future release of the software, they never change IMap. Instead they create anothe r interface called IMap2 and make changes to it.

"'p

With this development approach , your existing code that works with the Map class and the IMap interface wi ll continue to work in the futu re with the next version of the sofrw;ue. At that time , if rou like, you could edit your code to point to the new interface, but it 's all up [ 0 you.

W If you arc cont inuing with the next chapter, leave ArcMap open. Otherwise close it.

UsiIlJ.: 1IIIIIIiple illll!rfilCi"S

Page 174: Getting to Know Arc Objects

ABSOLUTE AND RELATIVE PATHS

A§ you wrote code for this exercise. you may have notked that the path to the streets.mxt iiiI.' was differl!f1t than the one you typed in the previous exercise.

In exercise IDa, you typed:

'C, \ ArcObjec~s \ Da~a \dc \ s~reets , mxt"

This is a hard-<oded (or absolute) path, The path begins with a drive letter and lists earn subsequent folder that I!ads to the Slreets.mxt file, A hard-<oded path will locate the target data as long as it is stored in the specified location, If the target data is stored somewhere else (if it is moved, for example). the path will break and the data will not be found.

In exercise lOb. the hard·coded path has been rnange<! to:

",. \ D4t a \ dc \ str eets.mxt "

This is a relative path. It leads from the file that contains the code (in this case, exIOb.mxd) to the target data. The two dots mean "go up one folder in the directory structure.' Since exlOb.mxd is in the ChapterlO folder, the dou direct the code up one level to the ArcObjects folder. From there, the r~t of the path is hard-<oded.

You can go up as many levels as you want by using seu of dou:

" .. \ , . \ .. \ streets .mxt·

Relati~ paths make your code aAd data more portable. You can move the ArcObjects folder to any location you want. The code will always find streets.mxt, because the target data stays in the same loca, tion relatj~ to exIOb.mxd-up one folder to ArcObjeru. then down to Data, and down to de.

When you know that your data structure isn't going to change, use hard-coded patlls. for data that may move. use relative paths.

CH"J'TI!R 10 PROGRAMMING WITH INTERf ACES

Page 175: Getting to Know Arc Objects

Navigating object model diagrams GCUIllIo: IU~'('r!

CrO:dfiliK r!lld tL"iWling ('olor .•

So far, as you've worked with obje<:ts--gctting and setting their propcn ic5, runn ing methods. even switching interfaces-you've worked with onc class at a rime. But you know, of cou~. that there are hundreds and hundreds of ArcObjccts c1asst.'S.

The ArcObjccts you're fa miliar with . like Application and ThisDocumem, arc a lways right there waiting for you, like a limousine at your door. Typically, howeve r, you need to work with objects that are not quite so obligingly at your service. For example, suppose you want to program a button to change the colo r of a Rivers layer. A layer's color is an object (created from a class [ike RGBColor below) with proper­ties to mix different amounts of red, green, and blue.

IRgtICQIof

.......... - .

Even though rou have nevcr used RGBColor before, )'ou know from the last two exercises thai to make any new object you declare a variable to one of its interfaces, you set the variable to a new objec t with the New keyword, and afte r that )'ou can get and sct properties and run methods.

Dim pColor As IRGBColor Set pColor : New RGBColor pColor.Blue : 180

But your goo l is to make the Rivers layer bluc. How does [he code know which layer, in which data fmme, you want to change1lt's a different situation when, inst('ad of creat ing new objects, you wan! to do something with an object that 's already in play somewhere in your application, To do that, you have to find }'our way to the object.

ghled malc'ial

Page 176: Getting to Know Arc Objects

It's kind of like hopping to a marker in a game of hopscotch , o r swinging from one vine (0 another in the jungle. The hopscotch squares (or the vi ncs) arc classes, and you hop from onc to the next until you get to the one you want .

For ex;unple, (0 change the River layer's color, you would make ~·our way from the MxDocutnent class (MxDocument is the map document o r currently opened .mxd file) , to the Map class (the Map class in ArcObjects refe rs lo a data fra me), to the FeatureL"l}'er class, (0 the Renderer class (renderer is a fa ncy word for a layer's leg· elld), to the Symbol class, and to the Color class. and there, at last, ~'ou would change the properties of the color object.

MxDocument - Map - Layer - Renderer - Symbol - Color

Now, because you have to make a part icular series of hops 10 get from your starting point to rour destination, you can infer thac there arc certain spec ial connections or relat ionships between classes. The MxDoculllent class is associaled with the Map class, or connected to it, and thai 's why you can go ftom one to the o ther. However, the MxDocument class is no t connected to the Color class. And therefore you can't go straight from MxDoculllent to Color.

In UML, assoc iated classes arc connecled with a solid gray line. The line means you can get fro m one class to another. This relationship can usually be expressed in plain English by saying that objects in one class h;!v(' objects in the cOl\llcctcd class. For example, the MxDocument class is connecled 10 the Map class, and it's also nalUrnl to say that map documents have d ;.na frames. The Symbol class is connected to the Color class. and it's also natural to say that symbols have colors.

-0-{ .... . " ."~ .- •

O ther symbols on the diagram give you addition31 information about how the classes are related. The asterisk by the Map class means multiplic ity. In other words, a map document can have many m;!ps in it. The relationsh ip between the Application cl3ss and the MxDocumcnt class would nOI have 3n asterisk because you can't show twO .mxd fi les in one ArcMap window.

The black diamond tells rou that the objec t with the diamond is composed of the assoc iated objects. You can think of the object with the diamond as a container. The map document contains maps. If you delete the map documelll, any maps inside it aTe deleted too.

Navigming object model d iagrams means hopping around from one class to another. Now we'll consider how Ihis hopping is accomplished techn ically.

C lasses have propert k'S on their inte rfaces. When you set a property, you have to usc the right type of value. For example. on the ILayer interface of the L"lyer class below, there is a Name properry and its va lue must be set to a string. ILa yer also has a Visible property. which must be set to;! 8oo1e3l\ value {true or false).

CHJ\I"T£R 11 NJ\VIGJ\TING OBJECT MOIlEL 1)IJ\GIVoMS

Page 177: Getting to Know Arc Objects

.'i~'l I! Il) I H I I

I When you get property values you have to be ready to receive the right type of value. A programmer would St'ly that the Name properry Tellims a string and the Visible property retums a Boolean.

Some propcrrics return interfaces. For example. the MxDocument class below has a property caUed FocusMap that returns an IMap. (FocusMap te lls you which data fra me in the document is ac tive.) What this means is that FocusMap doesn't return a map object, but it returns a pointer to a map object's IMap interface. Through that pointer, you have access to the object's IMap properties and methods.

, __ r ". -.... •

On the diagram. a line connecting two classes tells you that you can get one object (well , the interface of the objt:ct) fro m another. To make the connection, a property o n the one object will re turn an interface of the connected object. Here the FocusMap property on IMxDocument returns the IMap interface of the connected map object. If you want to hop from the MxDocument class to the Map class, you get the FocusMap pro perty.

Let 's look at how to write the code that takes you from MxDocument to Map. Your starting point is the prcdeflnt:d ThisDocumem variable, which points to the IDocument interface on MxDocument.

ThkOocunwnt prlHlefiMCI

ghted material

Page 178: Getting to Know Arc Objects

• • •

I , I

Since m e FocusMap property is on IMxDocumcnt, you first have 10 use Qucrylnterface to switch interfaces. Declare a variable ro the interface you need , and set it cqu31 to the variable you already have.

Dim pMxDoc As IMxDocument Set pHxDoc = Thisoocument

Now that you have a variable that points to IMxDocument. you can gct the FocusMap property. S ince this property returns an IMap interface. you declare a new variable lO IMap.

Dim pMap AS IHap Se t pHap = pMxDoc.FocusMap

Thm's ir. You'v .... JUSt hopped from MxDocumcnt to MClp. If you walUoo (0 go on (0

work with a layer object, )'OU wo uld do the s.."lme thing: find a property in the Map class ( IMap has a Larer property) that returns an interface of the Layer class ( the Layer property re turns ILayer). Since Querylnterface isn '( needed here, it only takes two lines of code to b'O from Map to Layer.

Dim p Layer As ILaye r Set pLayer: pMap.Layer (ll

As long as c lasses are associated (connected with a line 01\ an obj!'Ct model diagram) , there will be some propcny th<.lt takes you from one to the other.

Maybe you aTe wondering how you' re supposed to know which classes are associated and which are not ! You find out by looking at o bject model diagrams. which arc poster-sized drawings that show not o nly c1asscs with their propcnies and methods. but also the relarionships berween c1asscs.

A single diagram is not big enough to ho ld all the A rcObjccts classes and their interfaces. In fac t, there are many diagrams, o rg::mizl..--d by categories o f classes. For example. the Geometry diagram contains classes for poi m s, lines, and poln:ons. The Gcodatabasc diagram contains classes for tables, fe<.lture classes. rows, and fi elds. If a class o n o ne diagram is connected [Q a class on a d ifferenr diagrnm, you will be referred [Q that diagram (jUSt as an atlas may refer you to a map on another page).

The fo llo wing object model diagram shows more than a hund red classes, o ne of wh ich is the Map class and its interfaces.

CUAI'TER 1 1 NAVl(';ATlNO OBJECT ~tO I)EL OIAGItAMS

Page 179: Getting to Know Arc Objects

-----

_. --

, , { ; \ '

The oval indicat~ that t he Map dass is ass()(i3ted with the !..lyer dass, which is found on t he Map layer dlClgrollm.

O bj\.'Ct model diagrams arc pretty detailed, but [hc~' only use about eight different symbols. Once you learn these symbols. and get a little practice, you'll be able 10

follow a diagram as easily as you would a street map. (Or ma},be morc easily!)

O bject model diagrams arc located in the developer help. If you don 't have the help lo.'1dcd on your computer, you can get the diagrams from the online developer help (arcobjccrsonlinc.esri.com). lf you have some wall sp.'lce, you can buy printed poste rs (ro m ESRI (www.csri.com/ExploringArcObjects}.And. finally, all the diagrams atc included on the Gelting to Know ArcObjccrs data CD as PDF fil es.

You now have the ccnrml idea about how to navigate ArcO bjCClS classes. As usua\' it 's no t quite the who le story. The association relatio nship that yo u've been learning about is actually JUSt one of three class relationships. Now we'll talk a linle bit about the o ther two.

Insum tintion . also calk-d the C reates relationship, is a relationship in which one class has OJ method that creates new objects from another class. Imagine a Shocmaker class with a C reateShoes method. Running this method creates a new object from the Shoes class and returns you its IShoes interfuce . ln UML, this relationship is shown by a dashed black line with an arrow that points to the created object. You won't inslantiate any objcclS in this chapter, but you will later in the book.

ghled rna\( ial

Page 180: Getting to Know Arc Objects

The third type of class relat ionsh ip is inheriumce. Inheritance is Whe!l [1 particular class US<.'S an interface (programmers say "implements" an interface) fro m a more gencml class.

Remember when in Ihe last chapter we mlh.-d aboUl grouping the Elephant class's properties o n lO different interfaces! Propert ies specific to elephants weOl on the IElephant interface , and propen ies that applied to all ani mals ",em on IAni mal, where they could be used by the G iraffe class, the Moose class, and so o n. On an object mcxlel d iagram , it wouldn 't be convenient to draw the IAnimal imerface on every class that used it- il would take up tOO much space. So prOj.Jrammcrs make a so-called absnacr class, and call it something like A nimal, and d raw the IAn imal interface on Ihis class.

" .: .

TIle point here is that Animal isn 't a full-blooded class. TIlere arc no Animal objects: there :m: only Elephant objl'Ct.s, Giraffe objl'Cts, Moose objects, and so on. The Animal class is nothing more than a schematic conven ience, a parking place (or an interface that is used by many different classes.

Inheritance is shown with solid black li nes and a triangle. Below, the tr iangle is on the L,yer class, wh ich means that the other connected classes inheri t all of L'lyer's interfaces (which in this case is just ILayer).

_ $_

" .... "

The FealUfeLa~er, RasterLayer. and TINLayer classes all inherit from the Layer class. This meani that all t h f~ cI.use, implement the ILa ~ er interface. which is drawn on the abstract Layer etass. Thl! triangle points to the abst ract clan (aliO called the superdan).

C HAPTER I I NA VIGATING OKj ECT MO!)ElIllAGRAMS

Page 181: Getting to Know Arc Objects

( ! I I I

Since you're going to work with abstract classes in th is chapter, let's sec how you write code for them. Suppose you want to create a new FeatureL'lyer and set irs Name property. The Name property is on the lLayer interface, which is shown on the abstract Layer class. But since the Fe3tureLayer class inherits this interface, you write your code as if you were seeing the interface on the FeatureLayer class.

Dim pLayer As ILayer Set pLayer : New FeatureLayer pLayer.Name : · USA "

This leads to a final point. The fa ct that there are different class relationships means that there are different ways to diagram classes. (You might havc noticed this in the previous diagrams. )

C<. , -- u",'

).{) wtlite bo.

AbstTllCl classes, likc the L'lycr class you wcre JUSt looking at , arc drawn as 2· 0 gray boxes. As mentioned before, no objects come out of abstract cla!ises. They are just parki ng spots for common interfaces.

Classes (which it's sometimes convenient to call regular classes. to distinguish them from classes in general) are drawn as 3·D white boxes. Objects from regular classes have to be instantiated-you can't create them yourself with the New keyword. If you want an object from a regular class, you have to find another class that knows how (has a property o r method) to make o r get these objects.

Coc/a.ues are drawn as 3·D gray boxes. These are the kinds of classes you're a lready fam iliar with. You can create obj/.'Cts from coclasses with the New keyword. You can also get these objects by using properties of other objects that rerum them.

'it J

material

Page 182: Getting to Know Arc Objects

, I • ,

,

• • I

Getting layers

In this exercise, you'lI ..... ritc some code that gelS the layers in a data frame and rums them off. This involves navigating from a starring point through several classes 10

get to the layer objects you w:mt. You 'll (a llow the path sho wn below. except that you'll stan with MxDocumcnt (where the proocfim .. cl ThisDocumcm variable is waiting for you) and skip the step of happing from Applicatio n to Mx Documc[)I,

• :: , dar

! , .. ' •

• ... -•

~,..

'1' • , ,

l ~ ~ '"'" _105 5 , I"" _ ~

o Iii' IiiUt ,-' __ '-'

• C '.-•• , .-. -... • ' _J

_1-' ..... . .. -ft ~a ·.

••• • 5.· ... . .. · ... m '.-

... A long the way. you'll do a couple offun t hings. You'll write a Fo r Each loop thm cycles through each layer in the drma {mme to tum it o ff. A nd you'll SC t Objl>C.t prop­cnies to update the wblt' of contents and the map display after the layers have been turned off.

You may be wo ndering ho w }'ou'li ever learn all the class re latio nsh ips o n rom own and be able to navigate easily fro m one class to anothe r. It can be a little overwhelm­ing at first , hut it's like learning rom \Va}' around a network of hiking trails. Yo u make some wrong rums. get lost :1 few times, but then you develop a sense of how every­thing is connected and it stan s to become automatic.

Surprisingly, you probably kno w more than you th ink about class relat ionships, because you h;we been an ArcGJS user. Fo r example, you might not need the d iagram above to (e ll you that Maps contain L,yers, because in your A rcG IS experience you have addl.>d hundreds o f layers to maps. You already kno w they have a relationship. If you've evcr deleted a map. you know the !a)'ers gel deleled (00.

CIIAI'1l!R II NAVIOATING DajECT >I OO£L Dlf"GKAM$

Page 183: Getting to Know Arc Objects
Page 184: Getting to Know Arc Objects

D In Acrobat Reader. zoom in on the Map class. near the layer oval, to match the graphic below. (The Zoom In tool looks like a magnifying glass. If necessary. adjust the zoom level using the other tools.)

The Map class is connected 10 the Layer class by a !,>Ta\' line with a diamond and a Slar. The d iamond tdls )'QU maps have layers; lhe stm s., )'s a tnllP can have many la ~'crs.

The Layer class is not shown on this d iag"un. [nste:ld. it appellrs inside :m oval {also known as a womlhole} with the name of the diagram . Map L,yer. that includes it.

Md)O(ul'Mnt dolil

t

o In Acrobat Reader. open Map layer Object Model.pdf in the C:\ArcObjects \ Diagrams fo lder.

Layer gets a d iagram to itself bccausc it has so many coclasses.

C IIJ\PT[II. I I NJ\VIGJ\TING OHJF.UT MQPEI. 111i\(lMMS

Page 185: Getting to Know Arc Objects

· .'i(let/un CW()

Next you' ll take a closer look at the class properties [ 0 see how rou can hop from one class to another.

II Sta rt ArcMap and open ex' 1a.mxd in t he C:\ArcObjects\Chapter1 1 folder.

D When prompted for a password, enter Carter.

The ArcMap window maximizes and you see the streets of Washington , D.C., and sc,rerai crime layers. On the Crime Analysis [ooJbar, a UIBunon callt-d ClearCrime has been added (or you. This is the button that will tum off all the layers.

II On the Crime Analysis toolbar. right-click Clear(rime and click View Source.

Visual Basic Editor opens and you see the C learCrime click event procedure. It is empty at the moment.

To start writing code, you need to locate a property on MxDocument that gets an object of the Map class. The FocusMap property returns the IMap interface (or the active map. (Remember, when we're using ArcObjccts, a map is a data frame. )

Since the FocusMap property is on the IMxDocument interface and the predefined ThisDocument variable points to the IDocument interface, you have to switch interfaces.

Gl 'lfillg /U) Y/ I S yrighted mal(rial

Page 186: Getting to Know Arc Objects

\

II Add two lines of code to swit ch to the IMxOocument interface.

Dim pMxDoc As IMxOOcumen t Set pMxDoc :: ThisDocument

Now thm you have a variable pointing to the lMxOoc.ument interface. you can get a map object in twO lines of code. by declaring II variable and serling il . You d~larc the variable as IMap. because the FocusMap property returns the IMap interface.

D Add two lines of code to get the active map f rom the map document.

Dim pMap As lMap Set pMap = pMxOOc. FocusMap

O nce you have a map object. YOli can get layers from rlml map with the Layer prop­erty, which is on the IMap interface of the Map class. The b ycr property has an argument that speci/i:es the layer's posit ion in th e table of contents. The lOp layer is at position 0, the second layer is at position I, and so on .

• ___ 1_ .....

D Declare an Ilayer variable.

You declare the variable as IL'lyer ix-cause the L'lyer property returns the ILayer interface.

Dim pLayer As ILayer

You will SCI Ihe pLayer variable inside a Fo r E.'lch loop. Each time th e loop nms, the variable will be reset to a different layer, until all layers are turned off.

CIIAI"TER II NAVI(lATIN(l 06J«'1" /-Iol)!!(. OIAORAM$

Page 187: Getting to Know Arc Objects

llllJll ru'CJ

IllJ Start a For loop that begins with 0 and ends with the position number of the map's last layer.

For i = 0 to pMap.LayerCoun t - 1

Next i

Thc fo rmula pMap.LaycrCount - 1 gives you the index position of the last layer. no man er how many laycrs a map contains. For example, in a map with ten layers, the fi rs t l a ~'c r is a l position 0 (the fi rs t item in most ArcObjects lists is number zero) and the las t is at position 9. L,yerCount - I equals 9.

m Inside the loop (before Next i), add a line of code to set the layer variable.

Set pLayer = pMap . Layer(i)

The layer's index number is stored in the variable i. which contains a 0 the first time through the loop. That will get the fi rst laycr on the map. The value of i will incre­ment b\' 1 until there are no mo re layers in the map.

O n thc Layer diagram below, you can see that the lLayer interface has a Visible property. You tum layers on and off by setting the Visible property to true or fa lse .

• -I- Vo •• , . , prope:rt~

m Add another line of code to turn the layer off.

pLayer. Visible = False

~ ... ...... ' .... k . . ... . . .. """ • • .., .... .

' ''r • _ 0 To . .... "" ... ..:0 .... _ 1

,

-

Page 188: Getting to Know Arc Objects

A lthough your code affects both the A rcMap table of conten ts and the map display, dH.ose pans of the application do not change unless explicitly to ld to do so. You will add some code to redraw these areas.

Tlble of (on ttnll

'" PI. """ _ ~. , 1" _ !lIIo

.............. • ·0 ... . ..

• - Ii! "" •• "'

. 0 .. " .. -.--

r )',. • + I, mJOl :::J

•• •

MOO di\PlWf

m Outside the loop. after the Next i line and before the End Sub line, add the following line of code.

pMxDoc .UpdateContents

The UpdatcCom em s method on the IMxDoc:ument inrcrfrlce redraws the table o f contentS, but not the map display.

To redraw the map dispby, you need the IActiveVicw interfrlcc on the Map class. You can get there using the ACliveView propcrt \' on IMxDoc:umcnt.

Page 189: Getting to Know Arc Objects

.'\~l Cion tu'o

Once you ge[ [Q IAcriveView, you run irs Refresh method [ 0 redraw the map display. (Since the IAc[iveView interface is found on both the Map and the PageLayout classes as shown below, the C learCrime burton will work whether the user is in data view or layout view. In one case, the map display redraws; in the other, the vinual page redraws.)

- .",,,., ~,"'"

-"" ,,,., ~,"'"

III Declare and set a variable for t he map display.

Dim pActiveView As IActiveView Set pActiveView : pMxDoc.ActiveView

You can do this bcCliUse the pMxDoc variable points to the lMxDocumcn[ interface, which h:lS the ActiveVicw propeny.

Ii) Add a line of code to redraw the map display.

pAc tiveview.Refresh

After this line of code runs, all layers disappear from the map display.

' 0. , • C to ... , .•• ,..Co .... 1 Su .1..0,. . . ....... ,.. 11 ' .I..o,. •. v,."" • . , .. ..

.... 1 ... _._,ou ..... . ~ .. . 0<"" ..... , ..... , ......... v, •• I . . ... u .. v ... . ... _._ .... v .. .

.... ,_ .... ... fr •• ~

The code is ready to test.

m Close Visual Basic Editor.

m Turn all layers on by checking their boxes.

III Cl ick the ClearCrime button.

Get/IIII-: Itl)t·,"S

1. 1"'" ...-1

,- yrighl:!d ma,

Page 190: Getting to Know Arc Objects

All the layers tum of(.

iD Turn all the layers back on by checking their boxes.

Now that you have a bun on [Q rum of( all the layers, you no longer need the table of contents (or this purpose. You'll gel rid of the lable of contents and teS[ the button ag'lin.

m Click the View menu and click Table of Contents.

Turning off the table of contents leaves you with more viewing space. If you had a bunon to tum lhe layers back on , you could uS<' the application without duo TOC.

m Click the ClearCrime button.

All the layers tum off again.

m Turn the table of contents back on and turn all the layers back on .

,

• 0-

O~ -o~~._ • III .... '_ 0.-0--

111"0'" -, , ._- -

-- --" " ' .. :, ;o. ~"'~~ _ -"'f -- -:. ~~­, -,

As an experiment. go b.'1ck to the code and comment Out the line that runs the UpdrltcContents method. Tl'CI) click the C learCrime bunon aga in to sec thllt the table of cOntents check boxes remain c hecked. C lick the Source and Display labs at the bottom of the table of contents to force it to rl'(lraw. Go back and uncommcnt the Upd:ltcCont('ntoS line of code.

CIIAI'T1!R II NAVIGATING 08)EC'T MapEL DIAGRAMS

Page 191: Getting to Know Arc Objects

"L't {I,})l r It!1

As another experiment, make a second bunon called AIICrime. Copy all the code from ClearCrime's click event to AIICrime's click event. Find the line of code in the For E.1ch loop that sets layer visibility to False and change it to True. Try using your two new buttons together.

W If you want to save your work, clkk the File menu in ArcMap and click Save As. Navigate to C:\ArcObjects\Chapterll . Rename the file my_exl1a,mxd and clkk Save. If you are continuing with the next exercise, leave ArcMap open. Otherwise close it .

yrighted material

Page 192: Getting to Know Arc Objects

Creating and assigning colors

Color is an int egral pan of making a map. You assign color 10 a laycr's features, to text and graphics on a layom's page, and to the la)'ou t page itself. In ArcObjccls, each color is an object that you c reate and then set propert ies for. The simplified diagram below shows the Color abstract class and five coclasses.

" : ' I

E.'l.ch coclass represents a color model. Computer monitors display color with red, green, and blue light, so if ~'OU arc making maps for the Internet, you would make colors with the RgbColor coclass. If your maps will be printed on paper, you would make colors with the CmykColor coclass because CMYK (cyan, magenta, yellow. black) is a color model standard in the prim industry.

Each color coclass has propcnics that you set to mix and make a color. The RgbColor coclass has red, grecn, and bluc properties.

The values (or each property range from 0 10 255. (Wh)' this rangd Because a compUler slores 256 valucs in one bYle o( memory.)

To make a sand\' yellow color with Ihe ArcMap user inlerface, you would set slider bars (or type in values) as shown below.

O IAPTER r r NAVIGATINO 0 6jF.CT MOIli!l IlIAORAMS

Page 193: Getting to Know Arc Objects

sectIon two

To make (he same color with ccxle, you set the properties of an RgbColor object:

pRgbcolor.Red : 255 pRgbcolor.Green : 255 pRgbColor.Blue : 190

In this exercise, you will change the background color of a layout page. By default this color is white, but you can change it to an~,thing you like.

, ,

'.

'- Ej'-- -, - -The layout page color has bun dlanged from white to blue.

As in the previous exercise, you have to navigate to the object you w3nt to work with- in this case, a color object on the layout page.

lip; ' zllon

• LoY'"

''''

As before, you'll Start with the MxDocument class, bUl this time you'll hop to Page L1YOU1, and then to Page. At that point, you'll need to look at another diagram to see the Color classes.

Page 194: Getting to Know Arc Objects

I , •

When you get to the RgbColor class. you' ll c reatc a new color and SCI it equal to the Page's b3ckground property. After thai , you' ll refresh the display as you did in the last exercise.

Exercise 11b You work (or an adventure recreation company that organizes vacations to inlerest­ing places (or windsurfing, desert survival hikes. and o ther rugged act ivities. For each trip that gets organized, you make the supporting maps. You wam the background colo r of your map to reflect Ihe theme of the vacat ion. If it's near \\,311: r, the page colo r should be blue; if it 's a desert lour, the page color should be s;md~' brown .

Before writ ing any code. you will examine the A rcMap object model diagram to detcnnine which objects to use.

D If you need to, start Adobe Acrobat Reader and open ArcM ap Object Modelopdf from the C:\ArcObjects\Oiagrams folder.

To change the page color, you need to find a path from MxDocument to Page. On the large diagram below, MxDocument is connected to PagcL'tyout ... nd PageL'tyout is connected to Page. So in twO lines of code you can hop from Mx Document to PagcL'tyout. and in rwo more lines you can hop from PagcL:.lyout to Page.

----M~OOcumenl - _

. .,. -

C IIAI"TER I I NA VIGAT ING ObJECT MODEL l)lAGRAM S

Page 195: Getting to Know Arc Objects

SL'ctlCJn ttVO

D Zoom in on the Page cotlass.

The Page class has the S.,ckgroundColor property, which is whal you want 10 sct. S ince [he Badc.groundColor property requires the IColo r in[crface. you need to gct an object that has this interface.

'"'' ~ '----+ - ''''''OO'''''''~ ~"",ny

In theory, you should sec a line connecting the Page class [ 0 a class that implementS IColor. But you don 't, because on crowded d iagrams, like th is one, some connected classes can't be shown. To find classes that implement IColor, you might highlight IColor in the code window and press FI to open the IColor page in the A rcObjccts developer help. shown below .

... ... -. .. ---D ....... ...

"" om: ..... of_ _ GooClU. ... .ho ca.oI ..... of _

... "IC , --.... -.. __ ...... , .. _ ....... -_ ....... _of_

.... , ... , . , .. _ ........... (O hrna: ad,H' lilt = .... ).

... .... . " 7 .. _ _;t ____ 00_=_ -. ............. , ........ _--_ ............. _ ... "'--, ~_",'_ 'OJ ' " • ..,..

'W"'" .. _"""'... a ..... ' ..... C ,' C " " _¢H"C'" ..... ' , """c. ..... , .. c ' -~- ---------------

Cmlli llg m ul (/$Sfg ll fl/g colors

Page 196: Getting to Know Arc Objects

1

The help page shows fi ve colo r coc lasses. You can click each of them to sec wh ich interfact'S they support and lists of propen ics and methods. But what if you wam to sec these color classes on an objecr model diagram r

Locat ing a class o n one of the twenty o r so object model diagrnms can be like finding a needle in a haystack. Fortunately. there is an easy search method.

o In Acrobat Reader, open AIiOMDs.pdf in the C:\ArcObjects\Diagrams folder.

In the AllOMDs.pdf file. each diagram is bookmarked in the list at the left.

Book"",kt 101" u{hdi~f .. m

" 5

p :

The Find bunon (called the Search bunan in Adobe Rcadcr"6.0) will find any word o n any diagram and highlight it in blue. Befo re do ing any finding. \'OU will need 10

zoom in far enough 10 read the words.

U In Acrobat Reader, click the View Menu and click Actual Size.

o Click the Find button (the b inoculars icon at the top). In the Find dialog box. type RgbColor and click Find.

The Acrobat Reader display area centers on the RgbColor cociass, wh ich is also highlighlcd for you.

CiI"PT£R. r I N"\' IO"TING OBltl-r MOU£L I)IACAAMS

Page 197: Getting to Know Arc Objects

Sl!CC1(}n CW(}

-_. -­_. ----RgbCoIOI' codau

D Use the Hand tool (it looks and works l ike the ArcMap Pan tool) to move the RgbColor (odass to the lower right corner of the d isplay, so you can see all the Color classes.

., , .

-t- Fiyoe color coct.n~ &lIlnl'w!rit lhe ICoior intmM:1!

You now know which classes (Mx Oocumcnt, PagcL,yout, Page, and RgbColor) are needed to get the layout page and s('[ its color. Next you will write the code to set a new page color.

Crt.'fJliIJg tllld lIssiSlIIlIB colors

, I' , .

-, , J

yrl hl~ m na'

Page 198: Getting to Know Arc Objects

D Start ArcMap and open ex11b.mxd in the C:\ArcObjects\Chapter11 folder.

When the map opens }'ou see potential vacation sites in the country of Belize.

-Ii'! • 5 __ _

0 -

.... • e "

o

. ...... Got • •

o Switch from Data View to Layout View,

On the La}'out toolbar, a new menu called Page Color has been added for }'OIL h contains one choice, a UIButton called BluePagc. You will code this button to set Ihe background color of rour layoul pllge.

o Click the Tools menu and click Customize.

m On the layout tool bar, click Page Color, right-click on SluePage. and click View Source,

You see an emply click event procedure.

m Add the following code to get to IMxDocument.

Dim pMxDoc As IMxDocument Set pMxDoc = ThisDocument

m Add two more lines to get the page layout.

Dim pPageLayout As IPageLayout Set ppageLayout = pMxDoc.PageLa you t

CUAPTER I I NAVIGATINC OBJECT J-IOPEL "DIAGRAMS

Page 199: Getting to Know Arc Objects

m Add two more lines to get the page.

Dim pPage As lPage Set pPage = pPageLayout.Page

To make a color object , you use the Set and New keywords.

m Create an RgbColor object to serve as the background color of the page.

Dim pRgbColor As lRgbColor Set pRgbCo lor = New RgbCol o r

, .. "", . .... u .... _ _ u.~.n

JI_ . ............ ro . •• k ......... nuT ' ..

~ .... _ ............ -~ ...... ... •• _ ............. _._h,.. ... ~ .. ,,_ .... -k . ,._ • • _ ... ,....,._

~ .. '~'O' " .~I .. ... • JgbCo lo. - ... JgbCO'OI

m Set the Red, Green, and Blue properties to get the desired shade of blue.

pRgbColor.Red = 100 pRgbCo1or .Green = 150 pRgbColor.B1ue = 255

The color propenies you just set are found on the IRgbColor interface. But recall fro m step 2 that the BackgroundColor propcny returns the IColor interface. Th is means )'ou must usc Qucrylnlcrfacc [ 0 switch (TOm IRgbColor [0 IColor. (TIle prin­ciple of inheritance tells you that you can do this. The RgbColor coclass implements all the interfaces shown on the lColor abstrnct class. )

m Declare an IColor variable and set it equal to the variable that is already point ing to the RgbColor object.

Dim pCeler As leeler Se t pCeler = pRgbCeler

m Assign the color to the page's BackgroundColor property.

pPage.BackgreundCoior = pCo l e r

yrl hl~m n

Page 200: Getting to Know Arc Objects

ID Get and refresh the page layout's display. (As with the map display, you use the IActiveView interface to do this.)

Dim pAc tiveView As IActiveView Set pAc tiveView = pPageLayout

pActiveVi ew.Refresh

._.1.00 ...... . . 00

.................. . . 10

....... . 0 . . .... . III

~ .. "' .... .. . eo '.' ... ,eel.' • ,_. '0 •

... ,"" .. VI .. .. , .. " ... VI • • '0< ....... v, ... .. _ c . .... .

... " ... v l ......... 111

••

The code is ready to lest.

m Crose Visual Basic Editor.

fIll In ArcMap. on the layout tool bar, click Page Color and click BluePage.

The page color changes to blue.

~ .. "",- -- --" 0.

""'''iI -.' , • . ~ • . - '--

0- = __ .---

,

+

._--, --- --

! ~ ·14.II_

CII APT('1t I I NAV1GATINO ORI ECT ,",O!)El OIACRAMS

Page 201: Getting to Know Arc Objects
Page 202: Getting to Know Arc Objects
Page 203: Getting to Know Arc Objects
Page 204: Getting to Know Arc Objects
Page 205: Getting to Know Arc Objects
Page 206: Getting to Know Arc Objects
Page 207: Getting to Know Arc Objects
Page 208: Getting to Know Arc Objects
Page 209: Getting to Know Arc Objects
Page 210: Getting to Know Arc Objects
Page 211: Getting to Know Arc Objects
Page 212: Getting to Know Arc Objects
Page 213: Getting to Know Arc Objects
Page 214: Getting to Know Arc Objects
Page 215: Getting to Know Arc Objects
Page 216: Getting to Know Arc Objects
Page 217: Getting to Know Arc Objects
Page 218: Getting to Know Arc Objects
Page 219: Getting to Know Arc Objects
Page 220: Getting to Know Arc Objects
Page 221: Getting to Know Arc Objects
Page 222: Getting to Know Arc Objects
Page 223: Getting to Know Arc Objects
Page 224: Getting to Know Arc Objects
Page 225: Getting to Know Arc Objects
Page 226: Getting to Know Arc Objects
Page 227: Getting to Know Arc Objects
Page 228: Getting to Know Arc Objects
Page 229: Getting to Know Arc Objects
Page 230: Getting to Know Arc Objects
Page 231: Getting to Know Arc Objects
Page 232: Getting to Know Arc Objects
Page 233: Getting to Know Arc Objects
Page 234: Getting to Know Arc Objects
Page 235: Getting to Know Arc Objects
Page 236: Getting to Know Arc Objects
Page 237: Getting to Know Arc Objects
Page 238: Getting to Know Arc Objects
Page 239: Getting to Know Arc Objects
Page 240: Getting to Know Arc Objects
Page 241: Getting to Know Arc Objects
Page 242: Getting to Know Arc Objects
Page 243: Getting to Know Arc Objects
Page 244: Getting to Know Arc Objects
Page 245: Getting to Know Arc Objects
Page 246: Getting to Know Arc Objects
Page 247: Getting to Know Arc Objects
Page 248: Getting to Know Arc Objects
Page 249: Getting to Know Arc Objects
Page 250: Getting to Know Arc Objects
Page 251: Getting to Know Arc Objects
Page 252: Getting to Know Arc Objects
Page 253: Getting to Know Arc Objects
Page 254: Getting to Know Arc Objects
Page 255: Getting to Know Arc Objects
Page 256: Getting to Know Arc Objects
Page 257: Getting to Know Arc Objects
Page 258: Getting to Know Arc Objects
Page 259: Getting to Know Arc Objects
Page 260: Getting to Know Arc Objects
Page 261: Getting to Know Arc Objects
Page 262: Getting to Know Arc Objects
Page 263: Getting to Know Arc Objects
Page 264: Getting to Know Arc Objects
Page 265: Getting to Know Arc Objects
Page 266: Getting to Know Arc Objects
Page 267: Getting to Know Arc Objects
Page 268: Getting to Know Arc Objects
Page 269: Getting to Know Arc Objects
Page 270: Getting to Know Arc Objects
Page 271: Getting to Know Arc Objects
Page 272: Getting to Know Arc Objects
Page 273: Getting to Know Arc Objects
Page 274: Getting to Know Arc Objects
Page 275: Getting to Know Arc Objects
Page 276: Getting to Know Arc Objects
Page 277: Getting to Know Arc Objects
Page 278: Getting to Know Arc Objects
Page 279: Getting to Know Arc Objects
Page 280: Getting to Know Arc Objects
Page 281: Getting to Know Arc Objects
Page 282: Getting to Know Arc Objects
Page 283: Getting to Know Arc Objects
Page 284: Getting to Know Arc Objects
Page 285: Getting to Know Arc Objects
Page 286: Getting to Know Arc Objects
Page 287: Getting to Know Arc Objects
Page 288: Getting to Know Arc Objects
Page 289: Getting to Know Arc Objects
Page 290: Getting to Know Arc Objects
Page 291: Getting to Know Arc Objects
Page 292: Getting to Know Arc Objects
Page 293: Getting to Know Arc Objects
Page 294: Getting to Know Arc Objects
Page 295: Getting to Know Arc Objects
Page 296: Getting to Know Arc Objects
Page 297: Getting to Know Arc Objects
Page 298: Getting to Know Arc Objects
Page 299: Getting to Know Arc Objects
Page 300: Getting to Know Arc Objects
Page 301: Getting to Know Arc Objects
Page 302: Getting to Know Arc Objects
Page 303: Getting to Know Arc Objects
Page 304: Getting to Know Arc Objects
Page 305: Getting to Know Arc Objects
Page 306: Getting to Know Arc Objects
Page 307: Getting to Know Arc Objects
Page 308: Getting to Know Arc Objects
Page 309: Getting to Know Arc Objects
Page 310: Getting to Know Arc Objects
Page 311: Getting to Know Arc Objects
Page 312: Getting to Know Arc Objects
Page 313: Getting to Know Arc Objects
Page 314: Getting to Know Arc Objects
Page 315: Getting to Know Arc Objects
Page 316: Getting to Know Arc Objects
Page 317: Getting to Know Arc Objects
Page 318: Getting to Know Arc Objects
Page 319: Getting to Know Arc Objects
Page 320: Getting to Know Arc Objects
Page 321: Getting to Know Arc Objects
Page 322: Getting to Know Arc Objects
Page 323: Getting to Know Arc Objects
Page 324: Getting to Know Arc Objects
Page 325: Getting to Know Arc Objects
Page 326: Getting to Know Arc Objects
Page 327: Getting to Know Arc Objects
Page 328: Getting to Know Arc Objects
Page 329: Getting to Know Arc Objects
Page 330: Getting to Know Arc Objects
Page 331: Getting to Know Arc Objects
Page 332: Getting to Know Arc Objects
Page 333: Getting to Know Arc Objects
Page 334: Getting to Know Arc Objects
Page 335: Getting to Know Arc Objects
Page 336: Getting to Know Arc Objects
Page 337: Getting to Know Arc Objects
Page 338: Getting to Know Arc Objects
Page 339: Getting to Know Arc Objects
Page 340: Getting to Know Arc Objects
Page 341: Getting to Know Arc Objects
Page 342: Getting to Know Arc Objects
Page 343: Getting to Know Arc Objects
Page 344: Getting to Know Arc Objects
Page 345: Getting to Know Arc Objects
Page 346: Getting to Know Arc Objects
Page 347: Getting to Know Arc Objects
Page 348: Getting to Know Arc Objects
Page 349: Getting to Know Arc Objects
Page 350: Getting to Know Arc Objects
Page 351: Getting to Know Arc Objects
Page 352: Getting to Know Arc Objects
Page 353: Getting to Know Arc Objects
Page 354: Getting to Know Arc Objects
Page 355: Getting to Know Arc Objects
Page 356: Getting to Know Arc Objects
Page 357: Getting to Know Arc Objects
Page 358: Getting to Know Arc Objects
Page 359: Getting to Know Arc Objects
Page 360: Getting to Know Arc Objects
Page 361: Getting to Know Arc Objects
Page 362: Getting to Know Arc Objects
Page 363: Getting to Know Arc Objects
Page 364: Getting to Know Arc Objects
Page 365: Getting to Know Arc Objects
Page 366: Getting to Know Arc Objects
Page 367: Getting to Know Arc Objects
Page 368: Getting to Know Arc Objects
Page 369: Getting to Know Arc Objects
Page 370: Getting to Know Arc Objects
Page 371: Getting to Know Arc Objects
Page 372: Getting to Know Arc Objects
Page 373: Getting to Know Arc Objects
Page 374: Getting to Know Arc Objects
Page 375: Getting to Know Arc Objects
Page 376: Getting to Know Arc Objects
Page 377: Getting to Know Arc Objects
Page 378: Getting to Know Arc Objects
Page 379: Getting to Know Arc Objects
Page 380: Getting to Know Arc Objects
Page 381: Getting to Know Arc Objects
Page 382: Getting to Know Arc Objects
Page 383: Getting to Know Arc Objects
Page 384: Getting to Know Arc Objects
Page 385: Getting to Know Arc Objects
Page 386: Getting to Know Arc Objects
Page 387: Getting to Know Arc Objects
Page 388: Getting to Know Arc Objects
Page 389: Getting to Know Arc Objects
Page 390: Getting to Know Arc Objects
Page 391: Getting to Know Arc Objects
Page 392: Getting to Know Arc Objects
Page 393: Getting to Know Arc Objects
Page 394: Getting to Know Arc Objects
Page 395: Getting to Know Arc Objects
Page 396: Getting to Know Arc Objects
Page 397: Getting to Know Arc Objects
Page 398: Getting to Know Arc Objects
Page 399: Getting to Know Arc Objects
Page 400: Getting to Know Arc Objects
Page 401: Getting to Know Arc Objects
Page 402: Getting to Know Arc Objects
Page 403: Getting to Know Arc Objects
Page 404: Getting to Know Arc Objects
Page 405: Getting to Know Arc Objects
Page 406: Getting to Know Arc Objects
Page 407: Getting to Know Arc Objects
Page 408: Getting to Know Arc Objects
Page 409: Getting to Know Arc Objects
Page 410: Getting to Know Arc Objects
Page 411: Getting to Know Arc Objects
Page 412: Getting to Know Arc Objects
Page 413: Getting to Know Arc Objects
Page 414: Getting to Know Arc Objects
Page 415: Getting to Know Arc Objects
Page 416: Getting to Know Arc Objects
Page 417: Getting to Know Arc Objects
Page 418: Getting to Know Arc Objects
Page 419: Getting to Know Arc Objects
Page 420: Getting to Know Arc Objects
Page 421: Getting to Know Arc Objects
Page 422: Getting to Know Arc Objects
Page 423: Getting to Know Arc Objects
Page 424: Getting to Know Arc Objects
Page 425: Getting to Know Arc Objects
Page 426: Getting to Know Arc Objects
Page 427: Getting to Know Arc Objects
Page 428: Getting to Know Arc Objects
Page 429: Getting to Know Arc Objects
Page 430: Getting to Know Arc Objects
Page 431: Getting to Know Arc Objects
Page 432: Getting to Know Arc Objects
Page 433: Getting to Know Arc Objects
Page 434: Getting to Know Arc Objects
Page 435: Getting to Know Arc Objects
Page 436: Getting to Know Arc Objects
Page 437: Getting to Know Arc Objects
Page 438: Getting to Know Arc Objects
Page 439: Getting to Know Arc Objects
Page 440: Getting to Know Arc Objects