You are on page 1of 440

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 v a l ~ 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
UnderstAndi ng ArcObllhb
Chapter 9 MakinQ your own objects 133
9a CrPating 136
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
Chapl er 11 Navigating object model diagrams 171
Exefcise l1a Getting 178
Exercise lib Creating and assigning colofs 188
Chapter 12 Making tools 199
Exercise 12a Reporting coordinates 200
12b Dr"....,!"!!! graphics 211
Exercise 12c Using TypeOf statements 221
3 Using Ard)blecb
Chaoter 13 Executing commands 227
Exercise 13 lkinq COITlI1\olll!!Items all!! 228
Chapter 14 Adding layers to a map 239
Exercise 14a Addin9 a qeodatabase leatUie 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
17a Making definition queries 318
Exerci!.t! 17b $electing features and seiling the color 332
Chapter 18 Worki ng with selected features 339
Exercise lSa Using selection sets 342
Exercise lab Usin9 cursors 348
CONTENTS
CONTENTS
Chapter 19 Making dynamic layouts 359
Exercise 19a Naming tlelTlfl1ts 362
19b Manipulating eierT'oellts 370
Chapter 20 Editing tables 377
20a Adding 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
Why learn how to program ESRI ArcObjects"' !
Thi nk of ArcGIS as a house that someone else has buil t and furnished for you. You
move in and find that it has 10[5 of rooms, great furn iture, all the conveni ences,
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 ArcCatalog'" your own. You may not even want to change them too
much. Maybe remove a tool that you never use from a tool bar. Or take a cert ain
menu choice and put it on a bulton. Or reduce some repet iti ve task to a si ngle
button click.
On the other hand. you might have plans to remodel the whole house.
Whatever the scope of your ambition, getting to know ArcObjects-and the
concepts behind programming them-wi ll give ~ ' o u a new level of confidence in
your relat ionship wi th the software.
If you have li ttle or no programming experience, begin with the book's first section.
"Understandi nG" VBA." There you' lIleam about objects, properti es, and methods;
how to set variables; how to wri te procedures and li nk them to buttons on the user
interface; how to use simple objects like message boxes; and how to employ program-
mi ng constructs li ke If Then statements and Do While loops.
If ~ ' o u are already comfortable with an object-oriented language, especiall y Visual
B.'lsic- (or Applications (VBA) or Mi crosoft- Visual Basic, you may want to start
wi th the second section, "Understanding ArcObjects." There you' lIleam about
the ArcObjects architecture, how to read object model diagrams, and how to use
righted material
programming intcrfaccs. (If you havc a good idca what t hc last sentcncc is talking
about , you probably know enough to skip the first section.)
The third secti on of the book, "Using ArcObjects," leads you through a number of
GIS 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 int roductory discussions,
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, however, wi th even
the small est of typi ng mistakes. (But every mistake is an opportunity to learn.) If
exercise code does fuil, you can go through 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 you don't have to because
each exercise is a new staning point, al ready prepared wi th maps, data, and any
VBA code you nced. This is true even when the exercises build, as they often do, on
work you have done previously. Every exercise .. Iso incl udes a map document wit h
the correct results, in case you get stuck. Each chapter has frolll one to four exercises
(except for chaptcr I , which has none). The exercise Icnb'th varics, but as a rul e,
chapters should take twO to four hours to complete.
To usc (his book, you must have a copy of ArcVicw , ArcEdiror"', or Arclnfo'"
version 8.3 (or a later version) running on your computer. The map documents used
in thc exercises wi ll not open on carlier vcrsions of the software. The CD thai comes
with the book contains the exercise data you need, pl us addi tional resources, but
does not include the software itself. For instructi ons on installing the dam, refer ro
appendix B.
For t he latest information, Q & A's, addenda, and errata, visit the book's companion
Web site at wtllw.esri .com/GTKArcObjects .
I NTllQDUCTrpN
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 Appli cations! 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 helpful unless you know whm objcctoriemed
programming is.
Objed-orlellted pi ogrammlng
Object -oriented programming is a structure or design for computer programming
languages. It resembles our own experi ence of the world. We see the world as divided
into objects that have qualities, or properti es, 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, or 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 rustl e in the wind or shed leaves in the full. It grows from a li ttle seed.
One day it dies.
Similarly, 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 speciali zed. 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
The syntax of these instructions varies somewhat from language to language. but the
bnsic form is "Object.Method." (The peri od is pronounced "dot.") First comes the
name of the object, then comes the behavior that ~ ' o u want from it. For example. to
add a record to a table object, you would write something li ke:
Table. AddRecord
To make a tree object drop its leaves, )'ou would wri te somethi ng 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 other.
What makes object-oriented programming interesti ng and ri ch is that objects have
relati onsh 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 might be able to wri te an instruct ion to create a
ut.'C object (Tree. Crente) but not to create a branch object. Branch.Create doesn't
work because branches don' t exist independentl y of trecs----and this is defi ned by the
propert ies and methods of your objects. Instead, to make a branch. you fi rst create a
tree and then run its OrowBranch method.
Tr ee.Creat e
Tr ee.GrowBranch
If you want to make an apple, it mi ght be Trt'(' .Create, followed by Tree.GrawBranch,
followed by Br.mch.GrowApple.
Suppose you want to be elaborate and make a boy object 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{AnAppl e )
When the boy eats the apple, consequences ensue. For example, the apple will no
longer exist and the bo)" s IsHungry property might change from Yes to No.
You can sec that in object-oriented programming. it's important to learn the
relationships among the objects you work wi th: which ones you can make. which
ones make others. which ones have ..... hich 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 .... arion of a special
system (or diagramming them. You will stan seeing these diab>rams in the sc<:ond part
of the book. They look like this:
CIV,PTI!R I PROGRAMMING WITII OI:lJECTS
'.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 diagrams, 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 cannot accommodate them, you can purchase a bundle of printed
copies at www.esri.com/ ExploringArcObjects.
Visual Basic for Applications (VBA)
Vi sual B'lsic for Applicat ions, a Si mplified version of Vi sual Basic. is one of many
object-ori ented programming languages. You can use Other languages to program
ArcObjects (like C++ or Visual Basic), but VBA comes included with AreGIS
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 appli cations. Program-
mers working in languages like C++ typically build software appli cations from
scr:ltch with a set of objects, while VBA programmers customize applications, like
ArcMap, that come wi th VBA inside them. YBA programmers can use as much of
the applicati on's built-in functionality as t h e ~ ' want.
VBA has its own set of development tools. many of which you will use in this book.
For example. it has windows for organizing and sroring the code you write; tools for
creating dialog boxes and their components (buttons, drop-down lists. scrolling
boxes, and so on); and tools for debugging code.
Code is organized in procedures. A procedure includes all the instmct ions needed to
accomplish some clearly defined task, like printing a map or maki ng a boy eat an
apple. Procedures can be linked to each other so thar when one fin ishes it tells
ight I,
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 chai n of procedures calling one another, but the first link
in the chain requires a human touch. Actions like opening an applicati on, clicking
a button, or 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 butt on


""
A
.,
Arc:Objecb
Code n.ms

... ....... , = .< ...
... ... "...., ... .. "'" ..... v
.. . .... __ ... n _ _
... . .. "....v .... . ... _ _ . , ....... .
.... ...., . l ..... . ....... n . h u .. '""
..... ...., .......... -
... ....
ArcObjeclS are a set of computer objects specifically dcsign(..-d for progrnmming with
ArcGIS 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 ArcGIS user, you have been using ArcObjects all along. C lick the Save bunon
in ArcMap and a procedure runs to S<1ve your map document. Click the Draw Point
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, and the point graphic are all
ArcObjects. In fact, ArcMap and ArcCatalog arc both built from ArcObject:5.
In rhi s book, will use ArcObjects to cuslomi ze 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 appli cations as well. Thanks to a design standard call ed
COM, which provides guidelines to the programmers who develop objects, you can
use ArcObjecrs to put map functionality in applications like Microsoft Word or
Microsoft Excel (and you can also PUI word-processing or spreadsheet funcriQnality
in ArcMap).
On(' thing you won't do in this book is masler [he uni verse of ArcObject.s-there are
far too many of them. You will get to know a. lot of the common ones, however.
More impormntly, you' ll get 10 know the principles 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 ArcObjects on your own.
Ctl AI'TER I wtTIi OllJECTS
Building a custom application
Orgallitillg CUIIUrn.lnJ$ OI l U roollx,r
Makillg ),Ollr Qtl'l l communds
Sfllting 1'llllI ts with
ArcMap and ArcCaralog have plenty of toolb.'us, menus, and commands (buttons
and tools), enough and more for most users' needs. However, they will never have
everythi ng that everyone needs, and will always have something that some people
simply do not. Fortunately, with a li ttl e training 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 nO one could ever have predicted you'd need.
Ml ln

-
ight
I
,
I
,



I



,

I

,
,

,



,
I
I
L
Some of your ArcObjecrs work 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 long enough, there arc prob.1bly some repet itive
actions you do on a dail y or weekly basis. Maybe you make a lot of fcature selec-
tions 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 ..
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 loolba'
When you need a completely new functi on , you can create own bun ons and
lOois and pm thcm on tooibars. And then you gCt to wri te code for them.

I
Yo"" new bunon
CHAf'TER l BUI LDINC A CUilTOM AI'PLICAnON
\ l' l I I
Organizing commands on a toolbar
The graphi c user interface (GUI) for ArcMap and ArcCaralog is made up of
toolbars, menus, and commands. Toolbars conmin commands or menus. Commands
come as either buttons or tools. Menus provide pull-down Iisls of commands or of
other menus.
AtcMap toollwf
. . ""
Command - -<'I. Com",,,,"
...
' .. ,;' .
" ....
Aq, , !B It\dof
D 5' .. III
RIUtt ... n, !!I II\dgIJ o-n
M .. nu Mtnu
To make changes [ 0 the user interface, you use the Customi ze 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 Customize dial og 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
Exen::ise 2a
You arc a GIS programmer for the planning dcparrmcill of Man hanan, Kansas.
When pt.'Ople come 10 the planning department office for parcel maps, a planning
depanmelll staff member uses ArcMap 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
appli cati on that anyone can usc.
Users of the parcel viewer application will need to find parcels, label them wi th
identifi cation 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 ent ire ci ty. In ArcM"p, you' ll
creme a toolbar with commands for onl y those acti ons.
D Start ArcMap and open ex02a.mxd in the C: \ ArcObj ects\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 different folder or drive, go there
now, locate the Chapter02 folder, and open the map.
The m<'lp cOnl <'lins I"yers for the cil Y boundary, p<'lrcels, and streets.
Q Cli ck the Tools menu and click Customize. Click the Toolbars tab, unless it's
already active.
On the Toolbars tab, checked tool\).1rs arc visible, unchecked arc nol. Your li st of
tool bars will vary according [0 whi ch ArcGIS 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
.
'\l ((Itln (llll?
II Replace the toolba r name with Parcel Viewer. Make sure ex02a.mxd is selected
under Sa ... e in.
ji'--
D Click OK.
Parcel Viewer is added to the li st 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 Fi nd from t he Tools tool bar to t he
Parcel Viewer t oolbar. (If your Tools toolbar is not di splayed, you can go t o t he
Toolbars tab of the Customize dialog box and check its box.)
0'8ll11fzillg commllllds 0 1/ {/ tooflxlr
,,-
.. -
ZOo ...

":[1."

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


-
I
I
I
I
I
I right
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 followi ng steps. you wi lileam how to put
copies of a command on different toolb.'lrs. That way Fi nd can be on both the Tools
toolbar and the Parcel Viewer toolbar.
U In the Customize dialog box, dick the Commands tab.
The Commands tab di splays two li sts. Categories and Commands. Categories
organi zes commands by their funct ionality. Your list of cat egories may vary accord-
ing to which ArcGIS extensions you have Io..'lded.
The Commands li st contains commands that you drag OntO [Qolbars. Unlike
dragging fmm one toolbar to another, commands remain in the Commands list .
So you can drag as many copies to as many toolbars as you need.
In the following 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 BUIWINO " C U 5 T O ~ 1 "PPLlC"TION
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 wi ll look on paper with all its cartogrnphic components like north
arrow, scale. and titl e.
O'R(lIIizillg colIIl//{//lils 011" too/bar



( yrl h l ~ m n
,\ ,
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 familiar with the ArcMap 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 onl y text displays. To keep all the commands on the 5. "lmc li ne.
you ma\' have to widen the tool bar.
m Right-cliCk layout View and click Text Only.
The tWO commands ;l rc now di splaYI..-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
.\ 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 Tool bars tab. Uncheck all t ool bars except
Main Menu and Parcel Viewer.
Although you don't need it, ArcMap requi res 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 inst ructions below.
- On the Parcel Viewer tool bar, 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
......
P r ... _____ .... _h __
.. _
r... I
3 1
c ... rl
('[-...... _ ..... -
Organizillg commwu(s 0 11 a m()I/xlr
yrl m '1.
- In the object found list, right-dick the parcel and click Flash feature .
....
_____ rH I
- 1'- 3 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



,

,.
iN
r

lY
,
,/>

I f

- In the dial og, 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

. "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('
foll owing exercises.
You can use a shortcut to open the Customize dialog box. Double-click on a blank
area in the toolbar area.
'----_ ........
_. ,
. , ,
here to
oprn me Customize
dialog 00.
m If you want to save your 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 continui ng with the next exercise, leave ArcMap open. Otherwise
dose it.
0'8(lII i:.:"1II8 com"'lII1ds 0 11 II foo/lxlr

yrl n
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 Customi ze di alog box to create commands called user interface 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 t on UrTooI UIEdi t 80.
As with any bunan. clicking a UiBunon makes something happen. For example.
when YOli dick the Save bUHon, the map is saved. UITools work by clicking them
and then clicki ng in. the map display arca. one can be acti ve 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
"


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

.,


3 1" 3 , a ..:. '
.
.. ="'., '"
To get a UIControi to do something. you write code with Vi sual Basic Editor. There.
YBA organizes your code into projects, code modules, and procedures.
CIIAM'ER 1 B UILDI NG A CUSTOM AI' I' LICATION
\ll(//)ll (1IlL'
EdilOl'
"
Projects are files where your UIControls and VBA code are stored. 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 profi les folder) .
Say you have a map document call ed rivers. mxd and it contains rivers and mhcr
water-related layers. And you need to make a UI 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 calculat e fl ow on rivers.
Say you need to make a UITool that reports any polygon's arca in squarc fect, acres,
and hectares. TIl is tool is not specific to any project. In fa ct you want it avail able
whenever you have polygon layers displayed in a n ~ ' 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 template to see if it contains any UIControis and code
{helt nceds to be available at all times. If your of&'<lnimr ion uses base [cmpi:ucs, you
can also store UIControis and code in them.
Projects organize code with code modul es, windows that ~ ' o u type into. You make
as many code modules as you wanl or need. However, every project has a code
module called ThisDocument . The ThisDocumcnt code module is the place for you
to write code for any UIControis that you make in a parricular project .
.\laking yOllr Ofl'lI COII/mtll/tis
:!d ma I.
,






I

I
I
I


,
,
!

j



,


I



,
i



l
Within each code module, your YBA code is organized into procedures, listso( VBA
instructi ons that perfonn a task. A procedure to cut the lawn might look like this:
Star t CutTheLawn
Get lawn mower f r om gar age, fil l with fuel if needed
Remove sticks and 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, funct ion, and property. Event
procedures correspond to user acti ons. For example, a UlButton has an event pro-
cedure call ed Click. You cooe the click event procedure so it will fun when the user
clicks the bunon. The other three procl.-<! urcs arc all ca ll ed into action by event pro-
cedures. So no code runs unl ess the user does something (causes an CVCnI).
All procedures havc a fi rst and last linc, wh ich arc ca ll cd wrappcr lincs. Your codc
goes between thcm. The fi rst line cont ains either the Public or Privat e keyword.
Pri vatc procedures can onl y be callcd on by procedures in the same code module.
Publi c procedures can be call ed on by procedures in other code modules. The fi rst
line also contains a keyword identifying the type of procedure (Sub, Function,
Property), the name of the procedure (for instance, cmdQuit_Click) , and parentheses.
(VBA identifi es both subrout ine and event procedures with the Sub keyword.) The
parentheses are required. Here they're empty, but in later exercises, 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 displays the quoted [ext mess.'lgt' in a dialog box.
When someone clicks the Quit bun on, the MsgBox line of cooe is executed, and the
di alog box below appears. Visual Basic comes wi th 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 BUILIJING A CUSTOM APPLICATION
,
{ ,
Exercise 2b
People are now using the Parcel Viewer application to print their parcclm[lps.
Occasionall y. 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 UlComroLs. 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 UIButtonCont rol 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 Y f l ( h l ~ m n
'XC 'el 2
Had selected Nonnai.mxt for Save in, the bunon's name would have "Normal"
as a prefix. UIConrroi s 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
ArcMap reads every t ime it starts up. Any UIConrrols )'ou save in Nonnal.mxt
I always appear, regardless of the .mxd file you open.
,

,
I
,

I
,
I
,

I
I
I
,
I
IJ In t he 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
You will change the bunon's icon to di splay text only.
o RighHl ick 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 call ed ThisDocument. Depe[lding on your VBA set -
t ings, these windows may be different sizes or in different positions compared to the
OnCS in the foll owing graphi c.
CIIi\PTl!R 1 BUILDINC ... CUln'OM M'I'LlC",TtON

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 UIConrrols and write code in the current
project that corresponds [ 0 the currently opened map document. ex02b.mxd.
Event procedures for the projcCl's UIControis arc s[Ored in a code window called
ThisDocument. That's why when you ri ght-click on a UIControl and click View
Source. the ThisDocumcnt code module opens. If it is a new UIButton, wrapper
lines (or the button's click event procedure arc ;1 momati cally added.
....
.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' "
The word "Prompr" is bold because it is the first argu ment you should type. For
Prompt, you a text suing ( 0 be displayed in the meS&'lge box's di alog box. Argu-
ments in square brackets arc optional. For a descript ion of each argumem. look up
MsgBox in the online hel p.
<:<.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 li ne of code by adding the f ol lowi ng text string,
quotes and all .
msgbox "For hel p di a l extension 25"
The click event procL-dure is now re:ldy to rcst.
m Highl ight t he procedure as shown below.
VBA checks your syntax and, whcn it's okay, converts it to uppercase for you as
needed. You typed msgbox and VBA changed it to MsgBox. lt 's a good idea to do
your rypi ng in Im .. crcasc and let VBA check your syntax and handle capitalizati on.
_ ... , " ......... _ . " .. ,
CHAPTER 1 BUII.DI:<;(l A$\{.fHjlM

.'i!.?ctlon (Inc
m On the Standard tool bar, click t he Run button (or press FS).
The Visual Basic Editor Standard 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 li ne of code runs, ArcMap comes to t he foreground, and the help tnCM.'lge apj:Cars.
- ",
I '* I
Hi ghli ghting a procedure and clicki ng the Run but ton is one 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 Editor.
III On the Parcel Viewer tool bar. click Help .
...
The message displays .
.......... , .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 wi th the next exercise, leave ArcMap open. Otherwise
close it.
,\laM; 118 .1'0 11 r 0 1/'1/ CO"""f"l(ls
~ right
Storing values with variables
---
In the previous 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 writ e a linc of code. In the line, you make up a vari able 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 31\ 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 the
va lue in a message box with the following line of code:
MsgBox Temperature
1M Inude the Temperiture variable displays here
01' I
As the da}' goes on, the number stored for Temperature will \'ary depending on the
wcat her. Bcc.'luse the value wi ll 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 statement. As it g N S warmer outside, a
new number is assigned. When the line of code below runs, the old number is
cleared out and the new number is assigned.
Temperature ; 50
The Temperature variable now contai ns 50.
A variable can be assigned a val ue 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.
(.'HAI'TER 1 BUlll.>l NC A CUSTOM APPLICATION

Variables can be substituted for numbers. For example. you could have subtracted 5
from me current temperature with the following li ne of code. The math equation.
Temperature - 5, is solved before the vari able's value is assignt.od.
Temperature : Temperature - 5
All math is perfonned from left to ri ght. except for operations in parentheses, which
are evaluated fi rst. In compl ex 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 mil es 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 24
0
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 Chill 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 vari able, the characters must be quoted.
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 li ne of code runs, the message and temperature display as one value .

1
To keep the temperature updated. someone must cntcr new numbers. A di alog box,
call ed InpurBox, has an area [.0 type in values .
---
SJOrillB mllll.'S witb IVlriables
...
I Ol I
0-01
Qhl
on!!
An InpurBox can be used in an assignment stat ement. 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.
Unless 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.797693134862315 E308.
EJ08 means that the deci mal place in 1.79769) 134862315 can be moved 308 places
to the right. That's like taking away the deci mal 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 call ed declaring or dimensioni ng 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: here 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 onl y one of several keywords uSt.-d to declare vari ables. You' Ul eam about
others-publi c, 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 foll owing graphic.
CIIAPTER l BUILDING A CUSTOM APPLICATION

scellon nne
Il ...... , I l .....
'", b, ..
0,," "'
........ 1 b,lO'
T .... ., r.,
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.>Ill< ""
.-.
1 ',,,,",,,,,um*tw _
....., ._,
h ....
I ."., tll."' ""
,-
9>l,I,',1O',mAlI.$801
: l
0 ....... 1 , ......
D.,. ...... , ........ 1.100 .. 00 .. _ ".-
.. 't

....., Ob!." , __
....... '0 ..... . 0 ............... ,,1_
{ .. ..-.
--
-,
!i .......
_.
Ito .............
O
,-
-,

,-
i6 b ... , On, .................... "'"._ ...
---
..
Oou.'.
Exercise 2c
Pt.'Ople are using the Parcel Viewer application to locate parcels and print thei r maps
but usi ng pocket calculators to compute the tax for a parcel. They'd like me applica-
tion to compute the taxes for them, In thi s exercise, you' ll create a UIButton that
calculat es a parcel's tax. You' ll make an input OOX that asks the user for the p.1rcel's
val ue and then displays a message box with the tax.
U Start ArcMap and open ex02c.mxd in the C:\ArcObj ects\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.'" ,
n.
... ' 1 l
In the Commands li st, you see the Hel p burt on you crc,ncd in the prcvious excrcise.
,_ eo_
C !J '"
I I
II Click the New UlControl bunon .

, .. odl"",
,., IA 'J t : ... (" ~ . r e =.,.
o With the radio button ne)(t to UIButtonControl selected. 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.
.
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 Rightclick 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.
Cli ck Open.
The doll ar sign appears.

..
Now you will write code to make the C,lculate Tax button work.
m RighHlick t he 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 Hel p 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 cel 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 deci mal 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' "
\ ,
Variable names must begin with a char..lCtcr and not exceed 255 characters. They
cannOt contain spaces, periods, or 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 variabl e's data tYpe. For exampl e, all srri ng variables
might be named with the prefix "srr": slrName, strAddrcss. srrPhoncNumbcr. In the
code above, CUT is a prefix for Currency vari:lblcs and dar for Date variables.
Next you ..... illuse an Input Box to SCI the parcel value variable. Since Input Box has
three message, window titl e, and default value-the linc of code
thar creates it will be rather long. To make it easier (Q read, you'll lise the linc con-
tinuati on character (an underscore) to put each <lrgument on ils own line.
m Enter the following line of code, putting a space before each underscore.
cur Parcel Value = InputBox (
-Enter a parcel value",
-Parcel Viewer", _
100000)
Even Ihough you see four lines, VBA recogni1:cs Ihem as one line of code and
executes it as such. You can onl y 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 conventi on
ccntl!T fcc, and $ 11.00 for the city's new nrc tnlck.
TIle numlx-r in the input box is mult iplied by 0.02, then 855 and 11 ,Ire add<.'tI. The
resul t of the calculation is assigned 10 curTaxV<ll ue.
DJ Enter the following code to set the date variable.
datToday = Now
"Now" is a Visual Basic function. You'll learn how funct ions work in a few chapters.
For t he time being, you can think of "Now" as a pfl!dcnned vari able thm contains
the current date and time.
All the necess:l ry informati on has been gathered and evaiu:n<.-d. Whm rema ins is to
give the informat ion to the user in a meSs.:lge box.
CIIAPTER l BUIU) ING A CUSTOM APPI.1CAT10N
.'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 TaxVal ue, _
vbl nformation , _
datToday
Normall y, 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 conti nuat ion.
MsgBox "The tax value 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. cont ains coday's date. Without the third argument, the
message box title will read either "ArcMap" or "ArcCaralog," depending on which
applicati on you wrote 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 .....
....... ,", -
c ... T",hl_ " (" .... ..-c.IV . .... . O.OU '.5' II
IIot1'o<loo, " /lo_
bO .... "lM ... ",01 ... ,. , '" c .. n""".,,,",
VII l"'On. ..
<k<T0400,
5101i"8 /1tlfll 'S lI'ith tmit/ bles
I ."
r yrl rI;
CIS
Before testing the code. you will add a li ne of code [ 0 help ident ify 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 options like 0}lIion Explici t.
,"Va" s .... (.'CV1.'"t ... _ c u ~ " 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 variabl es.
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 intenti onally mi sspell ed 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
.
-'ilL'
With Option Explicit on, when an attempt is made to execute the code, Fest is
identified as an undeclared variable, and the foll owing error mess.,gc displays:


In the code window, VBA highlights the misspelled variable.
... To .. .. . '11\1
T .... ""n , . ...
_ .... .
With Opti on Explicit added lO the code module. the Calcul ate Tax buna n is ready
to (CSt .
m Close Visual Basic Editor.
Ell Test the Calcul ate Tax button by following the instruct ions below.
- On the Parcel Viewer t ool bar. click Calculat e Tax (S).
- For the value, replace 100000 wi th 150000. (If you enter t ext instead of a
number, or if you cl ick the Cancel button, an error message will appear. In
chapter 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
m nOli
You have now created two UIBut(ons and coded (heir cl ick evem procedures. Users
click the buttons and your code runs. Next arc going IO code 11 second of
procedure call ed ToolTi p.
Code in a ToolTip event procedure ru ns when a user moves their mouse over the top
of a command. There is no clicking involved. Below. 1I uscr hovers the mouse over
the Zoom In command and a yellow toolti p 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 r ou al ready added. To add Dl her
event procedures for Calculat eTax, you select them from the procedure li st. You will
add the ToolTip e"ent procedure.
' . , Vat a Sub "O
...... t "" .. "",
P .... . " r .... Vdue ... c .. .,. . ""',
P .... ".<1'_, ... I>oote
.. - _
'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 arc added.

IOUOW)
V. I" IV.I ... . O.OZ) e . " II
da,TO"', .....
IUIV ..... n.. tall .... ' ... 10: I' urn,Va, ... ,
... Izotc .-, lea,
d. Uo<IV

. ";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 Editor.
m Hover your mouse over the Calcul ate Tax button t o see its t ooltip .
..
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 continuing wi th the nelrt chapter, leave ArcMap open. Otherwise
close it.
')tOri1l8 l 'i'IIl IC'S lI'ith ['(I/tables
. '"
'::tyright
Creating a dialog box
Usillg (:(n\ fTO/s 10 build II fonn
In the previous chapter, )'OU call ed 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 onl y do so much. YOli can't add buttons, slider bars. or 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
there's a better way to do it. You can make own di alog boxes with
as many input boxC5, check boxes. and slider bars as you need .
.. _--...
.......... ' ........... -
p-- p-
1"' -... p __
"' - "_
Per_ C E ,
_ 1_ . 1 ... 1
m n
Using controls to build a form
No matter what they look like to a user, aJ1 these di al og boxes are called farols by
programmers. The (orm below has fi ve inpm boxes and three butt ons. 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 Edi tor, the blank cmnras (or making a user dialog box is also called a
foml. The objects on a (onn, like buttons, inpm boxes, and [ ( ~ X [ , arc call ed cont rols.
- Form
- FOfm window
In the smile war that you dmg commands from rhe Customi ze di alog box onto a
toolb..1.T, you drag comrols Ont O a form (rom Visual Basic Editor's Toolbox.
TooIbo.-
7 7 I
... ..,
D.ag and - .\r)
"""
Label controls arc used to add descripti ve informati on.
C.b"
- I
-
control
A ..
-
I:' r. ,., 0 ....
F
I ...!l..:J ;
~ "
~
CHAPTER ) C REATI NG A DIALOG IIOX

....... llllll1 lIne
Text boxes provide an area for [he user to type in information.
Combo boxes provide a li st of choices (hat users click a drop.down arrow to see.
Combo8ox
control
- .
- I
1
-
While designing the (onn, you don't sec val ues in the combo box. Values appear
when the form is running and the user is setting or entering values as shown below.
-
1-
-
1----
-
1- .......
-
,
As you add controls to a form, you set their propert ies in the Visual Basic Editor
Propert ies window. Properties delcnnine the appearance of a control, incl uding its
height. width, color, and text. Below, the Add button's BackColor propcrry has been
set to green and its ForeColor property to white. The word "Add" has been t)'JX.>d in
for the Caption property.
BlckColor-

foreColor-
UsillS cOII/l'Ois to build fl jo,.",
n
After setting the propenies for a comrol, you then writ e its VBA code. Controls
have procedures that arc coded to run when the control 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 dialog box will fi ll a panicul ar need for collect ing data or performing a task,
it is helpful 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 streetli ghts. They
have laptops in thei r [rucks and use ArcMap to locll te 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 Arc Map form [Q usc
in the field.
By examining the existing system of getti ng repair data into the dambase, you can
determine the infonnat ion 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 maki ng 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
would expect .
C ... _ '" .... \
...... 1 I
I
w"
I
~ . f===l
I
. ~
I
-
C ~ .... ~
o ' .. !u . ..... .,
o I! ... ~ .
I
On
I
Once your paper design receives everyone's approval. 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)IAl OO so!>!:

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 industri al 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 contai n 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 i n the C:\ArcObjects\chapter03 folder.
Only the Main Menu and Parcel Viewer toolbars need to be turned on for 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'
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 ....


. ... ,


..

- Fotmwilldow
When you create forms and comrols, VBA assigns them a ,'ariable name. For
example, if 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 propert y in t he 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 form's gray color to white.
CH,\I'TER J CRATIN9 DIAIOO ijQl(

"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 t he Palette tab.
Click the white square in the upper left corner of t he (olor palette.
You see the form change color (rom gray to white.
Ok k w I I l t ~ :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 pi xels. The size of the foml and
its controls arc aU given in pixel uni ts.
Next you will add a city logo [0 the form and SCt its properti es.
D Click t he 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/t rois /0 build t1 f orlll
,. , ,
;-yrl h l ~ m nOli
( 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
posi tion in the following step.
.... 1

pr.-jIOIO ...

..
.,
,
,
,
,
,
...
m In the Properties window, set the foll owing 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 whit e.
&._---""
Next you will specify the location of an image file (0 draw in the rectangle.
CIIAI'TER J CREATING /I. DIALOG IIOX
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 either clip or streich if.
ilpyoghl:!d ma I.
( ,
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 capti on 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
.\L'l tlon nnc;
You see the three controls with the properties applied. They' re all aligned bc<:ause
you set thei r 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 for the three
labels as foll ows.
- Name: IblValue; Caption: Enter parcel 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
other controls (they don't do an\'thing), you won't be writing any code (or them.
Usill8 ccmtlUis to b/lild {f form
pyright
I
i



I






I

I
,
,
,
!
I
,
I
,
.
xc i
Next you will select all three labels [Q ri ght-justify them.
Ell Drag a box around all t hree labels.
n.r ji be"

m In the Properties window, dick the TextAlign property, click t he 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" DIALO(; BOX
.'iL'ctIOll (1)1('
m For each CommandButton, set the following properties.
TaK button (on the left)
- Name: cmdCa lculateTax
- 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 tCSI run.
m Click the form's window to make it active. Click the Run Sub/User Form button.
T1\c {onn appears as a dialog 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
fa Click the x in the upper right corner of the dialog box to close it.
Normall y, you would also be able to clkk the Quit button on the dia log box. bUI
since you haven't added any VBA code, it doesn't work yet.
Cl Close Visual Basic Editor.
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 wi t h the next chapter. leave ArcMap open. Otherwise
dose it.
CIIAPTI!R J C REATlNG A DIAtqq Q,X
Programming with objects
I'rORTamminR with m ..
G.:uing and JI."uin8 un
You worked with objects in t he 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, however, so the (orm and control objects don't work yet.
To get these objects to do what \'00 want, you write code for their evenu, methods.
and properti es.
An event is a user act ion (like a mouse dick) t hat happens to an object. An event
procedure is code that runs when the action occurs. You worked with events and
event procedures in chapter Z when ),ou created thc Help and Tax Calculator
UIBunons and coded their click event procedures. When someone clicks either
bunon , your code runs.
A properly is a characteristi c or an attribute o( an object. In a way, properties are like
variables because they both store 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 one's Caption
property
In the previous exercise, you used the Properties wi ndow to set property values. For
example, after you added the cboZoning combo box to the (oml, you set its name,
le(t, top, and widt h properti es.
An object's , 'alues can also be set by writing lines o( code that look like a
sentence mixed wit h a math equation. This programmer's grammar, shown 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 object's name, a dot. 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 simil ar to sett ing a variable's value.
ightw malCrial
Object. Pr operty '" SomeValue"
Instead of usi ng the Properties window to sct the cboZoni ng combo box's left. top.
and width properti es. you could set them with the following 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 acti on.
The syntax for call ing a method into acti on is:
Ob ject . Me thod
Suppose you have a form object call ed frmAddRecord and you want to run its Show
method. (The Show method opens the given (ann.) You would write the foll owing
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 li ke events in that calling them il\lo acti on 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 t w O exercises, you'll work first with methods, then with properties.
CHAPTER 4 PROOIV. MMI NCl WITH OIJ)ECTS

SL'C(I()Jl (Int!
Programming with methods
The captain of (he spaceship Atlantis sits on the bridge and gi ves orders: beam up
some crew members. put the deflector shields down. go to warp spd. 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 li ght. 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 navigati on check the route and lOCal e obstacles.
A method, in other words. entails a procedure-a list of things to do. h may be a
long liS[ or it may be a short list, but either way you always 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 or down. The Status argument has two set-
tings. To put the shields down you would write:
Atlantis . Shi elds Down
Other 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 , Mi chael
A page or 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 controls. were 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 Calculator dial og 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 di alog box to work.
Your first task will be to write code for the Calculate Tax burton on the Parcel Viewer
toolb.1f. so users can click this bunon to open the di alog box. Next, you will write
code for the dial og box's Quit bunon, so users can click Quit to d ose the dialog box.
ProgrrlmmillB willJ metbods
, .,.",
ighled :nalc'ial
\ ,
Finall y. you will wri te code 10 add t he words Residenti al. Commercial, and
Industrial to t he zoning combo box. These words wi ll become sclecmble choices
on 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 t he Calculate Tax button and dick View
Source.
The lllisDocument code modul e opens. You see severnl procedures that you coded
in previous excrcist.'s. However, the C'1lculate Tax bunon's cl ick evcnt procedure is
empty. In exercise 2e, you wrot e code that used an inpUl box to do tax calculati ons.
Since you crc:Hed thc Tax C., k ul a[Qr dialog box, that code has become obsolete, so
il was deleted (or
In chaplcr ), you crcated the Tax C'llculmor dialog box and named it frmTax. This
is the name t hm you will use in your code to refer to the Tax Calculator fonn. In t he
next li ne of code, wi ll usc the Show method to open the form.
D In the Calculat e Tax click event, indent for a new line of code and type f rmTax
and a dot.
frmTax .
After ),ou t ype t he dot, a drop-down list of the form object's properti es and methods
appears (unless you've turned the Auto List Members option off under Tools>
Options).
\cons to the left of each item indicate 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 . . . ..... <'''' ''
, .. 1.. . -
.... ..
...... to
,
.-
CHAPTER 4 PROORAJ,.IMING W!TII OBJECTS
.''- [/(In (11l1'
II ScroH down in the list and doubledick the Show method. (You could also
type Show.)
When thi s line of code runs, the Show method opens the [aX form.
...... , .. , ... ,., ...... <"."11
.......... -
.. ,.,.,. ,

Now thm ~ ' o u have programmed a way for users to open the Tax Calculator, you wi ll
also progrnm a way for them to close it. You will add code to the di:Jl og box's Quit
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 Quit 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 Hide
is the method. When a user clicks the Quit bunon, this code will run.
Pro;:mmmillJ.: with /lie/bods
,
1
,
I
I

yrl h l ~ m n
Nexr, \'ou will wrire code to add the zoning names to the zoni ng combo box. The
code will be wriuen in the form's initialize evell( procedure. In the followi ng steps.
~ ' o u will navigate to that procedure and write code in it.
o In t he code window for frmTax, click the object list drop-down arrow and click
UserForm.
The object list cont ains the names of each object (control) on the fonn. as well as
the (orm object itself. You might expect to sec fnn"TIl x in the list-since that's what
you named the form-but instead you see User Form. No matt er what name \' OU give
the form. VBA always displays it as UserFoml in the object list.
Before you have a chance to do anything, Click is selected in the ProCl . -dure drop-
down list and its wrapper lines are added in the code window.
Objen lin
." ... . _ . . ... _CII .. "
........
Click is the form's def:lllit e\'ent procedure, When you select an object in the object
list. its dcfauh cvcnt procedure's wrapper lines are aUlOmatica ll y added (unless they
arc already there). You arc not goi ng to code the UserForm's click event . so ignore
these lines or remove them,
Wi th 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
initiali ze 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 .. ...
CII Ai'TR 4 PROGRAMMINO WlTII O"lijE<r1"S

.'il'Clfllll nne
Normally. you can set an object's properties with Visual Basic Editor's Properties
window. However, combo boxes don't have a property to hold the val ues that a ppear h ~ ,
in their drop-down lists. For this. you have to write code.
You add val ues 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 foll owing three lines of code:
-, ...... " . ..... .
-, ....... ,,- -... .
_ ....... ,,- '" .. '
You put these three lines of Addltcm code in a fonn's initiali ze evcnt, because code
in the initialize event runs in the moments before the form 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 ini tialize 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 val ues. 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 ,.
m On the Parcel Viewer t ool bar. click Calculate Tax .
.
The fonn's Show method mns and the dialog box opens.
m Click the Zoni ng type drop-down arrow.
The zoning types appear in the list and can be seiL'Cted. YOli sec the choices in the
li st, becausc thc)' were addL'(1 as the form initiali zed. (These choices don't actuall y do
:mything 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, will cont inue (0 code the di alog box.
m If you want t o save your work, click the Fi le menu in ArcMap and click Save As.
Navigate to C:\ArcObj ects\Chapter04. Rename the f ile and click
Save. If you are continuing with the next exercise, leave ArcMap open. Otherwise
close it.
'll(/flll
Getting and setting an object's properties
In the Propert ies window below, you see properti es for the Quit command hutton.
The capti on property is, naturall y enough, the word Quit. Naturall y, that is, if rOll
speak English. If your users arc Spani sh speakers, you would want the button to say
Tennin: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 swit ch (rom onc language to
another depending on who's usi ng the application. To do that. would first have
to writ e 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. capti on = -Terminar -
t-. 'N" n ,.

In this exampl e, you were concerned with .seuing the value of a property. In other
situations, you may want to find out the val ue of a property that has already been set.
It may be a property that changes accordi ng to uscr input, and you need to know
what it is so that you can usc it in another calculati on. Finding out a property's va lue
and sloring it in a variable is call ed getling a properry.
GeUill8 (I/J(J .. (m a/1jecl s /J1'O/)crtil'S
I)nt!
,
Suppose you' re writ ing a handy little tool ro convert feel to melers. Your dialog has
a few different cont rols-a coupl e of teX[ boxes and a bun on. The top text box is
call ed rxt Feet and its Text property is SCt to whatever value the user types in. The
bonom text box is called txt Meters and its Text wi ll be SCt programmati-
call y after the user clicks the Convert to Meters burton.
_ ... ... 1-
txlFftt text
--- I r,--- txlMetel'\ box
To get a property, you use a variable and an assignment statement with the foll owing
syntax:
variable = object . property
Here, you want to get the Text property of the txtFeet object. In the next line, the
variable is called Feet , but it could be callcd anything.
Feec : cxcFeec.Text
After the line runs, the variablc will contain the valuc typed in by the user (5280 in
thi s 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 rxt Feet object. assigning thi s val uc to the variable Fect. In
the second li ne of codc, to the right of thc equflt s sign, the vfl ri flble vflille is multi -
plied by the conversion factor. The line as a whole sets the resuh as the Text propert y
of the txtMeters object.
When the event procedure runs. rhe vfl lue ( 1609) displays in the DaMeters ten box.
_0 ._ ,_
_ , c-. -. I , , ...
txtFHt tUI box
txtMele,s lett box
An t!xperienced programmer could bypass the explicit vari able assignments and
wri te the code more efficiently in a single line: rxtMeters.Text '" u:tFeet.Text
0.3048.
CIIAn'IlR 4 PROGRAMMING ..... ITII OBJECTS
(lne
Exercise 4b
In this exercise, will write code for the Tax Calculator dialog box to get t he
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, poi nt 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-cl ick the Calcul ate 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 Currency data type can Store va lues up to 922 trilli on, bur requi res
8 bytes. The Long data type can store values up to 2.1 billion and takes up JUSt
4 bytes. Since 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' "
l
II Add two more lines of code t o declare and set a variable t o calculat e and hold
the tax amount.
Dim taxAmount As Long
taxAmount : (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 zoning charge (0.02 ), an
$8.55 comrcntion center fcc, and an $11.00 fire truck fcc.
Instead 0( 0.02, it would 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 di alog.
D Just above the two lines of code you added in the previous step. insert two
comment lines t o 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 assumed in calc ulation below.
Next you' ll add a line of code to display the tax amoll nt. You'll do it by setting the
Capti on property of the IblTaxAmoll nt label, shown below with a value of 5020.
D At the end of the event procedure, add the following line of code t o 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
dial og box keeps it, its controls, and all their property senings in memory. When a
hidden dial og box is rffipened, the UserForm initiali ze event procedure doesn ' ( run
again. That means its most recent settings reappear. Were a user to select Industrial
in the wning combo box and then click Quit , Industri al would appear when the
dia log box was reopened.
Clt AI'TER 4 PROGRAMMtNO WITII OBJECTS

'il'((f'/l1 nne
You will write code in the Quit button's click event to clear the combo box's
selection area, the text box's (ext area, and the label's capti on, so that t h c ~ ' 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 lpt ion
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 Resident ial tax va lue 0(2 percent, so even if you
select Commercial or 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' "
\ l 1 l
Next you willtcst 10 see that the pared va lue, wning 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 iali ze event docs not run. The code that rou addl.' d to the
Quit button's cl ick event clears the parcel value text box, the zoning combo box's
selecti on area, and the tax amount label.
, .. . ~ ..... .
---
I
--
I 3
. ... '
m Click Quit .
II] If you want to save your work, click t he File menu in Arc Map and click Save As.
Navigat e to C\ArcObjects\Chapter04. Rename the f ile my_ex04b.mxd and click
Save. If you are continuing wi t h t he next chapter, leave ArcMap open. Ot herwise
dose it ,
CII AI'TER 4 PROGRAMMING WIT II OtiJ ECI'S
Code for making decisions
Makin,!; u Ca.5e for branching
Coding 1111 If Then
Unless otherwise dircoed, li nes of code in a procedure run, in order, from first (Q
last. However, lines of code can be grouped into blocks, and decision-making state-
ments, called Case and If Thcn, can control which blocks run and which don't.
Case statements handle mult iple-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-
ti on 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 call ses different code
tonm.
In a Case statement, you write a block of code IO run for each possible choice.
Depending on the choice, the appropri ate block (and only that block) runs.
If Then statements handle truefalse situat ions. Suppose you have a dialog 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 writ e twO blocks of code. One runs when the statement
is [rue and [he orner runs when the statement is false.
ighted material

,


,
I
,
,
I
I
Making a Case for branching
Case stat ements process multiple-choice si ruari ons jusr like you do when you
approach a tmffic signal: when the li ght is red, you stop; when the li ght is green, you
proceed with caution; when the light is yell ow, 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 t he lights arc out, 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. Aft er 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 statement above assumes [hat theTrafficSignalValue has only three
possibi lities: red, green, or yellow. But if there's a power failure in the area, the lightS
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 handl e a traffic signal value ot her
than red, green, or
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, commerci al. or indus-
u ial , and each zoning type h3s a different [aX rat e. In t his e.xercise, you'll create. a
C'lSC Slalement to determine the user's zoning t ype 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
't.'l (1011 flJlC
You sec the Tax C., lculator fonn.
EI On the form, doubleclick the Calculate Tax button to open the form's (ode
wi ndow.
Double-clicking a control opens the fonn's cooe window (or brings it to the front if
it's already 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 incl ude the
zoni ng 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 selecti on in the zoni ng combo box. If the user picks Residenti al, (he variable
value wi ll be 0.02; if t hey pick Commercial. it will be 0.023; and if (hey pick
Industrial, it wi ll 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 onl y requires four bytes of space and can hold decimal values.
h's the most efhcien! numeri c data type for storing small numbers that have decimal
places.
Next, rou' li code the Case Statement. In exercise 4a, you used the Addhem 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/cbillR
~ Y f l h l ~ m n


I
In each branch of the C, se statement, sngTaxRatc will be set lO the tax rate (or the
selected zoning type. (The Industri al type is selected in the graphic 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 zoni ng.
D Inside the Case statement, add a Case to (heck for Resident ial value. Add a
second line of code to set t he tax rate varia ble to 0.02.
Case "Residential "
sngTaxRat e ; 0 .02
Each case is indented from the main Select Case stat ement 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 val ues and set the
tax rate variable for each.
Case 'Commercial "

I sngTaxRat 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
.'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.l ue
c.kul.ted
m On the Parcel Viewer toolbar, click the Calculate Tax button.
m For parcel value, type 400000.
m For Zoning type, click the dropdown arrow and click Industrial.
'.0 ....,-
---,
--,
". , ... ,
.\fakIIlM (I Ctl$(' for brtlllclJlng
( yrl n
,
II] Click the Calculate Tax button.
TI\e estimated tax, 11020, appears. To t CSt rour Case s m u ~ m e m with the other
zoning types, you will switch zoning 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 ::Jppropri atc 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
,
I I ) \
! I n ... -
Coding an If Then statement
Out dri ving, you approach a fork in the road where going left takes you into the city
and right takes you into the countryside. You need to make a decisi on 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 rel axing dri ve 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 = aWor 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 essenti al thing about If Then expressions (also called Boolean or logical
expressions) is that they are either true or false. For example, 4 < 5, 20 > 40, 2 <- 2.
and "Hello" - "Good bye" are all logical expressions, because when you evaluate
their logic they result in either a true or false answer. But 4 + 5, on the other hand,
is nOt a logical expression. When }'OU evaluate 4 + 5, you get 9, and the number 9 is
not 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 ) , greater
than or equal to (>- ), less than or 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 connecmrs, whi ch are Engli sh
words like AND and OR. Below, AND combines two expressions into one larger
expression. In order for the full expression (Q be true, both small er expressions must
be true.
x>y ANDa: b
With OR, onl y 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
Another way to create an expression is with a function. VBA comes with a v,uiery
of predefi ned functi ons 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. For 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 ,-
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 foll owing 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 for alkaline and nemml pH Icvels.
If the If Then expression is true, or 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 great er
than 14). the code aft er the Else keyword runs.
If intPHLevel < 7 And intPHLevel >= 0 Then
MsgBox "You have an acid"
ElseIf intpHLevel > 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
CHAPTER 5 CoOl! FOR QECISIONS
.\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 Calculate Tax, and gets
an error message.
' -
-_.-,
--
.. -
... _---
The error appears be<:ause me quotation marks make $200,000 a string instead of a
number. VBA c.mnot multiply a string and a number:
"$200,000" 0 . 02
In this exercise, you will code (he Parcel Value text box's Change event. E'ICh lener
or number that the user types intO the text box causes code in the Change 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 or 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 Editor.
COt/iIlJ.l (1II1f7bell
,.,
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. Change 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 IsNumeri c (txt Parcel 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 t he Else statement.
El se
CUAPTER 5 Colli; FOR MA"INO DECISIONS
Sl.-l(11
D Indent and add the following line to set the Calculate Tax button's Enabled
property to false.
cmdCalculateTax. Enabled = False
When the user types anything other than a number imo the Parcel Value lext box,
the Calcul ate Tax bunon will be dis.'l bled {grayed out}.
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 , Calculat e 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 displays.
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 for you. For example,
you type
emdC
as if rou arc going to type cmdCalculateTax.
Codillg fill If 1bcII sftllel1WIlf
I I 11 l
,
yrl h l ~ m n
\, ,
But afler typing juSt emde, 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 mistakes in ,:.t ri able. 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 are continui ng with the next chapter. leave ArcMap open. Otherwise
close it.
CH"I"TER;; CoOl! FOR MAKING DECISIONS
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'{lleJ with functions
Up ( 0 thi s poim, you've been working mostly with event procedures, whi ch run in
response to a user acrion or a change in the system stat e. In thi s 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
acti on. An even! procedure runs when irs event occurs. A subroutine runs when it is
called by anmher procedure. A call is a line of code that says, "ProcL"Ciure So-and-so.
. , "
It S your rum to run.
The calling procedure may be nn event or 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 called it. A subroutine mi ght assign symbology to world coumries based on
their population values. A functi on might sum the population value for each coun-
try and return the earth's population.
Instead of having lots of different procedures calling each other, you mi ght be
wondering why you couldn't put them all inw one big block. In the example above.
why not take all the code for 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.


In fuCl , you coul d wril e code t hat w'l y-it 's just not efficiem. Writing code in discrete
blocks that call ot her di screte blocks has several advantages. For one thing, it makes
if easier to reuse the code. Suppose you' ve made three buttons with different dick
event procedures. One draws buffer zones, another intersects tWO layers, and the
third uses one layer to dip another. In each case, you wam to print the map after the
operntion. You could copy and paste your m:lp-printing cod!;' int o all three event
procedures, but it's simpler to writ e the code once and run it with a call from c:lch of
the event procedurcs.
Suppose you decided to do the copy and pasti ng anyway, and then found that your
map-printing code had an error. Instead of debugging it once in a subrout 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 functions also keep your code organil!ed.lf you have several tasks to
perform in sequence and you code t hem all in a single long block, it's easy to lose
track of what a parti cular line of code is doi ng and what has al ready been done.
In this chapter's four exercises, you will call and modify subrout ines and write a (unct ion .
(.UAI"TI!R 6 USING SUHIIOUTINFS ANn I'UN(.'TIONS

\lL"(Inn (Inc
Calling a subroutine
You tell a subrolltine to run with the Call statement.
Public Sub GetMessages()
Call Message
End Sub
The subrout ine above is called GetMessages, and it does onl y onc thing: it teUs
another subroutine, called Message. to run. When called, the Message subroutine
runs and displays a mcss.. ,gc box.
Public Sub Mes sage()
MsgBox "Geography 15 terrific
End Sub
Any procedure that wants [Q display the words "Geography is terrifi c" can call the
Message procedure. Below, the DailyQuote subrouti ne 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 call s 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
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 call ing 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 calls
Test2. and its tim two lines run. The second line of Test2 calls Tesu. and its three
lines run. When Tesu finishes. control returns to Test2 and its last two lines run.
When Test! /i ll ishes, control returns 10 the click event and its last tWO lines run.
Public Sub cmdMessage_Click ()
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 displays before the Hide method
runs on frmGIS.
Exercise 6a
You work as a programmer on the Washington, D.C., Police Department 's Crime
Anal ysis team. E.'lch week, your team mects with the mayor, police ch ief, and prc-
ci nct captai ns to discuss how to reduce crime.
During the meetings, analysts di splay 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 di splays the ('mire city. with a marker
showing where they' re zoomed to.
You have been reading the book Exploring ArcObjects (parr of the ArcGlS software
documentation available at www.esri. com!ExploringArcObjects). In the 1:xJok, you
have found a sample subrout ine call ed CreatcOverviewWindow that docs just what
you need. Part of being a good programmer is bei ng a good thi ef. Stealing this code
will Sl.we you a lot of programming time.
In thi s exercise, you will import the CreateOverviewWindow subromine and call it
from a click event.
CIIAI'TER 6 USING SUBROUTINES ANI) fUNCTIONS
(llelll ,Inl'
D Start ArcMap and open ex06a.mxd in t he C:\ArcObjects\Chapte r06 folder.
When the map opens, you see Washington, D.C., layers and the Crime Anai\'sis
toolbar. which contains severnl buttons that you will code in this chapter.
Cnme AAi!ylIS
t oollMI
0 " 0
" __ Ot, __ -.

C o ..
-
Ii'! C I , ~ w
,



. , ,
If rou havc worked through 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 Vi ew 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 CrcateOvcrviewWindow subroutine.
First. however, you will impon the subroutine.
I .. . ...
Calfillg {I slI lmmrl1le
OPYflCJhl"':d a 'I
I
In the Project window, right -dick 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 overvi ew
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. Navi gate to C:\ArcObjects\ Oat a\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 whi ch you write and s[Qrc procedures.
When you impon: code, ,I new standard module is aut omati call y created 10 hold it.
In the Project window, under Project (ex06a.mxd), click the plus si gn next to the
Modules folder to open it .
---Nf:W modul o:
Iddt'd here
In the Modules folder, double-dick Module1 to open it .
You might recognize, in a general way, what the code in CreatcOverviewWindow
docs. The first lines are comments foll owed b\' several Dim statements for declaring
variables. The next lines set those vari ables 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 bl ue out line symool on the rectangle that shows where
[he ArcMap display area is zoomed to.
The subrouti ne uses some ArcObjects code that you won't learn about umil chapter 10.
It's OK if you don't undcrs,md the details. In this si tuati on, 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_,
CHAI'TER 6 USINC SUBROIITINES ANI) FUNCTIONS
, lll(lll (Jnl'
o In the Properties window, replace the module's name, Module1 , with
CrimeAnalysisTasks. Press Enter.
In the ot her exercises of thi s chapter. you will add more subrouti nes to the
CrimcAnalysisTasks modulc. You could store every subroutine in irs own modul e,
but since these arc all about the s.,me topic, it's logical to store them together.
The event procedures for your UIControls (like the Overview button's click event)
are stored in the 1l1isDocument code module. This means that procedures in one
code module (ThisDocument) will be call ing procedures from anmher code modul e
(CrimeAnalysisTasks). For thiS to work, the called procedure must be declared
Publi c. CreateOverviewWi ndow above is already declared Public. Procedures that
arc decl ared Private can onl y be calk-d by other procedures in the same modul e.
D Make the ThisOocument 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 subrout ine to run.
_ _ .. ... _ ... .. o_cuun
ca. , C ~ r o o"odo
. ... 10&1
You could have copied all the code in the CrealeOvef" iewWindow subrout ine 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.
Another benefit of keeping the procedures separate is that ~ ' o u can call
CrcatcOvef',jewWindow from procedures other than the click event.
Coffing fI slI/)fTml il/(!
,
:)J:ryngh _ m
I
1
m Close Vi sual Basic Edi t or.
There have been several recent burglaries ncar the Holy Name College. You will t.est
the subroutine examining the area around the coll ege.
m Turn t he Landmarks and Burglaries layers on.
m Click t he View menu, point to Bookmarks, and click Holy Name College.
Because you're in, it's hard to [ell where in lhe District the coll l'ge is located.
-
J
(
-
- -
I. '=0000w
- --

-
-
ED On the Crime Analysis tool bar, cl ick the Overview button.
You Ill ay have to move or resi"e rhe Overview 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 yOIl make to the blue box a(fect the ArcMap window.
CH" I"TER 6 USING SUBROUTI NES "ND I'UNC710 NS
.
.\I.'L (Inn (Jill'
m In the Overview window, drag the blue box to the eastern corner of the Dist rict.
as shown.
The ArcMap display pans to the new area. The extem of the bl ue box in the
Overview 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 subrout ine wriuen by someone else.
Programmers do this all the lime to make li fe 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 ArcOhjecls, that wi ll gCI easier. You' ll do more
copying and calling in the foll owing exercises.
GET MORE FREE COOE SAMPL.S
In Close the overview window.
m If you want to save your work, click the File menu i n ArcMap and click Save As.
Navigate to C:\ArcObjects\ Chapter06. Rename the f ile my_ex06a.mxd and click
Save. If you are conti nuing with the next exercise, leave ArcMap open. Otherwise
close it.
Cal/fllj.l (I SI//JlTJIIIIIU'
I. " '
opyrighl:!d ma I.
Passing values to a subroutine
Sometimes procedures pcrfonn their task without any arguments. In the last exercise,
you call ed the C reat cOvcrviewWindow subrout ine and it opened an Dv('ndcw
window. That subrout ine has no argumentS. When call ed. it runs [he s.'l Il1C way
every time.
Arguments pro,.jde informat ion to a procedure so mat it can run with some vari ation.
Suppose you want to creatc a subroutine that prints a map at a page size specified by
the user (l etter-, legal, C-, D-, or Esize paper), When you code the subroutine, you
define an argument with a namC' and data type in parentheses. It's li ke dedari ll!:: a
vari able. but without the Dim keyword.
Publi c Sub PrintMap (aPa geSize As String)
End Sub
When rOll ca ll the PrinrMap subroutine. you musr enter a val ue for its nrgument.
This is called passing a value [Q a subroutine. The code bela ..... passes t he "Lcttt"r"
p.1ge size to the PrintM3P subroutinc.
Cal l Pr i nt Map ( "Lette r" )
A.s t he Pri ntMap subroutine runs, the variable declar\.od in its arguments li st is set to
hold the p.'lSSOO value. Code inside the subroutine can use the vari able to respond
differcntly accordi ng [Q which val ue is passed. For example, your code might use a
Case statement to evaluate the variable and run different blocks of code.
Public Sub Pr i ntMap (aPageSize As Stri ng)
Selec t Ca s e aPa geSi ze
Ca s e "Letter"
Ms gBox "The page S1ze 15 " & aPageSi ze
Ca s e "Legal"
Some othe r code runs
End Sel ect
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
CIIAPTR 6 U SINO SU8 ROUTINES.ANIl f UNCTIONS
, ,
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 anal yst 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 devel oper
help Web sitc (arcobjectsOnline.esri.com). There you do a search and find a sample
subroutine called Crc3tcNcwCh: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 Chart.
In this exercise. you will import [he CreatcNewehart subroutine and modify it to
accept an argument for t he chart title. That way. anyone making a chart can give it the
name they want. You'll test the new subroutine by maki ng 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 Crime 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 Chart click event procedure.
First, you will import t he 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 goi ng to import was obtained (rom the devel oper help Web si te.
Si nce some people may not have an Inte rnet connection, the sa mple code to make
chans has been provided with thi s book's data CD.
D In the Import File dialog box, click the Files of type drop-down arrow and dick
All Fil es. Navigate to C:\ArcObjects\ Oata\Sampl es\ArcObj ectsOnl ine and click
CreateNewChart.txt. Click Open.
A new standard code modul e is added to t he project. To see it, you will open the
Modules folder under Project (ex06b.mxd).
o In the Project window, under Project (ex06b.mxd), click the plus sign next to the
Modules f ol der t o open it.
~

Passi/lg ' (lhU's / 0 (l SlIlm:JII /;II l!
"":yrighl:!d ma ,.
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 code so you can 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 Crcat eOverviewWindow 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 - 110. 'MM."
... , , .. "" ... .. ' ''''' . " _a!> . . .. , .,.."
The CrcaicNewChfHt code is now in the 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 modul e thai was added to project when you illllXlrted
the CreateNewC hart sample code.
m In the Modules f ol der, 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 (bet ween the parentheses), type strTitle As String. This declares
a string 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 repl ace Chart with the sunde variable.
m Scroll down in the CreateNewChart subroutine and locate the followi ng line.
pDataGraphProperties.Title : My Chart -
C"AI'TER 6 USINO SUI.lRottrll'O'M ..... NU P1JNC'nONS
(1)1L'
m In that line. change " My Chart" to strTitle.
pDataGr aphProperties. Title = strTitle
Make sure lO usc onl y the variable name and no quotes. Now when any procl"<i urc
calls CreatcNe"-C hart and passes it a text string, the subroutine will store thai string
in the strTidc vari able and use it to set the chart 's Ti tle 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 ('Enter 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 .... " _CHUIl
... .... 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 n
TIle Cre1ltcNewChart 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 Cre:l teNewChart subroutine uses the selected layer's ami bute rable to make the
chart. The ch[lrt \'[lhICS, showing t he number of arsons, are mken from the fi rst
numeric field in the table. The chart labels, identifying the precincts, arc taken from
the fi rst 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 [l ny. you woul d sec a yellow 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 t he file my_ex06b.mxd and click
Save. If you are continui ng with the next exercise, leave ArcMap open. Otherwise
close it.
Making several calls to a single subroutine
Sometimes you design a user interface with two controls thai do the same thing.
ArcMap, (or exampl e, has the Layout Vicw menu choice on the Vicw menu and the
View minibunon in the lower left comer of the map display. Both swi tch the
vicw [Q Layout Vicw.
Since 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

....
",
Arsonists commonl y don't stop with sctting just one fire, and, oddly enough, they
don't generall y go very far afield. So the people who anah'ze arsons typically smn by
drawing buffer !Oncs to sec if t here arc similar arsons ncar each other.
Insl'cad of writing the code yourself, a search of the developer help yields a sample
subroutine call ed 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. Once agai n, you will modify the code to accept an
argument. This time, each button will pass a different buffe r va lue: 500. I ,0Cl0. or
1.500 meters .
. 11f1kiIlR Si..'Ir!rtll calls /cJ fI siIlN!(> slIbro/llfll(>
, ..
m n
,
,
D Start ArcMap and open ex06c. mxd in the C:\ArcObjecu\Chapter06 folder.
When {he m;lp opens. you sec the Disn ict \<l Ycrs and the Crime 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 module. you sec the empty Buf(cr500 click (' vent
procedure. After import ing and copying the procedure for dr:.lwing buffers, you will
call it from this dick event.
U In t he 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 install L-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\ArcObj ectsDeveloperHelp
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 wi ll open the CrimcAnalysisTasks code module, 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.
CHAI'TIlR 6 USING SUBROUTINES ANI) FUNCTIONS
o With t he cursor a t t he t op of the CrimeAna lysisTasks module. a bove t he
Create NewCha rt subrout ine. 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 subrout ine has an empty arguments list. You will add an argument
to all ow the passing of a buffer distance. The 500, 1000, and 1500 but tons on the
Crime Analysis toolbar will each call t his subroutine and pass it different distance
values.
Before you adjust the code lO suit your needs, you will remove the modul e t hat was
addl'Cl to your project when you imported the BufferFeatures sample code.
m In t he Modules fol der, under Project (e x06c.mxd), righHlick Module1 a nd cl ick
Remove Modul e 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 li st of the Buffe rFeatures subrout ine (between t he
parent heses), type st rBuffe rDi sta nce As St ring. This decl ares a st ring va riable
to hold the buffer dista nce.
Public Sub BufferFea tures(strBuff e r Dis t a nce As String)
Recall that the chart title argument from the last exercise g<lVe the user more freedom:
here, your buffer distance argument will be used to restrict their freedom. Instead of
giving the user an input box to emer a distance, rour cooe will pass one of t hree
predefi ned values.
By the way, it may seem odd t o work with distance as a string, but the existing code
is written to expect a su ing. You could change it so t hat it expects a number, but
leaving it as a string is easier and will get the job done just as well.
You have to make one ot her change. The BufferFearures subrout ine already has t wo
lines of code that dec lare and set a buffer distance variable. Since you have put your
own buffer distance , 'ari able in the argumentS list, you will find and del ete these two
( nonadjacent) li nes of code that arc no longer m.'Cdcd .
.llaking S(J/.'('m/ 10 tl sl1lgle $lIbrolllllW
,
!
I

o yrl n
''Xt,: I
m At the top of t he subrout ine. locate t he following l ine of code.
Dim s trBufferDi s tance As String
......... v...
.. 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 li ne of code.
m Scroll down in the subrouti ne and locat e the following li ne 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) Delet e this line of code. t oo.
m Make t he ThisDocument code window act ive.
CHAPTER 6 SUkROUT1Nts AND " UNCT10 NS
.
. '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 . . .... Ir ........ "." '
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' S O ~ . 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 Uni versity. You will use
the buffer buttons to analy!c them.
ED In ArcMap, click the View menu, point to Bookmarks, and click Howard
University to zoom to it.
You will select the uni versi 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'
\
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! = ...

-

,
,
,
,
,






,


I
. _.


il'"
O!J
""
,

,
" .
, .
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 colors used for drawing. For now, yOli wi ll select the thrcc buffer graphics
and change thei r symbology manuall y.
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 universi tr.
CIIAPTER 6 USINC SUHH.OUTINE' "HI)

. '\l'Ctlll71 (JJll'
._.- .................
Q rUiHi

0_.
,

-
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 10 (I sillgle SUb rollti ll('
, ,
ial



,
,
,


I
,
Returning values with functions
- - - - ~ ~ - - - - - - - - - - - - - - - - - - - - - ... ----


In the previous exercises in this chapter, you called subrouTines and passed values to
them with arguments. Functions work simil arl y, except that (as ment ioned :1( the
start of the chapter) a function returns a value. To be more specifi c. a functi on
returns a value to the 5o' lffie line of code thtl t call s it. You' ll sec how this works in
a moment.
A functi on 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 arithmet ic. and returns a new value (with any luck. it will be 3) . When
you call a (uncti on, 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 (uncti ons: MsgBox and Input Box.
The line of code below calls the Input Box funct ion. You pass the Input Box functi on
a text string inside its parentheses. The suing displays in a dialog box that prompts
the user to type in a val ue. Once a value is entered, it is passed back out of the
Input Box (unct ion and assigned to the strVal ue variable.
strValue = InputBox ( "Enter a Parcel Value" )
This line of code calls the (unct ion and passes it a value (to the right of the t.'<juals
sign ), and it receivt.'S a new value b.1ck from the functi on 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 ~ ' o u 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 mil es. The function
will receive an input value in kilometers, do some :u ithmet ic, and pass back the
equi valent in mil es. To code a funct ion, you stan with its wrapper lines:
Publ ic Funct ion Ki lomet ersToMiles ( km As Doubl e ) ~ Double
End Funct ion
The fi rst line includes the name of the functi on ( Kil ometers ToMiles); an argument
dt.'Claring a vari able and data type for the input value (km As Double); and the As
keyword followed by a data type for the returned value (As Double, shown here in
boldface) .
Although they are of the same data type herc, the input val ue and the returned
value do not have to be. Say you were creating a function to calculat e 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.
Publi c Function Age I nYears (age As Date) As I ntege r
End Func ti on
CHAPTER 6 USI NG SUMII. OUTINI'.5 ANIl FUNCTIONS
I (11lL'
To complete the code (or the KiiomerersToMiles (unction, you need a conversion
(onnula to change kilometcrs into mil es (lldlomefcr equals 0.62 1371 miles) and
you need to pass the new value out o( the function and back to the line that called
it. You can do all that with one line of code.
To pass a value out o( a (uncti on, you use the (unction's name like a variable. The
line of code below sets Kil ometers ToMiles equal to [he mil es equivalent of kil ometers.
Public Function KilometersToMiles (kID As Doublel As Double
KilometersToMi1es : kID 0.621371
End Function
Setting KilometersToMiles as if it were a variable all ows the line of code that calls
the function to receive the returned value.
When you call functions 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 hold the
,'alue that the functi on will rerum. The second sets this variable equal to the func-
ti on name and passes a value into the function (1 0 in the exampl e 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 functi on's return value is a Double.
Dim x As Double
x = Kilometer s ToMi1es (10)
The foll owlllg diagram illustrates the process. The functi on is coded in the
ConversionTasks module and called from the ThisOocul11cnr module, where the
value lOis passed into it. In the functi on, this input value is SlOred in the km variable
and converted to 6.2 1371 miles. Then Kilometers ToMiles is set equal to 6.2 1371,
whi ch 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 holds the value 6.21371.
..
from tM funct ion
10 Uliling
of code
A Is from 1M Uliling
Ii code 101M funct ion
Declari ng and setting a variable isn't the only way to handle a function's returned
value. Since a function returns a value, the functi on can be used anywhere that that
value is accepted. For 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.
"


KilomctcrsToMiles (unction as a mCSs.:lge box's first :lrgument as shown on the
line below.
MsgBox KilometersToMiles (10)
Exercise 6d
During the crime analysis meetings, the group reviews recem drug busts. TIle
amount of drugs confiscated is typically reported in kil ograms, and someone always
asks, "How much is that in pounds!"
In thi s exercise, will make a (unclion to convert kilograms to pounds. You will
call rhe functi on from a button on the Crime Analysis toolbar. Once the (unction is
wrincn, you will be lIble to call it from any other procedures that havc a use for it.
o Start ArcMap and open ex06d.mxd in the C:\ArcObjects\Chapter{)6 folder.
When the map opens, you sec the fllmiliar District layers rmd the Crime 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 CrimeAnalysisTasks modul e. 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 module. You'll
define its arguments and returned value data type in the next two Sfeps.
Ctli\PTEM 6 USING SU8ROUTINES Ar-:r)
.... ,-' ...
o In the function's arguments list (between the parentheses), type dbl Kilos As
Doubl e.
This defines a variable to hold 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 Defi ne the data type of the funct ion's returned value by typing As Doubl e 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 kil ogram,
so the formula is pounds kil ograms 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 val ue 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-
tion to t he line of code t hat call ed it, you set t he function's name equal to a value.
Here it's the formul a's resul t value.
'_ ,o. ." ... _ ... '(.'" ...... _ ,., ..
1 ..... _.... , - .,." .. . ...... .
,
The function is now complete. All that remains is to code the Kil osToPounds
button's click event procedure to call the functi on 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 Input Box is the val ue that will be passed to t he 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//)

x

"

n nal
m Inside the KilosToPounds click event, declare a variable for t he user's kilogram
val ue and set it usi ng t he InputBox f unction.
Dim user Kil os As Doubl e
userKi l os ; Inputbox ( "Enter t he numbe r of kil ogr ams-)
You are ready to call the KilogmmToPound functi on. This includes declaring a
vari able to hold the function's returned value.
m Declare a variable f or t he KilogramToPound function's returned val ue and set it
by call ing t he KilogramToPound funct ion.
Di m user Pounds As Double
us e r Pounds = Kil oqr amToPound (user Kil os )
m Add a final line of code t hat uses a message box to report the convert ed value.
MsgBox us erKi l os & - ki lograms i s &
userPounds & pounds
........ _, " .. ....
...................... PO'*I
.... , ... _ ,' _ _ To ...... ... 1
" Ok ...... u le. < U J __ _
.... ..
-I
.... Of . . ......... ......... .
TI,e butt on and .he functi on arc 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 Cl ick 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:\ArcObj ects\ Chapter06. Rename the f ile my_ex06d.mxd and click
Save. If you are cont inuing with t he neKt chapter, leave ArcMap open. Otherwise
close it .
CHArTER 6 USINO SU8ROUTINES "NO FUNCTIONS
Looping your code
Coding" For 100/1
Coding a Do 10011
In VBA programming, tasks can be run repeatedly with loopi ng 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 for 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 ~ ' o u r job
to make them from 8 to 5. When the expression "time> 5:00 P.M." changes from
false to true, your sandwi ch-making stops for the day. So every time you finish 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
Coding a For loop
TIle mechanics of a For loop arc simple. You set a \'ariable equal to a stan val ue.
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
on the first line is foll owed 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.
For variable = Start Value To EndValue
Block of code here
Next
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 thi rd time. x changl's to J and a third map prints. Thl' loop stops nmning
after the tlmth map is primed.
FOI" X "" 1 to 10
' Code here to print 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 li st of items, you can al so skip ovcr iTcms using the StCP
keyword. Suppose you have a database of 10,000 customers and }'ou only 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
' print a mail ing label
LO(lpi ng statements are also useful for popul ming lists, like those in combo boxes.
TI, e onl y to add val ucs 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
.
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, ~ ' o u 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 call ed cboClasscs will contain a li st 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<
,
,
'\ "
, .
,
with J d .\.W$
8 I_
e Iii!! c.. 5
,m
0 0_
__ ,,,.., ,0
. ,11 .. ,0 :M;;I IZl
ltgt'nd with 5
.oo -

,m
0 0.71135
II:I IIlJS :snu
. ;sm: . .,.".
. ""'".. - u ... ,g
. "11""0 :M;!,D
D Start ArcMap and open ex07a.mxd i n 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 wi th val ues.
D Click Quit to dose the dialog box.
D Click t he 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.
Before writing any code. you will make a property sening for the twO combo boxes [0
help eliminate user typing errors.
..
o-oc.-_ ;::1 ==;"' ----
,-----
0-0_"_ '1--"" ____ _
cboCluws
8 ' ''' I
I
D On t he form, dick t he combo box cboYears to select it. In t he Properties wi ndow,
set its Style property to 2-f mStyleDropDownlist.
This option forces the user to pick a decade from the dropdown li st. Otherwise,
they could (ype in any value 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 or 1920) that will cause an error.
CUAI"'l'ER 7 LooPINO YOUR COllE
SL'ctl()ll ,IHe
Next, you will set the same Style property for cboClasses to keep users from maki ng
maps with fewer than three or more than eight 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 wi ll 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 Qui t bunon's click event has code ro close the fonn. The
M<l keMap bunon's click event h<ls code to call the RenderMap subrouti ne.
The RenderMap code uSt.'S the selected combo box values to get census data from
the Coumi es 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 cl ick UserForm (unless it is
already selected). In the procedures list. click the drop-down arrow and click
Initialize.
Since the initiali ze 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 vari able 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 ( ) ( I i ' I ~ fI For loop
opyrighl:!d ma ,.
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 informati on, and a
legend with more than eight is hard to int erpret. Visually, the shades of a color start
to look alike, and the distinctions betwcen classcs becomc less

For i ntClass = 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 li ne 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
.. 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 ntYear = 1930 To 2000 St ep 10
Next
m Inside the loop, add the following line that uses the Addl tem met hod 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 di alog box opens. the combo boxes arc empty until the user clicks
the drop-down arrow to make a selection. You will set a property for 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 . Val ue = 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 t o 7.
m Cli ck MakeMap. Move the dialog box so you can see the map.
CadillS (/ For fOOl)
,
,
,
1
'.

"
,- yrighl:!d ma I
\C"/\O
I


Many western counties arc yellow, which means they arc in the lowest populati on
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 migrati on from the midwest to the west. For a more specific anal ysis, you
could zoom in to a specific state and compare populat ion values for different
decades.
In the next exercise, you will work with a combo box that docs jllst [hm. You wi ll
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. Ot herwise
close it .
(: HAI"rER 7 Lool'lNG YOUR conE

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 Until 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 foll owed 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 as 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 functi on; when used with the vbYcsNo aryument, it offers a choice of some
kind and presents the uscr wit h two buttons. Depending on whi ch button the user
clicks, the function returns the value vbYes or vbNo.
- ~ -
1 ,.. 1 No
Thc following expression checks to see if the val ue 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
Wi t h fi ve colors, this isn't a problem. But what if you w,lOtcd to bui ld a combo box
li st of one hundred colors ! 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 t he 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 det ail. To open a fil e, you use VBA's Open functi on,
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 third argument is another keyword: either Input, Output, or Append.
(input is lIS<.-d to read a file. Output to write values to a new file, and Append to
add lines to an eXisting file.)
The fourth argument is the As The fifth argument ( ... ) is a fi le number you
assign. In given session, your code may read information (rom many different
fi les, so you need a simple way to tel l them ;Ipart .
When loop is done re<lding v<llues, you usc the Close functi on to d ose the file.
The C lose function has <ln argument 10 specify which fil e to close.
Close n
Howdo you know when loop has read all the values1 You usc the VBA function
called End of File (EO F) . EOF 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 expression.
In the example below, [he Do Unrilloop applies the EOF (uncti on [ 0 file num1x>r I.
The loop runs as long as EOF is false:. When the last line has been read, the EOF
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 vari able. As each line is read. its cont e nts arc put int o the
va riable (strNa me, in Ihis example).
CHAPTER 7 looPING " OUR COll I!
'Ll/"ri ~ l i ) L
Input .1 strName
Suppose the line being read from the text fi le consists of the word "Blue." Aft er the
li ne of code above n ms, strName will hold the va lue uBlue." The vari able holds
wh:ltever text string it fi nds in each successive line of the file. In a list of colors. it
wi ll hold values like "Blue," "Orange," and "Maroon." In a list of businesses, it would
hold values like "ESRl , 380 New York St, 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 li ne, and sets the variable with that val ue. When 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 following example, you use it to add a choice to a combo box.
The code opens a fil e c., lI cd names.txt and loops through it. Each line of the ten fi le
is successively stored in the vari able stTName. The Addltem method then takes the
vari able 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 thi s 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.
When the map opens. you see a layer of U.S. counti es with each state outli ned.
D Click the CensusMaps button. Move the dialog box. so you ( an see it and t he
map at t he same t ime.
Most of the code beh ind the dialog box has already been written. When the user
picks a state from the States combo box. the vicw will zoom in on that state.
This combo box itself, however, has not been coded, so its drop-down list is empty.
Its drop-down style hasn't been set either, so you can st ill type into it . Before adding
items to the combo box, or setting its Style property, you wi ll make sure the zoom
functionality is working.
C()(UI/B aDo loop material
In the Choose a state box, click the drop-down arrow to confi rm t hat it is empty,
then type Utah.
,---
o...tr.M_
1- ::J
0-. .-",,,,, 2 _
1 '
::J
-.-
mo511tes
~ - TI
I I
Click MakeMap.
MakeMap gets Utah from me combo box. zooms to it. and draws its out line.
Click Quit 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 contains a single
srfl[e name.
f. , ...... .,..,. ""' .....
Close the text file and file browser windows.
Before wri ting the Do loop. ~ o u ' l l SCt the combo box's Style property so that users
can't type in the box.

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 (or state names is call ed 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 iti al i.e even[ contains your two loopi ng 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
.""' ......
, .... to I,., V"c' ''''_'.'''.'''.11
... ... '000'
' 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 t o alter the path below.)
C()(/illR (J Do loop
:. yrighl:!d ma I
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 trFi l e = "c ; \ a rcobjects\data\ us a \sta tenames . t xt "
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 wi th 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 nput As . 1
lEI Add a Do Until loop that continues until EOF is true.
The EOF function uses the fil e number as its arguml' nt; in the previ ous 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- 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 press (111 and Brl'ak keys on your This operation is called Conl101-Bruk..
\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
til e (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




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 counties are in the hi ghcsllhird of all U.S. counti es (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.
Fixing bugs
Using rhe dcbllg loo/..s
Work ing through the exercises in this book, you have very likely gOllen a few error
messages. h was probably easy enough to fix your mistakes by comparing what you
typed wit h whal was written in the book. As you begin to write your own code, fi x-
ing mistakes may nO[ be so simple. However, 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 t hey are, why they hnppen. and how to find and fix them.
Before \'our VBA code runs . it is automatically translated into machine language
(3 language consisting cmirc ly of zeroes and ones, which is all your comput er reall y
understands). This translation is call ed compiling. When there is a problem in the
tra nslati on, you get a compile 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. for insrance. or t yping a merhod without the name of an object
and a dot. as in the example below.
Show
If you run code wi th syntax mi stakes. you get a compile error message .
......... _ ....

~ - -
. ..... _ ... -
.. I -I
I g h l ~ m n
Besides givi ng you the error message, VBA hi ghlights the offending procedure in
yellow and the error itself in bl ue.
::J I'" " I
_U._C_ .... lI
' ''': ... ""._w _I ...
..,
b ......
/ I
In commst to compil e errors, nm-time errors occur after the code has successfully
compiled and is being run. A nm-rime error means that your VBA code is syntact i-
ca ll y correct, but that the inst ruCtions 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 error:
Acres ~ SquareFeet" I 43560
Here, the type mismatch error appears, because a text string can't be divided by a
number.
VBA can't mi ss compile and run-time errors, and it kindly alen s you to them wi th
error messages. Unfortunatel y, VBA cannot detecr the third type of error, whi ch is a
flaw in your program logic. Code that has a logic error compiles and nlllS, but pro-
duces incorrect results--or at least not the results you were aiming for. It 's son of like
telling rour dog to ferch a ball when you really want ed it ( 0 fetch a stick.
\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 t h ~ H produces the wrong result every time.
aParcelsAcres : aParcelsSquareFeet I 4356
The correct formul a for 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. Since 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 logi c can often be caused by typing mistakes. In chapter 2, you
learned that Option Explicit can find typogmphical errors in vari able 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 for 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
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, 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 procedure thm n:sults ill a nm-time error.
As you step line by linc through the code. you will eventuall y hit the bid line thm gen-
erotes the error message. so you know right where the problem is. Clicking 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 specifi c 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 Breakpoi nt
button on the Debug toolb.u.
II

You C:ln also add a breakpoint by clicking in the code window's margin. Ei ther way,
a r('(\ circlc marks the spot and thc linc of code turns red.
CHAI"T'ER a FIXING alio s
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
combinati on o( stepping, runni ng, and breakpoints. The loop below runs (rom 0
ro 1000. Su' pping through it li ne 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 thi s problem. Clicking Run on
the code below runs it to the fi rst breakpoint. Clicking Run again runs the code to
the second breakpoint. Cli cking Run a third time runs the code to compl etion.
FirJt
- 101
..,. ... ,
..... .
" .....
.... ..
At a breakpoint, you can ei ther dick Step [0 run the present li ne and highlight the
ncxt line or click Run ro run all the code up to the next breOlkpoint.
Sometimcs, seeing 01 li ne o( code and an error 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 vari able in the paused rcll ow
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 error.
--(._,
...... _ ore .. u 10' 0\>0 '
. .. ,.t k ... ... ",_ <

..
. , ,
/be ddJIIB tools

.... -..
,
,
,al
,
Exerdse 8
Aft er 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 dialog box. UnfoTtun::nely, many mist<l kcs were made and the dialog box
no longer works.
In this 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. count ies and the CcnsusMaps burton on Ihe
ArcMap Standard loolbar.
This exercise lISSllmcs \'Oll are using Visual Basic Ed itor's defauh crror-rrapping
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.


- -
- I-
p .... - .. -
pc' __ .. ",
c. .... ea"
r ___ _
""''' .
r _ .... _

,_ ........ -
- 1:1_0;0._
P'

D Click OK. Then close Visual Basic Editor.
o Click CensusMaps.
Before your code could compi le, a VBA syntax error was locat('-<i . When a compi le
error is locat ed, an error mcss.. 1ge appears, the code stops running, and Visual B..1sic
Ediror opens .
.n --
......... , , ... -
CIlAl'TER S FtxlISO "lI("o5
.'i .. ' l t , () 11 (J n l'
II Click OK on the error message.
The error is hi ghli ghted in blue and its procedure in )cll ow. 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" accidentally
typed in, or is it a remnant of a previous line of code?
Some comment lines here mi ght 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. Normall y. )' OU usc comments to make nOtCS [Q
yourself and other programmers. Comments are al so 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.
Only the uncommemcd block will run.
Now that you've fixed the compile error, you'll run the code agai n.
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 tryi ng 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
,
m Click the CensusMaps button.
Another error appears; thi s t ime, it 's a run-t ime error. The mcssal,.'t" indicates an error
in the Project .ThisDocumcm..CcnsusM<l ps procedure.
II ,,.. 77 __
(10 I
The type miSmatch error means your code uses a data type that VBA is not expecting.
For example, rou may be using a number where VBA needs a string.
VBA usually hi ghlightS 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 show you 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, 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
first linc of code in the m .. cro turns )'ellow. This line will run as soon as you
click Step .. gain .
......
... ...
CHAlorttA. a FIXIN'f1
Ell Click Step.
The procedure's fi rst line runs. The second li ne 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
initiali ze event procedure turns yellow. 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 actuall y inside the
form's initiali ze event.
( 'si t/g the delmg tools
-
,
,.,
When an error 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 arc currently stepping
through. The iniri all!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 initiali ze proct.-dure TUns and the first line in the For loop is
highlight ed. (Di m and other declarati on statements are skippt.-d.)
0 .... m ..- .. I . ..... .
fe. , . . ...... "'0 .... 1000
III Cli ck Step.
A type mismat ch appears because the code tri es 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, not a string.
For a detaik-l:l description of this error, you can click the error mess.'lgc's Help button.
The type mismmch error is error number 13. Common ('rrors like rhi s 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.
m Click OK.
m Change NEight" t o 8.
You have f1x ed the run-time error. The code is now ready to test again.
m On the Debug t oolbar. click Run. (This Run button works just the same as the
one on the Standard toolbar.)
ArcMap and the Census Popubtion Maps di alog box appear. If you click MakeMap.
it will make a map. However, some people have complai ned 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 t he years that can be
selected.
---- .
o-.c..._
-.-
I
In your origi nal code. onl y the dl,."Cadc years were add(.,,(\ [0 the drop-down list, but
now every year between t 930 and 2cxx) is there. The Count ies larer att ri bute table.
however, onl y has data for 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 di splay.
(It would be a pure logic error if inCOTTCCI data was shown and no error message was
generated.)
m Cl ick Quit .
Usillg fix- delJl/g foots
I
,I
opyfight:K:: ma I<
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 event, add a breakpoint by clicking in the margin, to
the left of the first line of the Years loop.
The line turns red.
-= ........ . 1d<I!t_ .. .
. "
Now you will nm all the code up to that line.
OJ On the Debug tool bar, click Run.
Your code runs to t he breakpoint. The code pauses and that line turns yellow. Whil e
it's paused you can run. ncp, or view variable values.
tIl Click Step. Then hover your mouse over the intYear variable.
n,c variabl e conrains 1930. the firs t value in the loop .
... . ......... , .... .
....... ., ,. .. , .',
."
Evcrything looks normal so fa r. You'll run the loop again.
\
1 f
ED Click Step twice to run through the loop again. Hover your mouse over the
intYear variable.
You expect to sec 1940. but you see 1931. A logic error is adding every year to the
cboYcars combo box. The loop is running as told, but it's not incrementing 10,
because the Step keyword and 10 arc missing from the loop's first line (the red line).
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 choices.
CsllIg Ibe debuglro/s
n (lnt?
m
",
m Set the number of classes to S and the state to Texas. Crick MakeMap.

0..._"_ j t 3
0........ j ,.,..
---=
YOlL h<lve fixed the errors introduced by your coworker whil e weri.' on vacati on.
Tactfull y, leave il copy of Gl' tting 10 Know ArcObjeas on hi s desk.
m Click Quit.
The suggestions below can minimi ze errors in your code.
Tum on Opti on Explicit [Q identify typi ng mistakes in "<lriable names.
Run the code and decipher tlny error messtlges.
Usc the Debug toolbtl r to isolme bad lines of code.
Test for logic errors by enterillg va lues for which you al ready know the corrcct
results.
Try all combi nat ions of options on dialog box canITa ls.
Have someone else 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 l AmRS FIXINO Beds
Making your own objects
CreUling dtlHC:!
CTI!ul ing obje(:h
At an e a r l ~ ' age children inevitabl y ask, "Where do babies come fromr' In VBA
years, you arc at that age and ready to ask a similar questi on, namel y, "Where do
objects come from!" Fortunatel y, it's less awkward to answer the second question
than the fi rst. Objects 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
Later in (he chapter. wc' llmlk about this code in more detail; ri ght now, the point is
that you can make a dog object because somebody somewhere has already 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 collecti on 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
you're thinki ng thm if objccts come from classes, that just raises another
question: where do claSSt.'S come froml Programmers make them, of course-but how!
A class is basica ll y a container full of propenies and melhCKls. TIle cont ainer is a
code module and the properties and methods arc procedures.
You already know about storing procedures in code modules. In chapter 4, you "'rotc
procedures for a Tax Calculator form and Sl or(."{\ them in iI module called a form
module. In chapter 6, you wrote procedures for a CrimeAnalysis tOOIb..1T and stored
them in a modul e call ed 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 modul e.
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 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 create a B.1rk method.
Public Sub Bark!)
MsgBox "Roof, Roof , Roof"
End Sub
Running thi s 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
propert y code in the Dog class module and makes sure Ihal a string is expecuxl.
When you lei I the dog 10 bark, your code the Bark() subroutine in the Dog class
module and runs il.
You can think of object -ori ented programmi ng havi ng two a lower lier of
crl'ating and using objl"cts from existing classes, and an tipper lier of creati ng the
classes Ihemselvcs by wriling Ihe code for propenies and mel hods in a dass module.
ProgrammerS refer 10 these li eI'S as diem and server programming. A dass is call ed a
server since it provides services to cl ient.s. When you m3kc a dass. you arc doing
CtlAM'ER I) MAKINO , 'OUR OWN 0IYEC1"S
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 about client-side programming with ArcObjects servers,
However. knowing a bit about server-side programming Co.'!. n onl}' hel p make }'OU a
bett er client-side programmer,
-,:,, ,,,1 ,

I
I
I
,
,
I
,
!

,
Creating classes
Mi crosoft 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 (or you. Luckil y,
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 appli cation to hel p manage tax
assessment and coll ection. It mi ght be useful to model the city's land parcels in
ArcMap. Nei ther YBA nor ArcGIS has a parcel object . Sure, you could make a
Parcel layer from a Parcel Feature Class in a geodawbase and query its attributes. But
sti ll , there is no programmable object called a parcel. So you couldn' t write a line of
code like the onc below to display a parcel's value:
MsgBox myParcel . Value
And you couldn't write a line to display a parcel's zoning code:
MsgBox myPar cel . Zoning
Thar may give you a reason to creat e a parcel class of your own. Before you do the
programming. however. you need to do some planning. Whm properties should
parcel objects have and what methods should they nm?
Say you decide that parcel objects should have a Value propert y. 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 hold values like "residenti al"
or "commercial") that you also want to be able to get or set. Finall y, YOli want a
method that calculat es the tax on a parcel.
At firs t, you might skNch your ideas on paper, but sooner or later it's a good idea to
represent them with Unified Modeli ng Language (UML). UML is a diagramming
technique that programmers use to draw classes, properties, and methods with stan-
dard symbols. For example, classes (li ke Parcel) arc drawn as rectangles, propen ies
(like Value and Zoning) appear next to b.'lrbells. and methods (li ke C"icul areTax)
appear next to arrows. These UML pictures arc called object model diagrams .
In the diagram, data types arc list.ed to the ri ght of propert ies and methods. For
example. you see Zoning: String which means mat the Zoning property is stOred as
a stri ng.
CIIAJ'TER 9 MAKINO \' OUR OWN OllJECTS
SL'Ct/Ul1 Cllll
There are several software packages that draw UML symbols. If you code applications
with [he parric ipation of other people especially other programmers-it's probably
wonhwhi le to buy one of them. Whether you use UML or not. it's essent ia l to
diagram your class before you begi n coding it.
The diagrams are most useful after your coding work is done. People who arc new to
your classes can look at your diagrams lO understand how they work In the following
chapters. you will look at ArcObjC(: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, or a b.."lSC template. If you create the class in the currem map documem, li ke
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 ........ ,
Unlike 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 onl y 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 Publi c allows them lO be
Crt'flrillB c l a s . ~

used by 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
procedures. (In chapter 2, you rcad thm there arc four types of procedures: event.
subrout ine. functi on. and property.) \'(Iith property procedures. you call write morc
detail ed code to comrol the gcrt ing and sen ing of propcnies. For example. you
mi ght wrile a procedure that retrieves propert y values from a database roble. Whil e
this book does nm go into the subject of properly procedures, you can learn more
aoour them h)' searching the Vi sual Bask online help for the Propert y keyword.
To make a method for a class, yOli code a subrominc or a (uncti on, depending on
whether the method returns a value. The CalculateT:lx method wilt return 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
puuing it in a cl ick evem procedure, which requires user interaction to run, you
lI'ould make it one of the object's methods, so it could be run behind the scenes. )
On the UML di<lgr:un of the Parcel class, thl' dara type rl'lurned by thl' method is
li sted after its name. Ca\culatcTax() : Currency translates to "The C, lcul::!teT.'lx
method returns the Currency dolta type." So you add As Currency to the functi on's
ccxlc itS shown below. The method has no argumcnLS, so its parentheses arc empty.
l'HAI'TR I) MAIUNO OWN OBJECTS
'\ ((!
Classes are code modules. properties are variables (or property procedures), and
methods arc subroutine or functi on 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. Client-side programmers never know the diffe 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 urrentl y, the scientists use notebooks to keep track of their ele-
phants. They also record each elephant's trumpeting sound in a .wav file. Your job is
to create an ArcMap environment for their work. Since 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 informat ion to
make a UML diagram of the Elephant class.
El:;r.1t
I
In thi s exercise, you will do the server-side programming to make an Elephant class
based on the diagram. Your elephant class wi ll cOllSist of twO variables and a proce-
dure that plays a sound fi le. In the next exercise, you will do the client-side program-
ming and write code to create elephant 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 create geographic
features like poi nts, lines, and polygons, and assign their geographi c 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.
Class l opens and looks just like any other code module. This one will store your
Elephant class and the code for its properti es and methods.
Crr' lItillR cllISSf!S
11 (leU
pyrighted mate'ial
o In the Properties window, for the Name property, replace Class 1 with Elephant.
Press Enter.
The Elephant class is created. Now you 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 t hey will be
set by client-side programmers (including you) who make elephant objects out of
~ ' o u r Elcpham class. Fot example, aft er creating a new elephant, a cIiem-side
programmer might write
myElephant.Name = "Benny "
0 '
my Elephant.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 Publi c.
If the Trumpet mcthod wcre going to return a va lue. like a dec ibellc"el. ~ ' o u would
make it a functi on. Si nce it JUSt pla)'s a sound file, you' ll make it a subroutine.
- """.=.,., --- J CI' I
'*' ~ I
. ~ .
- ,. .. I,
,.. ..... " I ....
,
'i L' l ( 1 () 11 t tt' f)
D Click OK.
10 Inside the Trumpet subroutine. add the following (ode. (If you have installed the
dat a at a di fferent location, you wi ll need t o modify t he path accordingly,)
s ndPl aysound _
C: \ ArcOb j e c ts\ Data\ e l ephant .wav , _
SND-p5 YNC
This code is a hi t differcni from anything you' ve seen before. The sndPlaySound
function does nO( come from either VBA or ArcObjcclS, bur is a Microsoft Windows
Application Progmmming Interface (API ) functi on. API functi ons carr)' out operat -
ing system operat ions like playing sound fil es, fi nding out who is logged on to a
computer, or rcrri eving the path to the Temp folder.
To cal\ an API functi on in YBA. ~ ' o u fi rs[ have to declare il in another code module.
(You did this in chapler 6 when you dedaTl-d the KilQb'f'amToPound function in onc
module and call ed it from another.) In this exercise, the funcrion has already been
decl:m.'CI for you in the standard modul e called PlaySounds.
The sndPlaySound functi on has two llfb'llmems: 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 lets more code run while the sound fil e plays.
Functions return a val ue. but you don't al ways have to use it. The sndSoundPlay
function returns True if the sound plays and False if it doesn't. To keep the El ephant
code simple. you aren' t going to use the returned value.
To learn more about the sndPl aySound function and its options. go ro
msdn. microsoft .com and search for sndPlaySound.
Your elephant class is now complete. Gramed. it's a pretty simple class. but it relics
on the same coding princi ples 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\ Chapter09. Rename t he file my_ex09a. mxd and click.
Save. If you a re cont inuing wi t h t he next exercise, leave ArcMap open. Ot herwise
close it .
C rt!fllillg c/1I.>.S('S
pyrighted material
I
Creating objects
Up to now, yOIl have created objectS 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
CommandButt on objects b)' dragging them (rom the Visual Basic Editor Toolbox
onto the (onn.
Now you will crcatc obje<: ts with code, by declaring and scHing variables. Variables
represent not onl y basic data types like numbers. dates, and srrings. but can also
represcnt objects.
Variables that represent basic claw t ypes arc called intrinsic vari ables. 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 variabl es. TI1Cse \' 3ri;lbl cs <ITC .. Iso
dcclart.-d ,md set, but the code is a little dif(crt'm. When you declare an object vari
able, you 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 elephant 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 elephant s.
Dim E1 As Elephant
Dim E2 As Elephant
Se'
E1

New Elephant
Se'
E2 = New Elephant
CII AJ'TR 9
SLcrlu71 ta'l)
After creating them, you can set their propert ies so that each one is unique.
El.Name = "Jerry"
El.Age = 24
E2.Name = "Ron"
E2.Age = 28
What about objecrs rou creatc through the user imerfnce! You don't hnve to declare
nnd set object variables for them because VBA docs it for you. When you use Visual
Basic Editor to create 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 form fnnXYZ. You can now proceed to set its properties and run its
methods wit h code like the following:
frmXYZ.Show
Exercise 9b
In the previous exercise, you made an Elephant class and programmed its properties
and methods. In this exercise, you will make new objects out of this class and use
their properties and methods.
D Start ArcMap and open ex09b.mxd in the C: \ArcObjects\chapter09 folder.
On the Standard [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 butt on's empty click event. You will write code there to
create elephant o b j ~ t s from 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 t he Dim and Set lines run, a new objeCl is in yourcomputcr's mcmOf)' and you
h,lVc a variable (theElephant) to refer to it .


D Type t heelephant. (including the dot).
Your Elephant class is recognized by VBA as a full fledged cl ass. As with any other
object \'ari able, after YOli type the dot YOli see the dropdown list of its prop<'rt ies and
mClhods .
. .. , .... . ..... ,,-)
.... !O ...... , .
l OCI . .... I
-- ,,-
Next . you will wrile COOl' to SCl this new elephant's propert ies.
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
writ e 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 li nc. "bCrLf (carri age
ret um line feed) wi ll put the elephant's age on the second tine.
Ms gBo x " & theElephant.Na me & vbCrLf &
"Age: " & theElephant . Age , _
vblnf ormation, "Add Elephant"
So, , ........... " .... I
' .. 01 ....... ' . _ ' ... .0 4 ...... _, ' ,
''''"01 ....... '._ " ' .. too, , "b, .. _ , ",
.. "M_, ..... U ........ N_
"Age' " .... .... ,.-. -
"" "'_" , "UoO ., ...... ,
.... .....

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 Edi tor.
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 for 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 OK. 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
Programming with interfaces
U ~ i n g 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 ..... orking 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.
Suppose 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 group
applies to animals in general.
An inrerface is a logical grouping of properties and methoos for a class. It mi ght be
based on the level of generality or on some other 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 mi ght be called IElephant and
IAnimal. On a UML diagram, interfaces are shown with lollipops.
ighted material
You may be thinking that i( that's all there is to an intcrf;lce, it's pro.'tty simple. In
fa ct, 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 Mi croso(t. A major benefit of COM is that it allows code wrinen
in one language, like Visual Basic. to work wi th c.ode written in another language,
like C++. The ArcObjects interfaces and classes, for example, are creat ed with C++
and you can program with them using YBA.
In this book, you' ll work with existing ArcObjects classes and interfaces, but ~ ' o u
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
properl y 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 whi ch
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 ri able, you have to choose one of its interfaces.
' .... o-f
Ctli\I'TI'R 10 PROGRAMMING Wln l ll'o'TFRFi\CES
"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
decl are 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 Name prop-
erty is set equal to a string.
Dim pMap As I Ma p
Set 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 IActi veView interface.
Di m pActiveView As IActiveView
Set pActiveView = New Ma p
pActiveView. Extent = someNewEx tent
You onl y have access to the propenies and methods of the interfuce to which a
vari able is declared. So with pMap you onl y have access to IMap's properties and
methods. and with pAcri veView you only have access to IActi veView'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.
Vari ables like pMap and pActi ve View are called pointer variables because they JXl int
to a specifi c interface. You can say that pMap points to the IMap interface and
pActiveView JXlints to the IActiveView interface. By conventi on, pointer vari able
names have a "p" prefix.
You may be wondering why you haven't had to use interfaces with VBA objects.
Don't they have t h e m ~ 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 (or 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.
For e xample. rou can creat e a class and tell it to use t he ArcObjeC[s IContentsView
interface. The robs in t he ArcMap table of colll ems CilCh have t he IComcntsVicw inter-
face. When your class uses that ArcObjects interface, it fi ts in with other ArcObjccts.
lContenrsViewon your obj ect is recognized by ArcMap and becomes another tab in the
ArcMap table of content s. The custom tab shown below also has some ArcC.-ualog
imerfaces. TIl e re.s ul l is a new tab t hat cOnlains a full y funel' ion .. 1 ArcC.'ltaIOS tfCe .
. .... __ ... -.......
'"" ... - I , - __ __________
o 16 iii .. r.I :::J :1. ,... I{/
.'-
- ... "
.

...J ."... ..
.
...J ,,,h
::..J <I ' ..
...J "'""'_
...J 00l000,0
",J a-n

",J .,....,n
...J Ooooloo"
..;l a-II

W <I>00l00.1
.:J a.... ..

.,J ....... .20
U _
-
(USlom lab

I
A '
'1



When interfaces .. re hidden . you can't use t hem to make )'our own custom cl .. sses. In
t h is book, you won', reap the benefi ts of exposed ime rf .. ccs-rhat harvest wi ll have
to w .. it unt il you start programming your own ArcObjeCls.
CII AM'I!.R 10 PROGRAMMING IN11ORFACE$
"i\.'(llllll lll',1
Using IApplication and IDocument
Normall y, 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 already in use are the Application object and the
MxDocument object. Since these objects are in use, it (allows that variabl es have
already been declared (or them. The name o( the Application object variable is
Appli cation. 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, all ArcObjects vari ables 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 conventi on of beginning with a lowercase "p.")
The Application vari able 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 ~ ' "
I Application
Appliut ioo - tAo>-.... 1ion

Cilption property
The code below uses the pn.:.-ddlni..d Applicati on variable to set the ArcMap window's
caption.
Appl i c a t i on. Capt ion = Save El ephants
In class diagrams, the barbell s next [0 a property tell you whether you can get or set
the 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 IDocument int crt.lCe on the MxDocument
class. The ,'ariable has access to al l the I Document propert ies and methods. among
whi ch is the Title propeny.
ThisOoc:ument -
Title property
on 1000l.lrnent
CHAPTER 10 PROORAMMINO WITIt tNT\!. RFACE.$
....i L ( r I () n t tt' ()
In the diagram, all of IDocument's properties h:tve left -sided barbells. which means
you can onl y get thei r values. Say you W3nt to 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
wi th the foll owing code. No need to declare or set me ThisDocument vari able.
Msgbox ThisDocurnent . Title
Exercise 10a
You have been asked to make some changes to the Washington. D.C. , Police
Department's Crime 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 applicat ion a more meani ngful title.
Because the crime map conmins dam that should only be seen by certain dett>(; tives,
you' ll write an If Then statement to check the user's identity. As the crime map
opens, your code will ask for a password. Users who know it are authorized to open
the map; others will get a warning and be scm to a less sensi tive dty street map.
When ArcMap starts up. its title bar contains three elements: the name of the .mxd
file, the name ArcMap, and the name of the current software license (Arc View,
ArcEditor. or Ardnfo). Your first msk will be (Q use the Appiicmi on object'sC., ption
property to set a t ide that wi ll be more meani nb.{u l to poli ce personnel.
Appllcltlon
"" - I 5 ____
+ 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. .:.'
>d m,-,,' ,al
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 Arclnfo depending on ~ ' o u r license),
U Click the Tools menu, point to Macros, and click Visua l Basic Edit or.
D Unless the ThisDocument (ode module is already open, go to the Project wi ndow.
Under Project (ex10a.mxd), under ArtMap Objects, doubleclick ThisDocument .
Thc ThisDocumcnr code window opens, and rou sec the code you wrote in
chapter 6 for 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 Initialize event is to the
UserForm. 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 ArcMap title will be
repl;l ccd by a new one. Otherwise, a warning will appear, and ;l less sensi ti ve street
map will olX'n.
D In the Open Document event, add t wo 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 String
strPa ssword = InputBox{" Enter password")
You wiUser up an IfThcn smtcment TO verify 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).
,
I.. C [ I tJ 11 t tV 0
After typing the dot, you see a list of Application's properties and methods.
Duo . h .... .. . " ..,
1.,. ... 0 .. , ............... 1
1I
Since the Appli cati on 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 Pl opefty
II Finish the line above by setting the Caption property t o 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:
IApplicfIIloll (/lId IDocIl Illt'1/I
" ,
:-yrl m n
D After t he Else keyword, add t he following code to concatenate the map
document's t itle with t he warning instructions.
Msgbox ThisDocument. Ti tle & is a s ec ure map . & _
"A st ree t map wi l l be opened f o 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 specifi ed map. Because New Document is on the IApplication intert.'1ce,
you can still use the predefined Application vari able.
Appliut ioo
AppIle.Uon
v,ri.blt - 1AWic.1ion
m Add the following line of code t hat uses the NewDocument method and a path
to t he 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 Distri ct's boundaries and streets
but no sensitive crime daw.
Application.NewDocument _
Fa lse , _
"C : \ ArcOb jects\Oa t a \ dc\str eet 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 false.
CHAPTER 10 PROGRAMMING .... ITH INTERfACES
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 onl y 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"'" _._d1
" ",,_, ' . .......... 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 ArcMap, 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 f ol der.
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, ,,.
II] Cl ick OK on the warning message.
A new map opens with the strcelS and prcci nclS 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_exl0a.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
sure the "C" in Carter is uppercase. Click OK.
The crime map document opens. TIle applicati on title is now Disrrict Crime .
. -'.'''-
. ~ I
m If you are continuing wi th the next exercise, leave ArcMap open. Otherwise
close it .
If you leave ArcMap open, the application title wi ll remain District Crime. The title
stays unt il you nlO code to change it. or until you quit ArcMap.

.'\L'Cl/!)ll [tt'O
Using multiple interfaces
In the previous exercise, you used the Appli cation and ThisDocument predefined
variables. The interfaces they poi nt to, IApplication and IDocument. don't have
many propert ies or methods. It's great to have these twO variables as start ing points,
but there !l fe other 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
poi nti ng to onc interface on an object, you can write two lines of code to declare and
set a second vari able to point [Q onc of that object's other interfaces. You end up
wi th 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 wi th conventi on, 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
I h I ' ~ material
You now havc tWO dogs. The firs! dog. referred 10 wilh the pDogJ variable. is
namelt'ss but barkt"d twice. Tht' St'cond dog. referrt"d 10 with the pPcrZ variable. is
named Rex and has nO( yet barked.
..,
Now what if you want Rex to bark ! The pPCIZ vari ablc points 10 the IPel interface.
which onl y gets you to the Name and IDTag properties.
You might be wondering if you can uSt' the pDogJ "ariable. and write:
pDogl.Bark
You can, but that will only 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 vari able equal to thc vari able you al rc<1dy havc. Swit ching interfuces is
calk-d Qucr.,. lnterface. or QI for short.
To get Rex to bark. rOll dcc!:! re a second pointer "ari<1blc to the I Dog imcrfacc.
which Ims Ihe B.'uk mel hod.
Dim pOog2 As tOog
Insl ead of sen ing the variable equal 10 a New Dog (which would creal e 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 poinLS to the IDog interface. you can use the Bark method. The next
line of code geLS Rex to bark three timcs.
pDog2 . Bark 3
,etll(Jl\ lit"
The pPetl variable points to Rex's IPet 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. Now how about gett ing back to the other dog and giving it a name! The
vari able pOog\ points to the nameless dog's IDog intcrfuce, but 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 vari able equal to the one you already have.
Dim pPet1 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 namel ess dog's Na me property with the pPel l vari able.
pPet1.Name : "Rada r"
And. of course, you can still make Radar bark (again) with the original pDog 1 vari able.
pDogl.Bark 4
In all, you have four vari ables 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 ,.
Exercise 10b
Over time, the crime map will be updated and used by many differem pt."Oplc. In this
exercise, you will wri te code to keep t rack of whi ch users open it. This wi ll help you
see which members of the depart ment are gett ing the most value from the map.
You' ll SlOre the informat ion in the mapdocumem's Properties dialog box, which has
input boxes for things like the map's titl e, subject , and amhor. Specificall y, 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 thi s exercise. you' ll write code to make
the ArcMap wi ndow Rll thc display screen.
D Start ArcMap and open ex10b.mxd in the C:\ArcObjects\Chapter10 folder.
S For the password, type Ca rter. 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 password code is located in the OpcnDoc.ument event procedure in the
ThisDoc.ument code module. You' ll go there to writ e more code.
D Unless ThisDocument is already open, go to the Project window under Project
(exl0b.mxd) and doubledick ThisDocument under ArcMap Objects.
The ThisDocument code window opens and you sec your code (rom earli er exercises.
CIIAI'TER 10 PROCRA)' IMINC WITt! INTI;:RPACES
l' l l I
o Click the object list drop-down arrow and dick MxDocument . Click the procedure
list dropdown 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<lt ion class's IApplication interface. In this exercise. you will switch to the
IWindowPosit ion interface. also on the Appli cation class. IWindowPosition has
propert ies for controlli ng 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<l mple, the Applic<ltion class has
ten interfaces. but only two are shown in the following diagram. Also. all of the
IApplication interface's methods have been omitted.
lWindowf'ol,illon - IW .... Poaltioto
To get to the properties for setting the window size, you need a variabl e that poi ms
10 the IWindowPosition interface. You can start (rom the prl!defined Applicati on
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 vari able.
lIIf1fIiP/' 11/1('Iftla'S
11 11l'O
D After the If Then line, but before the Application.Caption line, add t he following
line of code to declare a variable 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 vMi ablcs pointing to twO diffcrcnt Appl ic:nion interfaccs. as
shown in the foll owing graphic:
D Add the following line of code to set the Application window's State property to
esriWSMaximize.
pWindow.State : esriWSMaximize
This code will the ArcMap wi nclow for the District Crime appl icat ion. To
leam more about the options for the Stal e property. you could highli ght State i n the
code window and press Fl to open the ArcObjL'CtS developer help window.
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 ~ l r e controlled by properties on
the MxDoc:ument class's lDocumentinfo interface, shown below. You will set the
Comments property.
ThisDorurMnt
vu(,ble --,_ o-{
IDocumentinfo
Interi.ce - IOon' ,. OdO 0---
=-=
" "
-
~ o . " "
Once 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 vari able for lDocumendnfo and SCI it equal t o the ThisDocument vari3ble.
f 'sillR IIIII/Ilp/e ',,'etj(/C('$.
'9
10
~
ighled mate ial
-


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 IDocumentl nfo.
Dim pI nfo As IDocumentlnfo
, &O.oo.G .. ""'00
........ _ .......... ., ...... "' .......... .
It "CO"., " ......... . n.o.
II
D ... .. , _ _ u 11'_' _"',0
... ,,,_ .
... -..................... .
"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 li ne of code to set the variable equal to
ThisDocument.
Set pInf o : ThisDocument
You now have rwo variables poi nting to two different interfaces. As shown in the
simplilled MxDocument class diagram below. ThisDocument points to the
IDocument interface and plnfo points to the IDocumendnfo interface.
MIlDoculMnt

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
& " Aut horized" & vbCrLf
The empt y quotes sepamt e the entries and put spaces between the t ime and the user
name. You won't sec what [he full commem looks li ke umil after the code runs and
you have a chancc to open lhc Properties di alog box.
CUAI'TER 10 WITIIINT(RPACES

'. ,
,l.lllrJ
... ............. . , .. ...
' ......... d , .. ", ... t "Ia,", ....... d,
.... . "" ... ,-_.<."".
h' , l aC n _ _ ...
I. ""'0'" , .........
DO. .................. _.u ..
So ,._ ' .... ..
,_.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.nicall y. 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

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
foll owi ng 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 ,.
Ie Add the following line of code to save the unauthorized user's information.
Appli c a tion . SaveDocument
When thc uscrenters an incorrect password, thcir password and time are added to the
comments arca and the SaveDocumellt met hod 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
- . .
"CO" ... --. __
a>v .... TIoI. _ _ .'. T,,'. ' - .......... _ . - ,
- . . .... .... . , IL ...... _G 1M ..... -
he ., . IIo _ _ o. _
..... ,

.... "
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 this 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 incorreCt password to Simulat e an unauth orb;.'(1 user.
m Click the File menu and dick Open. Open my_ex10b.mxd in the
C: \ ArcObjects\ Chapter 10 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 wi ll open the document wi th the com.'Ct password.
m Click the File menu and click Open. Open my_ex10b.mxd in the
C:\ArcObj ects\Chapte r10 folder.
m For the password, type Carter. Click OK.
The District Crime document opens and its window is maximi zed.
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 authori zed 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
software, 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 another
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 cont inue to work in the future 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 inui ng with the next chapter, leave ArcMap open. Otherwise close it.
UsiIlJ.: 1IIIIIIiple illll!rfilCi"S
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:

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 hardcoded 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 of the
path is hard-<oded.
You can go up as many levels as you want by using seu of dou:
" .. \ , . \ .. \ streets .mxt
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 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
Navigating object model
diagrams
GCUIllIo:
CrO:dfiliK r!lld tL"iWling ('olor .
So far, as you've worked with obje<: ts--gctting and setting thei r propcn ic5, running
methods. even switching interfaces-you've worked with onc class at a rime. But
you know, of that there are hundreds and hundreds of ArcObjccts c1asst.'S.
The ArcObjccts you're fa miliar with. like Applicati on and ThisDocumem, arc
always ri ght there waiting for you, like a limousi ne at your door. Typically, however,
you need to work with objects that are not quite so obligingly at your service. For
exampl e, suppose you want to program a button to change the color 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 RGBCol or 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 object with the New keyword, and after that )'ou can
get and sct properties and run methods.
Dim pColor As IRGBColor
Set pColor : New RGBColor
pColor.Blue : 180
But your gool is to make the Rivers layer bluc. How does [he code know which layer,
in whi ch 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
It's kind of like hopping to a marker in a game of hopscotch, or 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 way from the
MxDocutnent class (MxDocument is the map document or currently opened .mxd
file) , to the Map class (the Map class in ArcObjects refers lo a data frame), 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, 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 special connections or
relat ionshi ps between classes. The MxDoculllent class is associaled wit h the Map
class, or connected to it, and thai 's why you can go ftom one to the other. However,
the MxDocument class is not 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 from one class to another. This relati onship can usuall y 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-{
.... .

Other symbols on the di agram give you additi on31 informati on about how the classes
are relat ed. The asterisk by the Map class means multiplicity. In other words, a map
document can have many m;!ps in it. The relationship 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
associated objects. You can think of the object with the diamond as a container. The
map document contains maps. If you del ete the map documelll, any maps inside it
aTe deleted too.
Navigming object model diagrams means hopping around from one class to another.
Now we'll consider how Ihis hopping is accomplished technicall y.
Classes have propert k'S on their interfaces. When you set a propert y, 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"TR 11 NJ\VIGJ\TING OBJECT MOIlEL 1)IJ\GIVoMS
. ' 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 tells you which data
frame in the document is active.) What this means is that FocusMap doesn't return
a map object, but it returns a poi nter to a map object's IMap interface. Through that
poi nter, 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 obj t:ct) from another. To make the connection, a property
on the one object will return an interface of the connected object. Here the
FocusMap property on IMxDocument returns t he IMap interface of the connected
map object. If you want to hop from the MxDocument class to the Map class, you
get the FocusMap property.
Let's look at how to write the code that takes you from MxDocument to Map.
Your starting poi nt is the prcdeflnt:d ThisDocumem variable, which points to the
IDocument interface on MxDocument.
ThkOocunwnt
prlHlefiMCI
ghted material



I
,
I
Since me 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. Since 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 would do the s.."l me thing: find a property in the Map
class ( IMap has a Larer property) that returns an interface of the Layer class ( the
Layer property returns ILayer). Since Querylnterface isn '( needed here, it onl y takes
two lines of code to b'O from Map to Layer.
Dim pLayer 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 object model diagrams. which arc
poster-sized drawings that show not onl y c1asscs with their propcnies and methods.
but also the relarionshi ps berween c1asscs.
A si ngle diagram is not big enough to hold all the ArcObjccts classes and their
interfaces. In fact, there are many diagrams, org::mizl..--d by categories of classes. For
example. the Geometry diagram contains classes for poi ms, lines, and poln:ons. The
Gcodatabasc diagram contains classes for tables, fe<.l ture classes. rows, and fi elds. If a
class on one diagram is connected [Q a class on a differenr diagrnm, you will be
referred [Q that diagram (jUSt as an atlas may refer you to a map on another page).
The following object model diagram shows more than a hundred classes, one of
which is the Map class and its interfaces.
CUAI'TER 1 1 NAVl(';ATlNO OBJECT ~ t O I ) E L OIAGItAMS
--- -
-
_.
--
, ,
{ ; \ '
The oval that t he Map dass is ass()(i3ted with t he !..lyer dass, which is f ound on t he Map layer dl Cl grollm.
Obj\.'Ct model diagrams arc pretty detailed, but onl y use about eight different
symbols. Once you learn these symbols. and get a little practice, you'll be abl e 10
follow a di agram as easily as you would a street map. (Or ma},be morc easily!)
Object model diagrams arc located in the devel oper 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.'l ce, you can buy printed posters
(rom 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 ArcObjCClS classes. As usua\'
it's not quite the whole story. The association relationship that you' ve been learning
about is actually JUSt one of three class relationships. Now we' ll talk a linle bi t about
the other two.
Insumtintion. also calk-d the Creates relationship, is a relati onship in which one class
has OJ method that creates new objects from another class. Imagine a Shocmaker
class with a CreateShoes method. Running this method creates a new object from
the Shoes class and returns you its IShoes interfuce. l n 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
The third type of class relat ionship is inheriumce. Inheritance is Whe!l [1 particular
class US<.'S an interface (programmers say "implements" an interface) from a more
gencml class.
Remember when in Ihe last chapter we mlh.-d aboUl grouping the Elephant class's
properti es onlO different interfaces! Propert ies specific to elephants weOl on the
IElephant interface, and propen ies that appli ed to all ani mals ",em on IAni mal,
where they could be used by the Giraffe class, the Moose class, and so on. On an
object mcxlel diagram, 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 somethi ng li ke Animal, and draw the IAnimal
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 t han a schematic convenience, a parking place (or an interface
that is used by many different classes.
Inheritance is shown wi th soli d black li nes and a t riangle. Below, the triangle is on
t he L,yer class, wh ich means t hat the other connected classes inheri t all of L'lyer's
interfaces (which in this case is just ILayer).
_ $_
" .... "
The RasterLayer. and TINLayer classes all inherit from the Layer cl ass. This meani that
all cI.use, implement the int erf ace. which is drawn on the abstract Layer etass. Thl!
triangle points to the abst ract clan (aliO call ed the superdan).
CHAPTER I I NAVIGATING OKj ECT MO!) ElIllAGRAMS
( ! I I I
Since you' re going to work with abstract classes in this chapter, let's sec how you
write code for them. Suppose you want to create a new FeatureL'l yer 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 relationshi ps means
that there are different ways to diagram classes. (You might havc noticed this in the
previous di agrams. )
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 3D whi te 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 or method) to make or get these objects.
Coc/a.ues are drawn as 3D gray boxes. These are the kinds of classes you're already
familiar 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
,
I

,
,



I
Getting layers
In this exercise, you'lI ..... rit c 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 shown below. except that
you'll stan with MxDocumcnt (where the proocfi m ..cl ThisDocumcm vari able is
waiti ng for you) and ski p the step of happi ng from Appli cation to MxDocumc[)I,
::
,
dar
!
, .. '


...
-

~ , . .
'1'

,
,
f
l
~ ~ '"'" _105 5 , I"" _ ~
o Iii' IiiUt ,- ' __ '-'

C
'.-

,
.-.
-
...
' _J
_1-'
.....
. .. -ft
~ a .

5. ...
. .. ... m
'.-
...
Along the way. you' ll do a couple offun t hings. You' ll write a For Each loop thm
cycles through each layer in the drma {mme to tum it off. And you' ll SCt 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 wondering how }'ou' li ever learn all the class relationsh ips on rom own
and be able to navigate easil y from one class to another. It can be a little overwhelm-
ing at first , hut it's like learning rom \Va}' around a net work of hiking trail s. You make
some wrong rums. get lost :1 few times, but then you develop a sense of how every-
t hing is connected and it stan s to become automati c.
Surprisingly, you probably know more t han you think about class relat ionshi ps,
because you h;we been an ArcGJS user. For example, you might not need the diagram
above to (ell you that Maps contain L, yers, because in your ArcGIS experience you
have addl.>d hundreds of layers to maps. You already know they have a rel ationship.
If you've evcr deleted a map. you know the !a)'ers gel deleled (00.
CIIAI'1l!R II NAVIOATING DajECT >I OOL Dlf"GKAM$
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 diamond tdls )'QU maps have layers; lhe stm s., )'s a tnllP can have many
The Layer class is not shown on this diag"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
\ Di agrams folder.
Layer gets a diagram to itself bccausc it has so many coclasses.
CIIJ\PT[II. I I NJ\VIGJ\TING OHJF.UT MQPEI. 111i\(lMMS

.'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 Start 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 maximi zes 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 t he Crime Analysis t oolbar. right-click Clear(ri me and click View Source.
Vi sual Basic Editor opens and you see the ClearCrime 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
acti ve 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
\
II Add two lines of code to swi t ch to the IMxOocument interface.
Dim pMxDoc As IMxOOcument
Set pMxDoc :: ThisDocument
Now t hm you have a variable pointing to the lMxOoc.ument interface. you can get
a map object in t wO lines of code. by declari ng II variable and serling il . You d ~ l a r c
the variable as IMap. because t he FocusMap property returns the IMap int erface.
D Add two lines of code to get the active map f rom the map document.
Dim pMap As lMap
Set pMap = pMxOOc. FocusMap
Once 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 posi t ion in th e table of contents. The lOp layer is
at position 0, the second layer is at posi tion I, and so on .
___ 1_ .....
D Declare an Ilayer variable.
You declare t he variable as IL'lyer ix-cause the L'lyer property returns the ILayer
int erface.
Dim pLayer As ILayer
You will SCI Ihe pLayer variable inside a For 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$
llllJll ru'CJ
IllJ Start a For loop that begins wi t h 0 and ends with the position number of t he
map's last layer.
For i = 0 to pMap.LayerCount - 1
Next i
Thc formula pMap.LaycrCount - 1 gives you the index position of the last layer. no
man er how many laycrs a map cont ains. For example, in a map wi th ten layers, the
fi rst is al position 0 (the fi rst item in most ArcObjects lists is number zero) and
the last 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 more layers in the map.
On thc Layer di agram below, you can see that the lLayer interface has a Visible
property. You tum layers on and off by setting the Visi ble property to true or false .

-I- Vo , . ,
m Add another line of code to turn the layer off.
pLayer. Visible = False
... ...... ' ....
k . . ... . . .. """ .., .... .
' ''r _ 0 To . .... "" ... ..:0 .... _ 1
,
-
A lthough your code affects bot h the ArcMap table of cont ents and the map display,
dH.ose pans of the application do not change unless explicitl y told to do so. You will
add some code to redraw these areas.
Tlble of
(onttnll
'" 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 UpdatcComems method on the IMxDoc:ument inrcrfrlce redraws the table of
contentS, but not the map display.
To redraw the map di spby, you need the IActiveVicw interfrlcc on the Map class.
You can get there using the ACliveView propcrt \' on IMxDoc: umcnt.
. ' \ ~ 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 ClearCrime burton will work whether the user is in data
vi ew 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 vari able points to the lMxDocumcn[ interface,
which h:lS the ActiveVicw propeny.
Ii) Add a li ne 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 Cl ose Visual Basic Editor.
m Turn all layers on by checking thei r boxes.
III Cl ick the ClearCrime button.
Get/IIII-: Itl)t,"S
1. 1"'"
...-1
,- yrighl:!d ma,
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 cont ents (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 tabl e of cont ents leaves you with more vi ewing space. If you had a
bunon to tum lhe layers back on, you could uS<' the application wi thout 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-

-
III .... '_
0.-
0--
111"0'"
-
,
,
._-
-
-
- -
-"
" ' ..

_ -"'f
-- -
:.
,
-,
As an experiment. go b.'1ck to the code and comment Out the li ne that runs the
Updrlt cCont ents method. Tl'CI) click the C learCrime bunon aga in to sec thllt the
tabl e of cOnt ents check boxes remai n checked. Click the Source and Display labs at
the bottom of the table of cont ents 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
"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 vi sibility 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
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)'out page itself. In ArcObjccls,
each color is an object that you create 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 li ght, so if ~ ' O U 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, yell ow.
black) is a color model standard in the prim industry.
Each color coclass has propcnics that you set to mi x 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
compUl er slores 256 valucs in one bYle o( memory.)
To make a sand\' yellow color wi th 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
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 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.
I
,

When you get to the RgbColor class. you' ll creat c 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 other rugged act ivities. For each
trip that gets organized, you make the support ing maps. You wam the background
color of your map to reflect Ihe theme of the vacat ion. If it's near \\,311: r, the page
color should be blue; if it's a desert l our, the page color should be brown .
Before writ ing any code. you will examine the ArcMap object model diagram to
detcnnine whi ch objects to use.
D If you need to, start Adobe Acrobat Reader and open ArcMap Object Modelopdf
from the C:\ArcObj ects\ Oiagrams fol der.
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 li nes of code you can hop from MxDocument to
PagcL'tyout. and in rwo more lines you can hop from PagcL:.lyout to Page.
---
-
- _
. .,. -
CIIAI"TER I I NAVIGATING ObJECT MODEL l)lAGRAMS

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.
Since [he Badc.groundColor property requires the IColor in[crface. you need to gct
an object that has this interface.
'"''
'----+ -
In theory, you should sec a line connecti ng the Page class [ 0 a class that implementS
IColor. But you don't, because on crowded diagrams, like this one, some connected
classes can't be shown. To find classes that implement IColor, you might hi ghli ght
IColor in the code window and press FI to open the IColor page in the ArcObjccts
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 '
---------
---
---
Cmll i llg mul (/$Sfgll fl/g colors
1
The hel p page shows fi ve color coc lasses. You can click each of them to sec which
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 diagramr
Locat ing a class on one of the twenty or 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 di agram is bookmarked in the list at the left.
Book"",kt 101"
u { h d i ~ f .. m
" 5
p :
The Find bunon (called the Search bunan in Adobe Rcadcr"6.0) will find any word
on any diagram and highlight it in blue. Before doing 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 binoculars icon at the top). In the Find dialog box.
type RgbColor and click Find.
The Acrobat Reader di splay area centers on t he RgbColor cociass, which is also
highlighlcd for you.
CiI"PTR. r I N"\' IO"TING OBltl-r MOUL I)IACAAMS

Sl!CC1(}n CW(}
-
_.
--
_.
-
---
RgbCoIOI' codau
D Use t he Hand tool (it looks and works l ike the ArcMap Pan tool ) t o move t he
RgbColor (odass to the lower right corner of t he displ ay, so you can see all the
Color classes.
., , .
-t- Fiyoe color
&lIlnl'w!rit lhe ICoior
intmM:1!
You now know which classes (MxOocumcnt, 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 m na'
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 yout
CUAPTER I I NAVIGATINC OBJECT J-IOPEL "DIAGRAMS
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 pRgbColor = New RgbCol or
, .. "", . .... u .... _ _
JI_ . ............ ro .
k ......... nuT ' ..
.... _ ............ ......
... _ ............. _._h,.. ...
.. ,,_ .... -
k . ,._ _ ... ,....,._
.. ..
... 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
from step 2 that the BackgroundColor propcny returns the IColor interface. This
means )'ou must usc Qucrylnlcrfacc [ 0 switch (TOm IRgbColor [0 IColor. (TIle prin-
ciple of inheritance tell s 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 = pCol e r
yrl n
ID Get and refresh the page layout's display. (As with the map display, you use the
IActiveView interface t o do this.)
Dim pAc tiveView As IActiveView
Set pAc tiveView = pPageLayout
pActi veVi ew.Refresh
._.1.00 ...... . . 00
.................. . . 10
....... . 0 . . .... . III
~ .. "' .... .. . eo'.'
... ,eel.' ,_. '0
... ,"" .. VI .. .. , .. " ... VI
'0< ....... v, ... .. _ c . .... .
... " ... vl ... ...... 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- = __
.-
--
,
+
._--
, -
-
- -
-
!
~ 1 4 . I I _
CII APT('1t I I NAV1GATINO ORI ECT ,",O!)El OIACRAMS

You might also like