You are on page 1of 417

Introduction to Programming ArcObjects with VBA

(Final)
Jeremiah Lindemann Lisa Markham Robert Burke Janis Davis Thad Tilton
Copyright © 2001–2004 ESRI All rights reserved. Course version 3.2. Revised July
2004. Printed in the United States of America.
The information contained in this document is the exclusive property of ESRI. Th
is work is protected under United States copyright law and the copyright laws of
the given countries of origin and applicable international laws, treaties, and/
or conventions. No part of this work may be reproduced or transmitted in any for
m or by any means, electronic or mechanical, including photocopying or recording
, or by any information storage or retrieval system, except as expressly permitt
ed in writing by ESRI. All requests should be sent to Attention: Contracts Manag
er, ESRI, 380 New York Street, Redlands, CA 92373-8100, USA.
The information contained in this document is subject to change without notice.
U. S. GOVERNMENT RESTRICTED/LIMITED RIGHTS Any software, documentation, and/or d
ata delivered hereunder is subject to the terms of the License Agreement. In no
event shall the U.S. Government acquire greater than RESTRICTED/LIMITED RIGHTS.
At a minimum, use, duplication, or disclosure by the U.S. Government is subject
to restrictions as set forth in FAR §52.227-14 Alternates I, II, and III (JUN 19
87); FAR §52.227-19 (JUN 1987) and/or FAR §12.211/12.212 (Commercial Technical D
ata/Computer Software); and DFARS §252.227-7015 (NOV 1995) (Technical Data) and/
or DFARS §227.7202 (Computer Software), as applicable. Contractor/Manufacturer i
s ESRI, 380 New York Street, Redlands, CA 92373-8100, USA. ESRI, ARC/INFO, ArcCA
D, ArcGIS, ArcIMS, ArcPad, ArcSDE, ArcView, BusinessMAP, MapObjects, PC ARC/INFO
, SDE, and the ESRI globe logo are trademarks of Environmental Systems Research
Institute, Inc., registered in the United States and certain other countries; re
gistration is pending in the European Community. 3D Analyst, ADF, ArcCOGO, the A
rcCOGO logo, ArcGrid, the ArcGrid logo, the ARC/INFO logo, AML, ArcNetwork, the
ArcNetwork logo, ArcNews, ArcTIN, the ArcTIN logo, ArcInfo, the ArcInfo logo, Ar
cInfo Librarian, ArcInfo—Professional GIS, ArcInfo—The World's GIS, ArcAtlas, th
e ArcAtlas logo, the ArcCAD logo, the ArcCAD WorkBench logo, ArcCatalog, the Arc
Data logo, the ArcData Online logo, ArcDoc, ArcEdit, the ArcEdit logo, ArcEurope
, the ArcEurope logo, ArcEditor, ArcExplorer, the ArcExplorer logo, ArcExpress,
the ArcExpress logo, ArcFM, the ArcFM logo, ArcFM Viewer, the ArcFM Viewer logo,
ArcGlobe, the ArcIMS logo, ArcLocation, ArcLogistics, the ArcLogistics Route lo
go, ArcMap, ArcObjects, the ArcPad logo, Arcplot, the Arcplot logo, ArcPress, th
e ArcPress logo, the ArcPress for ArcView logo, ArcReader, ArcScan, the ArcScan
logo, ArcScene, the ArcScene logo, ArcSchool, the ArcSDE logo, the ArcSDE CAD Cl
ient logo, ArcSdl, ArcStorm, the ArcStorm logo, ArcSurvey, ArcToolbox, ArcTools,
the ArcTools logo, ArcUSA, the ArcUSA logo, ArcUser, the ArcView GIS logo, the
ArcView 3D Analyst logo, the ArcView Business Analyst logo, the ArcView Data Pub
lisher logo, the ArcView Image Analysis logo, the ArcView Internet Map Server lo
go, the ArcView Network Analyst logo, the ArcView Spatial Analyst logo, the ArcV
iew StreetMap logo, the ArcView StreetMap 2000 logo, the ArcView Tracking Analys
t logo, ArcVoyager, ArcWorld, the ArcWorld logo, Atlas GIS, the Atlas GIS logo,
AtlasWare, Avenue, the Avenue logo, the BusinessMAP logo, DAK, the DAK logo, Dat
abase Integrator, DBI Kit, the Digital Chart of the World logo, the ESRI Data lo
go, the ESRI Press logo, ESRI—Team GIS, ESRI—The GIS People, FormEdit, Geographi
c Design System, Geography Matters, GIS by ESRI, GIS Day, the GIS Day logo, GIS
for Everyone, GISData Server, InsiteMAP, MapBeans, MapCafé, the MapCafé logo, th
e MapObjects logo, the MapObjects Internet Map Server logo, ModelBuilder, MOLE,
the MOLE logo, NetEngine, the NetEngine logo, the PC ARC/INFO logo, PC ARCEDIT,
PC ARCPLOT, PC ARCSHELL, PC DATA CONVERSION, PC NETWORK, PC OVERLAY, PC STARTER
KIT, PC TABLES, the Production Line Tool Set logo, RouteMAP, the RouteMAP logo,
the RouteMAP IMS logo, Spatial Database Engine, the SDE logo, SML, StreetEditor,
StreetMap, TABLES, The World's Leading Desktop GIS, Water Writes, and Your Pers
onal Geographic Information System are trademarks; and ArcData, ArcOpen, ArcQues
t, ArcWatch, ArcWeb, Rent-a-Tech, Geography Network, the Geography Network logo,
www.geographynetwork.com, www.gisday.com, @esri.com, and www.esri.com are servi
ce marks of ESRI. The names of other companies and products herein are trademark
s or registered trademarks of their respective trademark owners. ArcView GIS use
s HCL Technologies Ltd. Presenter software under license.
C O N T E N T S
1
Introduction to Programming ArcObjects with VBA
Welcome to Intro to Programming ArcObjects Logistics Course materials Course obj
ectives Course timeline What is ArcGIS? Software support resources Learning path
s VBA: Visual Basic for Applications What can ArcObjects do? Exercise options Ex
ercise typographic conventions Exercise 1 overview Exercise 1: Install the class
database 1-2 1-3 1-4 1-5 1-6 1-7 1-8 1-9 1-11 1-12 1-16 1-17 1-19
2
The VBA development environment
Lesson overview The VBA development environment ArcGIS commands Using the Custom
ize dialog box The Customize dialog Using the Customize dialog box Creating a ne
w command Setting control properties Accessing your customizations Storing your
customizations Examining a control’s source code Demonstration Overview The Visu
al Basic Editor Understanding ArcMap software’s code storage Writing Visual Basi
c statements Some common Visual Basic functions Procedure types Running an event
procedure 2-2 2-3 2-4 2-5 2-6 2-8 2-9 2-10 2-11 2-13 2-14 2-15 2-16 2-17 2-19 2
-20 2-21 2-23 2-24
Copyright © 2001–2004 ESRI
i
Introduction to Programming ArcObjects with VBA
Contents
Navigating event procedures in a module The ThisDocument module Creating a new m
odule Creating a new sub or function procedure (macro) Defining procedure scope
Running a subroutine or function procedure Adding a macro to a toolbar Getting h
elp Exercise 2 overview Exercise 2: Explore the Visual Basic Editor
2-25 2-26 2-27 2-28 2-30 2-31 2-32 2-33 2-34
3
Visual Basic code: How, where, and when?
Lesson overview Object-oriented programming Example: Object-oriented terms How:
Visual Basic syntax Preset ArcObjects variables Automatic code completion Where:
Controls, documents, and forms Working with forms Setting properties at design
time Writing code for a form Using control properties at run time When: Form and
control events When: Map document events Saving your work Exercise 3 overview E
xercise 3: Create a user form 3-2 3-3 3-4 3-5 3-7 3-9 3-11 3-13 3-14 3-16 3-17 3
-18 3-20 3-22 3-23
4
Using variables
Lesson overview Variables Working with variables Dim (dimension) statement Assig
ning a value to a variable Function procedures Comparing values Decision making:
The If Then statement 4-2 4-3 4-4 4-6 4-8 4-10 4-12 4-14
ii
Copyright © 2001–2004 ESRI
Contents
Controlling If Then Decision making: The Select Case statement Levels of variabl
e scope Procedure-level variables Module-level variables Public-level variables
Static variables Exercise 4 overview Exercise 4A: Work with variable scope Exerc
ise 4B: Create a guessing game
4-15 4-17 4-19 4-21 4-22 4-23 4-24 4-25
5
Programming with class
Lesson overview Class Classes and objects Class libraries ArcObjects Class Libra
ries Exploring class libraries with the Object Browser Object Browser icons Crea
ting objects at design time Instantiating an object in code To Set or not to Set
? Coding a class with Visual Basic Client and server environment Distributing yo
ur classes Demonstration: Creating a simple class Exercise 5 overview Exercise 5
: Work with your own object 5-2 5-3 5-4 5-5 5-6 5-7 5-9 5-10 5-11 5-13 5-14 5-15
5-16 5-17 5-18
6
COM before the storm
Lesson overview Introducing COM COM classes have interfaces Working with ArcObje
cts COM classes More on interfaces … Polymorphism ArcObjects polymorphism Using
methods and properties 6-2 6-3 6-4 6-5 6-6 6-7 6-8 6-9
Copyright © 2001–2004 ESRI
iii
Introduction to Programming ArcObjects with VBA
Contents
Getting other interfaces Testing an object reference COM class code Using librar
y names Using the ESRI Object Browser Demonstration: Creating a COM class Exerci
se 6 overview Exercise 6: Work with COM classes
6-10 6-12 6-14 6-16 6-17 6-18 6-19
7
Understanding object model diagrams
Lesson overview ArcObject object model diagrams Relationship symbols ArcMap obje
cts Creatable Class (CoClass) Instantiable Class (Class) Abstract class Inherita
nce Property and method symbols Getting properties Setting properties Finding in
terfaces Wormholes Exercise 7A overview Exercise 7A: Navigating the object model
diagrams Lesson overview Finding object model diagrams Finding the right OMD: S
tep 1 Finding the right OMD: Step 2 Finding the right OMD: Step 3 Finding the ri
ght OMD: Step 4 Where to begin? Getting into the OMD Example: MxDocument > Map >
layer Exercise 7B overview Exercise 7B: Using the object model diagrams 7-2 7-3
7-4 7-5 7-6 7-7 7-8 7-9 7-10 7-11 7-12 7-13 7-14 7-15 7-16 7-17 7-18 7-19 7-20
7-21 7-22 7-23 7-24
iv
Copyright © 2001–2004 ESRI
Contents
8
Maps and layers
Lesson overview Loop review Object model overview Accessing maps Looping through
a collection of maps Managing flow in a loop Accessing layers Working with a ma
p’s layers Looping through layers Working with layer properties Adding a new lay
er to a map Setting a FeatureLayer’s data source Exercise 8 overview Exercise 8:
Working with maps and layers 8-2 8-3 8-4 8-5 8-6 8-7 8-8 8-9 8-10 8-11 8-12 8-1
3 8-14
9
Data access and creation
Lesson overview Data creation objects Opening an existing Workspace Connecting t
o an ArcSDE database Getting a FeatureDataset Getting FeatureClasses Pseudocode:
Adding a data layer GxDialog Example: GxDialog Exercise 9A overview Exercise 9A
: Create a layer from a shapefile Working with Name objects Creating a new Works
pace Creating a new Table or FeatureClass Field and Fields classes IField and IF
ieldEdit Creating a Fields collection Creating a Table or FeatureClass Work with
fields in a table Adding rows and values to a table Exercise 9B overview Exerci
se 9B: Creating data 9-2 9-3 9-5 9-7 9-8 9-9 9-10 9-11 9-12 9-13 9-14 9-15 9-17
9-18 9-19 9-20 9-21 9-23 9-24 9-26
Copyright © 2001–2004 ESRI
v
Introduction to Programming ArcObjects with VBA
Contents
10
Geometry and geoprocessing
Lesson overview Geometry objects Feature geometry Points and multipoints Segment
s Polylines and polygons Envelopes Zooming in to a Feature Displaying features G
eometry spatial operator interfaces ITopologicalOperator IRelationalOperator IPr
oximityOperator Area and length Spatial reference Spatial reference OMD Exercise
10 overview Exercise 10: Use coordinate input to draw features 10-2 10-3 10-4 1
0-5 10-6 10-7 10-8 10-9 10-10 10-11 10-12 10-13 10-14 10-15 10-16 10-17 10-18
11
Working with subsets and selections
Lesson overview Object Model overview SelectionSet Cursors and FeatureCursors Cr
eating a QueryFilter Returning a Search cursor SpatialFilter Three types of curs
ors Accessing records in a cursor Example: Summarizing a cursor’s attributes Rev
iew: Features and geometry Displaying a subset of features Exercise 11 overview
Exercise 11: Working with subsets and selections 11-2 11-3 11-4 11-6 11-7 11-8 1
1-10 11-12 11-14 11-15 11-16 11-18 11-19
vi
Copyright © 2001–2004 ESRI
Contents
12
Symbolizing elements and layers
Lesson overview Subclasses of Symbol Using color ColorRamps Creating simple grap
hic elements Example: Make a new element, set its symbol Defining an element’s p
osition Adding an element to the map (or layout) FeatureRenderers SimpleRenderer
UniqueValueRenderer ClassBreaksRenderer ScaleDependentRenderer Storing layers o
n disk GxLayer object Example: Saving a layer from ArcMap Exercise 12 overview E
xercise 12: Symbolizing elements and layers 12-2 12-3 12-4 12-5 12-6 12-7 12-8 1
2-9 12-11 12-12 12-13 12-14 12-15 12-16 12-17 12-18 12-19
13
Working with layout elements (Optional)
Lesson overview Object Model overview Review: Elements FrameElements Example: Re
ference MapFrames on the layout Review: Subclasses of Symbol Review: Color class
es The StyleGallery Getting style items from the gallery Example: Referencing an
individual style item Getting the item Basic steps: Adding a map surround Style
Selector Printing a layout Exporting a layout Exercise 13 overview Exercise 13:
Working with layout elements 13-2 13-3 13-4 13-5 13-6 13-7 13-8 13-9 13-10 13-11
13-12 13-13 13-14 13-15 13-16 13-17
Copyright © 2001–2004 ESRI
vii
Introduction to Programming ArcObjects with VBA
Contents
14
Using tools
Lesson overview Tool events Getting the user X and Y Display transformation Conv
ert display coordinates to map units Example: Rubberbanding IGraphicsContainer M
anaging graphics Refreshing the display Partially refresh the display Exercise 1
4 overview: Choose one Exercise 14A: Create a tool to draw point graphics Exerci
se 14B: Create a Parcel Proximity tool 14-2 14-3 14-4 14-5 14-6 14-7 14-8 14-9 1
4-10 14-11 14-12
15
Data management
Lesson overview Name objects Object Model overview: Name classes Creating a Data
setName Data manipulation objects Converting feature classes Exercise 15A overvi
ew Exercise 15A: Data conversion Editing with a cursor Editing cursors Example:
Updating misspelled attributes Adding a field Creating a domain Adding a domain
to a database Assigning a domain to a field Exercise 15B overview Exercise 15B:
Data management 15-2 15-3 15-4 15-5 15-6 15-7 15-8 15-9 15-10 15-12 15-13 15-14
15-15 15-16 15-17
16
viii
Application framework and events
Lesson overview Customizing the user interface CommandBars class 16-2 16-3 16-4
Copyright © 2001–2004 ESRI
Contents
Types of CommandBar objects Components of CommandBar: CommandItems Finding a Com
mandItem Finding an ArcGIS toolbar or menu Document events Example: Displaying a
different context menu Displaying a new shortcut menu Creating new menus Creati
ng commands to execute macros Updating the ArcID module Lesson overview Inbound
and outbound interfaces Finding outbound interfaces Using an outbound interface
Events supported by Map Capturing object events Coding object events Exercise 16
overview Exercise 16A: Program the user interface Exercise 16B: Coding ArcObjec
ts events
16-5 16-6 16-7 16-8 16-9 16-10 16-11 16-12 16-13 16-14 16-15 16-16 16-17 16-18 1
6-19 16-20 16-21 16-22
17
ArcObjects beyond VBA
Lesson overview Visual Basic versus VBA Remember COM? Basic steps: Building a CO
M component 1) Create a new COM project 2) Create a COM class 3) Reference the a
ppropriate libraries 4) Implement the required interface(s) Referencing the Appl
ication Example: Branching in a COM component 5) Compile your component DLL 6) R
egistering your COM component Where can COM components plug in? Resources for cr
eating custom components Exercise 17 (Optional): Building a COM command Lesson o
verview ArcGIS Engine 17-2 17-3 17-4 17-5 17-6 17-7 17-8 17-9 17-11 17-12 17-13
17-14 17-15 17-17 17-18 17-19 17-20
Copyright © 2001–2004 ESRI
ix
Introduction to Programming ArcObjects with VBA
Contents
ArcGIS Engine Developer Kit Engine Runtime Why ArcGIS Engine Developer Kit? ArcG
IS Engine Developer Kit resources Lesson overview ArcGIS Server Why ArcGIS Serve
r? ArcGIS Server resources Exercise 17: Creating COM classes with Visual Basic (
Optional)
17-21 17-22 17-23 17-24 17-25 17-26 17-27 17-28
x
Copyright © 2001–2004 ESRI
Course name goes here ModuleTitle
Introduction to Programming ArcObjects with VBA
Welcome Logistics Course materials Course objectives Course timeline What is Arc
GIS? Software support resources Learning paths VBA: Visual Basic for Application
s What can ArcObjects do? Exercise options Exercise typographic conventions Exer
cise 1 overview 1-2 1-3 1-4 1-5 1-6 1-7 1-8 1-9 1-11 1-12 1-16 1-17 1-19
contents
Introduction to Programming ArcObjects with VBA
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
Introduction to Programming ArcObjects with VBA
Introduction
1-1
Welcome to Intro to Programming ArcObjects
Instructor introduction Student introductions
Name Organization Role in organization Programming experience GIS experience Goa
ls and expectations for this class
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
1-2
Welcome to Introduction to Programming ArcObjects with VBA. Prerequisites: Intro
ductions to Visual Basic for ESRI software (Virtual Campus course) Introduction
to Programming ArcObjects with VBA is a five day course, consisting of approxima
tely 40 hours of class time. The course uses instructor-led lectures and demonst
rations in conjunction with hands-on programming exercises. You should expect to
spend most of your class time engaged in writing Visual Basic code for the ArcM
ap and ArcCatalog applications.
Introduction to Programming ArcObjects with VBA
Introduction
1-2
Logistics
Daily schedule
Start _______________ Lunch _______________ Finish _______________
Facilities
Refreshments and break area Restrooms Telephones and messages Internet access St
udent ID badges Parking
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
1-3
Daily schedule Under normal conditions, the class will begin each day at 8:30 a.
m. and continue until 5:00 p.m. There will be at least one break in the morning
and one in the afternoon. You will generally be given one hour for lunch. Facili
ties Your instructor will provide information regarding the facilities. Internet
access Some training facilities provide Internet access for your use during cla
ss. ESRI® regards Internet access as an essential business resource for classroo
m demos, exercises, arranging travel, and maintaining contact with your office.
Please limit your use of the Internet to business activities only and, as a cour
tesy to your classmates, refrain from typing or surfing during lecture presentat
ions.
Introduction to Programming ArcObjects with VBA
Introduction
1-3
Course materials
Books
Lecture Exercise
CDs
Course data Samples
ESRI
Training Data
Online course evaluation
http://classeval.esri.com Requires Course Identification Number
Software evaluation
E-mail enhancement requests to product teams
desktop_comments@esri.com
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
1-4
Teaching methods Research indicates that students learn differently. This course
maximizes your learning experience by combining instructor-led lectures and dis
cussions, demonstrations, computerbased exercises, and review questions. Class m
aterials Your class materials include lecture and exercise course books, and Obj
ect Model Diagrams. These are yours to take home, so feel free to write in them.
Included at the back of your exercise book is a CD that contains all the data r
equired for the course. Here you will find all the map documents, data, and solu
tion code used for each exercise. You will also find over 100 different code sam
ples that are not described or used during the course, but that you might find u
seful when you begin to write your own applications. The class data CD contains
all the data sets you will work with during class. A second CD contains the ArcS
DE 8.1 for SQL Server software, which you will install later today. Course evalu
ation Your feedback improves ESRI’s courses. At the end of the week, please eval
uate the following: • Instructor • Course materials • Teaching facilities • Over
all course
Software evaluation If you have access to a Web-based e-mail account during clas
s, you can send comments about the software directly to the product development
teams. Your comments directly influence enhancements to ESRI products, so please
let us know what you think.
Introduction to Programming ArcObjects with VBA Introduction 1-4
Course objectives
Reinforce VBA programming techniques Build VBA Applications with ArcObjects
Understand Object Oriented Programming Gain familiarity with COM classes Interpr
et ArcObject Object Model Diagrams Gain comfort in programming with some of the
commonly used ArcObjects
Ask questions and participate in discussions
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
1-5
Introduction to Programming ArcObjects with VBA is a five day course that focuse
s on the concepts of the component object model (COM), object oriented programmi
ng, and understanding the ArcObject object model. Although no prior experience w
ith Visual Basic (VB) is assumed, the introductory portion of the course moves v
ery quickly. Fundamental VB topics are covered in the first couple of lessons, a
nd then applied (and thus reinforced) throughout the week. You will learn to pro
gram through a combination of instructor-led lectures and hands-on programming e
xercises. You should expect to spend the majority (approximately 60%) of your cl
ass time writing Visual Basic code. Later in the week, your instructor will give
you time to experiment on your own, either by choosing a programming task from
a set of workshop exercises in Appendix B, or by tackling your own programming p
roblem. By the end of the course, you can expect to have a solid understanding o
f the VBA development environment. You will be able to modify the user interface
, design VB user forms, and write applications that enhance or extend the functi
onality of ArcGIS.
Introduction to Programming ArcObjects with VBA
Introduction
1-5
Course timeline
Day 1 VBA Skills Working with Classes
Day 2
COM Classes Reading OMDs Maps and Layers Selections and Subsets
Day 3
Day 4
Symbolizing layers Data management
Day 5
Application framework ArcObjects beyond VBA
Introduction to Programming ArcObjects with VBA
Copyright © 2001–2004 ESRI. All rights reserved.
1-6
Day 1 Lesson 1: Introduction Lesson 2: The VBA Environment Break Lesson 3: Visua
l Basic code: How, where, when? LUNCH Lesson 4: Using Variables
Day 2 Lesson 6: Working with COM
Day 3 Lesson 9A: Data access and creation
Day 4 Lesson 12: Layer Rendering
Day 5 Lesson 15B: Data Management
Break Lesson 7A: Understanding Object Model Diagrams LUNCH Lesson 7B: Understand
ing Object Model Diagrams Break Lesson 8: Maps & Layers
Break Lesson 9B: Data access and creation
Break Lesson 13: Working with Layout Elements LUNCH Lesson 14: Using Tools
Break Lesson 16A: Application Framework
LUNCH Lesson 10: Working With Geometry
LUNCH Lesson 16B: Events
Break Lesson 5: Programming with Class
Break Lesson 11: Subsets and Selections
Break Lesson 15A: Data Management
Break Lesson 17: ArcObjects beyond VBA
Introduction to Programming ArcObjects with VBA
Introduction
1-6
What is ArcGIS?
E X T E N S I O N S ArcGIS Desktop
ArcInfo ArcInfo ArcEditor ArcEditor
ArcGIS Engine
Custom Custom application application
ArcGIS clients
E X T E N S I O N S
ArcReader ArcReader
ArcView ArcView
ArcPad ArcPad
Web Web browser browser
Components
ArcObjects ArcObjects Network ArcGIS Server ArcGIS Server ArcIMS ArcIMS ArcSDE A
rcSDE
Application/Data servers
RDBMS
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming Arc
Objects with VBA
1-7
ArcGIS is the name used to identify ESRI’s flagship family of GIS products. ArcG
IS® includes ArcGIS client software, components, and application and data server
software. ArcGIS itself is not a GIS application; rather, it is a set of softwa
re products for building ArcGIS systems that best suit your GIS needs. ArcGIS is
based on a common library of shared GIS software components, called ArcObjects™
. ArcGIS is composed of client and server applications. Each software applicatio
n can create, manage, analyze, and serve data stored in one or more formats. •Ar
cGIS Desktop: Integrated suite of advanced GIS applications consisting of three
software products: ArcView®, ArcEditor™, and ArcInfo®. The ArcGIS Desktop applic
ations provide the same core mapping, editing, and analysis functionality. The l
evel of functionality available differs depending on which license you have. Arc
Info provides users with the most complete level of GIS functionality. It is com
posed of ArcInfo Desktop and ArcInfo Workstation. •ArcReader™: Allows users to v
iew high-quality published maps (PMFs) created in ArcMap™. •ArcGIS Engine: Devel
oper toolkit of embeddable GIS components for building custom stand-alone applic
ations using COM, C++, Java, and .NET. •ArcPad®: Used with PDAs for creating and
managing data while in the field. •ArcGIS Server: A shared library of GIS softw
are objects used to build and develop serverside GIS applications in enterprise
and Web computing frameworks. •ArcIMS®: Used to publish maps, data, and metadata
through open Internet protocols. •ArcSDE®: Manages and serves spatial informati
on from external RDBMs to ArcGIS clients. For more information, go to http://www
.esri.com/software/index.html.
Introduction to Programming ArcObjects with VBA
Introduction
1-7
Software support resources
ESRI Support Center a gateway to resources
http://support.esri.com
Knowledge Base
Technical articles White papers System requirements
Downloads
Patches and service packs Data models ArcScripts
For Developers
Developer resources
User Forums
Discussion groups E-mail lists
Copyright © 2001–2004 ESRI. All rights reserved.
Request ESRI Technical Support
Available to support subscribers
Introduction to Programming ArcObjects with VBA
1-8
ESRI’s primary resource for software support is the ESRI Support Center at http:
//support.esri.com. Knowledge Base The Knowledge Base is a searchable database o
f focused technical articles. It includes answers to frequently asked questions,
step-by-step directions for performing common tasks, and workarounds for known
software limitations. The Knowledge Base also contains topicfocused white papers
organized by product, system requirement information, and product documentation
. Downloads Obtain the latest software correction, software and code samples, ut
ilities, tutorials, user contributed scripts and sample code (ArcScripts), data
models, and evaluation software from ESRI’s Download page. User Forums In the us
er forums, you can ask questions, provide answers, and exchange ideas with other
ESRI product users. Resources include several discussion forums, and two subscr
iption e-mail discussion lists moderated by ESRI. ArcView-L is for ArcView users
, and ESRI-L is for users of all other ESRI products. For Developers This page i
s for ESRI’s developer community. It provides the latest developer information,
including sample code, technical documents, and object model diagrams for ESRI’s
developer products.
Introduction to Programming ArcObjects with VBA
Introduction
1-8
Learning paths
http://www.esri.com/training_events.html
Learning Guide
Learning paths organized by software and topic
Learning options
Instructor-led courses Virtual Campus courses Training seminars Web workshops
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
1-9
Depending on which ESRI software your organization has licensed, your skills, an
d your plans for upcoming projects, you may benefit from additional training on
advanced topics, on specialized software, or on background topics to refine your
understanding of GIS and related technologies. Detailed information about Instr
uctor-led and Web-based courses—including a list of topics covered, intended aud
ience, duration, schedules, and pricing—is available in the ESRI Course Catalog.
You can access this catalog on the Web at http://www.esri.com/training/index.ht
ml. On the ESRI Training Web site, you can also find information about new cours
es developed since the course catalog was printed. Web-based courses offer conve
nience and savings. Also, many ESRI Virtual Campus courses include a free lesson
, called a module. You can create a free account and begin training with these f
ree modules within minutes at http://campus.esri.com. In addition to Web-based c
ourses, the Virtual Campus also offers free live training seminars, training sem
inars, and Web workshops. Live training seminars are focused lectures on a varie
ty of GIS topics for all levels of users. Consult the Virtual Campus for upcomin
g topics, dates, and times. Training seminars are free recordings of live traini
ng seminars, viewable at your convenience. Workshops are recordings of live trai
ning seminars, viewable at your convenience, plus printable slides of the presen
tation, questions and answers from the live training seminar, a software exercis
e with accompanying data, an optional exam to assess understanding, and a certif
icate for successfully completing the exam.
Introduction to Programming ArcObjects with VBA
Introduction
1-9
Learning paths
Foundation
i
Extensions Learning ArcGIS I ArcSDE Databases Many Others
Introduction to ArcGIS I
W
Customization / Programming Introduction to Visual Basic for ESRI software Intro
duction to Programming ArcObjects with VBA
Advanced Customization / Programming Extending the ArcGIS Desktop Applications
W
i
i
Other ArcObjects/VBA Resources Virtual Campus VBA Workshop Series Getting to Kno
w ArcObjects
i
W
B
Developing Applications with ArcGIS Engine
i
Developing Applications with ArcGIS Server
1-10
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
Courses identified with the i symbol occur in a classroom with an instructor. Th
e W symbol indicates Web-based courses available on the ESRI Virtual Campus at h
ttp://campus.esri.com. The B indicates a book from ESRI press available at http:
//gis.esri.com/esripress/display/index.cfm. Students taking this course (Introdu
ction to Programming ArcObjects with VBA) are expected to have a least a basic u
nderstanding of programming languages. The Web based course Visual Basic for ESR
I Software will provide sufficient information for taking this course. ESRI’s Vi
rtual Campus also has a 4 part VBA Workshop Series that introduces you to to the
VBA environment, also a sufficient prerequisite for this course. You may also f
ind the ESRI press book, Getting to Know ArcObjects to be an excellent resource
to get start with ArcObjects and a valuable resource even as you become more pro
ficient with using ArcObjects. After completing Introduction to Programming ArcO
bjects with VBA, you may want to further your knowledge by taking advanced ArcOb
jects courses. This course is a prerequisite to the advanced ArcObjects courses
that ESRI provides. The subject matter of these advanced courses will be discuss
ed on the following slides and the last section in this course..
Introduction to Programming ArcObjects with VBA
Introduction
1-10
VBA: Visual Basic for Applications
Evolution of software customization languages VBA: Single programming language a
nd development environment embedded within an application
Past
Applications had separate customization languages Application Access ArcView® Wo
rd ArcInfo Programming Language Access Basic Avenue™ Word Basic AML
Future Now
Applications can share one customization environment Application Programming Lan
guage
Access ArcView Word ArcInfo
Introduction to Programming ArcObjects with VBA
VBA
Copyright © 2001–2004 ESRI. All rights reserved.
1-11
Visual Basic for Applications The VBA development environment consists of two pr
imary tools: the Customize dialog box for interactively modifying the user inter
face, and the Visual Basic Editor for creating user forms and for writing, testi
ng, and debugging Visual Basic code. Because VBA is the industry standard, there
are two big advantages to programming in this environment. First, if you are fa
miliar with using VBA in a particular application, you will find it very similar
(sometimes nearly identical) in other applications that support it. Second, you
will be able to (easily) use object libraries between applications. When develo
ping an application for Power Point, for example, you might choose to embed obje
cts from the ArcObject library (or vice versa). Other applications that use the
VBA development environment Microsoft Office: Excel, PowerPoint, Word, and so on
. Visio Corel WordPerfect Office 2000 Corel Draw 9 AutoCAD MYOB Accounting (Acco
unting package for small businesses) Micrografx iGrafx series (Business graphics
) OmniTrader (Securities tracking and analysis ) Many others …
Introduction to Programming ArcObjects with VBA
Introduction
1-11
What can ArcObjects do?
Use VBA to extend ArcMap/ArcCatalog Create custom user forms, buttons and tools
Automate workflows Subject of this course
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
1-12
Using VBA to extend ArcMap/ArcCatalog Both ArcMap and ArcCatalog come with Visua
l Basic for Applications (VBA). VBA provides an integrated programming environme
nt and the Visual Basic Editor. VBA is an excellent way to create custom command
s. You can create a new button, tool, combo box, or edit box (all referred to as
UIControls), then attach code to the control’s events. Once you have your custo
m control created, you can drag it to any toolbar. Macros can also be created wh
ich can be executed from the Tools toolbar. By creating the UIControls and Macro
s you can build sophisticated ArcGIS applications for the user to interact with
and automate workflows. All of these concepts will be covered in this course.
Introduction to Programming ArcObjects with VBA
Introduction
1-12
What can ArcObjects do?
Use stand alone programming language to extend Desktop applications and geodatab
ase Create custom components to enhance functionality Extending the ArcGIS Deskt
op Applications Command Command Edit Task Edit Task
Table of Contents Tab Table of Contents Tab
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
1-13
Extending ArcGIS Desktop Applications In some cases, you will want to extend Arc
GIS Desktop outside of VBA. You can create custom objects that plug into ArcGIS
Desktop with any programming language that supports the Microsoft Component Obje
ct Model (COM), such as Visual Basic 6.0 or Microsoft Visual Basic .NET. Custom
commands or toolbars created outside VBA are often distributed as ActiveX DLLs.
If you have created custom commands and toolbars, you can distribute these as Ac
tiveX DLLs and easily add these objects to ArcMap or ArcCatalog. This will put t
he code into a binary version of the object so the end user will never see the s
ource code. Components can be broadly categorized into two areas of customizatio
n: those that reside at the application level, such as custom buttons, toolbars,
windows and extensions, and those that reside at the geodatabase level, such as
custom feature class extensions and custom features. Some of these more advance
d customizations cannot be accomplished through the VBA environment. The informa
tion on this subject matter is discussed in the Extending the ArcGIS Desktop App
lications instructor-led course.
Introduction to Programming ArcObjects with VBA
Introduction
1-13
What can ArcObjects do?
Use the ArcGIS Engine Developer Kit to build custom applications Developing Appl
ications with ArcGIS Engine
Windows Example
Java Example
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming Arc
Objects with VBA
1-14
The ArcGIS Engine Developer Kit The ArcGIS Engine Developer Kit allows developer
s to create custom applications that can be deployed to machines that do not cur
rently have ArcGIS Desktop installed. It provides the developer with many resour
ces to complete their development task. The ArcGIS Engine Developer Kit is not a
product for end users. It is strictly for people who are developing application
s. As a developer, you can build applications based on ArcGIS Engine and deliver
those programs to end users. The ArcGIS Engine supports a variety of developer
languages including COM, .NET, JAVA, and C++, which allows applications to be de
ployed on different platforms. The information on this subject matter is discuss
ed in the Developing Applications with ArcGIS Engine instructor-led course.
Introduction to Programming ArcObjects with VBA
Introduction
1-14
What can ArcObjects do?
Use ArcGIS Server to build custom Web-based applications Developing Applications
with ArcGIS Server
Geodatabase Editing
Network Tracing
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming Arc
Objects with VBA
1-15
ArcGIS Server ArcGIS Server allows you to build custom Web-based applications, e
xposing ArcObjects through the Internet or LAN (Local Area Network). ArcGIS Serv
er is a GIS enterprise application server that provides complete GIS capabilitie
s throughout an organization while maintaining a centrally managed database. Map
ping, geocoding, spatial queries, editing, tracing and linear referencing are al
l examples of applications that developers can build using ArcGIS Server. These
applications can be consumed by browser-based clients, custom applications built
with ArcGIS Engine, and ArcGIS Desktop. ArcGIS Server will support all common d
evelopment environments (Java, .NET, C++, COM) and all major server platforms. T
he information on this subject matter is discussed in the Developing Application
s with ArcGIS Server instructor-led course.
Introduction to Programming ArcObjects with VBA
Introduction
1-15
Exercise options
Exercise shortcut
Full exercise steps
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
1-16
Exercise shortcut Appearing at the beginning of an exercise, the exercise shortc
ut summarizes the steps found in the main exercise. Each shortcut step correspon
ds with the same step number in the main exercise. Exercise shortcuts are ideal
for those students who have had some experience with the software and want to be
challenged by trying to complete the step without detailed explanation. Of cour
se, if you cannot complete the shortcut step, you can refer to the main exercise
for more detail. Full exercise steps The main exercise steps provide detail on
how to complete each task. If you are new to the software, follow the full exerc
ise steps.
Introduction to Programming ArcObjects with VBA
Introduction
1-16
Exercise typographic conventions
Action Descriptive text
Note
Control name
Warning Question with hint
Copyright © 2001–2004 ESRI. All rights reserved.
Keyboard input
Introduction to Programming ArcObjects with VBA
1-17
Before you begin your first exercise, you need to recognize the typographic conv
entions used in your exercise coursebook. Descriptive text This text can provide
an overview of the next sequence of actions, a review of actions just completed
, or an interpretation of output on your computer monitor. Descriptive text may
introduce what is about to happen with phrases like “Next, create a new map in A
rcMap”; the actual instruction follows, indicated by the checkbox symbol. Action
Actions are tasks—like starting an application, clicking a button, or typing a
command—that you must perform during the exercise. The square checkbox symbol in
dicates an action; act only on instructions that are prefaced with the checkbox
symbol. You can mark the checkbox symbol in your exercise coursebook as you comp
lete each task. This is especially helpful when shifting your attention between
your book and your computer monitor. Control name Names of objects on your monit
or with which you interact are italicized in your exercise coursebook. These inc
lude windows, menus, and buttons. Many buttons reveal their names when you hold
your mouse pointer over them.
Introduction to Programming ArcObjects with VBA
Introduction
1-17
Note Paragraphs prefaced with Note: provide inconsequential information, such as
an optional way to perform an action or platform-specific syntax for a script.
Warning The large exclamation point symbol and bold text signals critical inform
ation for performing the next action. Warnings may alert you to a subtle syntact
ical rule in a command you will type or inform you that the next button you clic
k will produce an error intentionally. If you have questions about a warning, as
k your instructor for clarification before proceeding. Keyboard input Text you n
eed to type—like commands in a Command Prompt, entering a file name in a Save di
alog, and pressing Ctrl + Alt + Delete—appears in bold, constantly-spaced font.
Question with hint Questions require you to record answers in your course book.
Questions are renumbered within each exercise and may be followed by a hint. Som
etimes the answer to one question depends on your answer to a previous one. Cour
ses that use this teaching technique extensively will include an exercise worksh
eet as an appendix in your lecture course book, enabling you to record all answe
rs on the worksheet for easier cross-referencing. Answers to questions immediate
ly follow each exercise.
Introduction to Programming ArcObjects with VBA
Introduction
1-18
Exercise 1 overview
Install the class data
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
1-19
Introduction to Programming ArcObjects with VBA
Introduction
1-19
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
1-20
Introduction to Programming ArcObjects with VBA
Introduction
1-20
Introduction to Programming ArcObjects with VBA
The VBA development environment
Lesson overview The VBA development environment ArcGIS commands Using the Custom
ize dialog box The Customize dialog Using the Customize dialog box Creating a ne
w command Setting control properties Accessing your customizations Storing your
customizations Examining a control’s source code Demonstration Overview The Visu
al Basic Editor Understanding ArcMap software’s code storage 2-3 2-4 2-5 2-6 2-8
2-9 2-10 2-11 2-13 2-14 2-15 2-16 2-17 2-19 2-21 2-23 2-24
2-25 2-26 2-27 2-28 2-30
2-31 2-32 2-33 2-34
contents
2-2
Writing Visual Basic statements Some common Visual Basic functions Procedure typ
es Running an event procedure Navigating event procedures in a module The ThisDo
cument module Creating a new module Creating a new sub or function procedure (ma
cro) Defining procedure scope Running a subroutine or function procedure Adding
a macro to a toolbar Getting help Exercise 2 overview
2-20
The VBA development environment
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
Introduction to Programming ArcObjects with VBA
The VBA development environment
2-1
Lesson overview
The VBA development environment Customize dialog box
Create new toolbars and commands Add, delete, and move commands Set control prop
erties
Storing and distributing customizations Visual Basic Editor
Code storage Modules Procedures
Visual Basic statements
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming Arc
Objects with VBA
2-2
Lecture 2 overview In this lesson, you will learn about the VBA development envi
ronment. This environment consists of the Customize dialog box, which is used to
modify the ArcMap or ArcCatalog graphical user interface, and the Visual Basic
Editor, which is used to write VBA procedures (macros). The first half of this l
esson will discuss the Customize dialog box. You will learn how to modify the Ar
cMap and ArcCatalog user interface by (1) adding new toolbars, (2) adding existi
ng ArcGIS commands, (3) removing existing commands from toolbars and menus, (4)
altering command properties (e.g., icon), and (5) creating custom interface cont
rols. You will also learn how to store and distribute your customizations. The l
ast half of this lesson will teach you how to use the Visual Basic Editor.
Introduction to Programming ArcObjects with VBA
The VBA development environment
2-2
The VBA development environment
Similar environment for all applications that use VBA
Customize dialog box: Interface customization Visual Basic Editor: Writing code
Customize dialog box Visual Basic Editor
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
2-3
The VBA development environment consists of two parts: the Customize dialog box
for modifying the user interface and the Visual Basic Editor for writing code. A
n advantage of using VBA that you will soon discover is that several application
s use the VBA development environment for customization. While these environment
s are not identical, they are very similar. All Microsoft Office products, for e
xample, will have a Customize dialog box that allows you to add, remove, and rea
rrange interface controls. All of these applications will have a Visual Basic Ed
itor for writing macros or designing forms. Once you are familiar with the ArcGI
S™ VBA development environment, your skills will be portable to several other ap
plications. Customize dialog box The Customize dialog box is a powerful tool tha
t allows you to customize ArcMap and ArcCatalog without writing a single line of
code. You can create, add, move, and remove toolbars and commands, and even add
tools others have created. Visual Basic Editor The Visual Basic Editor provides
an interface for creating forms and writing code. It also provides several util
ities for debugging and getting help that will be discussed throughout this cour
se.
Introduction to Programming ArcObjects with VBA
The VBA development environment
2-3
ArcGIS commands
Toolbars and menus contain commands Commands are buttons, menus, macros, and UIC
ontrols Each command has associated code
Toolbar Toolbar
Commands Commands
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
2-4
ArcMap and ArcCatalog have toolbars that contain commands (i.e., controls). Comm
ands are things such as buttons and menus, macros (Visual Basic procedures), and
UIControls (user interface controls). UIControls are custom controls that an Ar
cGIS VBA developer can add to the interface to perform specialized tasks. There
are four types of UIControls: UIButtonControls, UIToolControls, UIEditBoxControl
s, and UIComboBoxControls. COM commands are similar to UIControls, except they a
re stored in DLL, EXE (executable), or similar files and are created by a develo
per in a full-scale programming environment such as Visual Basic or C++. Users i
nteract with commands by clicking, typing, selecting, or applying, depending on
the type of control. Behind each control, there is associated code that will exe
cute in response to user interaction. As a developer of a UIControl, you can wri
te code to respond to button clicks, mouse interaction (mouse button down, mouse
button up, mouse move), and keyboard typing. While the Customize dialog box is
open, you can reorganize commands by dragging and dropping them to a new locatio
n on a toolbar or menu. You can even drag them between toolbars and menus or rem
ove them altogether.
Introduction to Programming ArcObjects with VBA
The VBA development environment
2-4
Using the Customize dialog box
Open the dialog to put the interface in design mode With the Customize dialog bo
x open, you can …
Rearrange or remove existing commands Add new toolbars and commands Change comma
nd properties
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
2-5
In the ArcMap and ArcCatalog Customize dialog box, you will find utilities for a
dding new toolbars, menus, and commands to the user interface. You may want to s
imply modify some of the existing commands by rearranging them or changing their
icon, for example. Regardless of the interface customization you want to make,
however, you always need to start by opening the Customize dialog box. While the
Customize dialog box is open, the user interface is in design mode, which means
clicking on commands will not execute them but will instead allow you to rearra
nge them or change their properties. Once you are satisfied with the interface c
ustomizations you have made, close the Customize dialog box to begin working wit
h the controls.
Introduction to Programming ArcObjects with VBA
The VBA development environment
2-5
The Customize dialog
Three tabs (panels)
Toolbars: Turn toolbars on or off, create new toolbars Commands: Drag new comman
ds onto the interface Options: Lock customization with a password, etc.
A
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming Arc
Objects with VBA
2-6
The Customize dialog has three panels: Toolbars, Commands, and Options. The Tool
bars and Commands tabs are the ones you will use to modify the user interface, w
hile the Options tab provides some control over basic customization options. Too
lbars On the Toolbars tab of the Customize dialog, you have the ability to work
with existing toolbars by turning them on or off, renaming them, or deleting the
m. If you make a mistake while customizing the interface, you can also reset an
individual toolbar to its original state by selecting it in the Customize dialog
and clicking Reset. You may also use the Customize dialog to create brand new t
oolbars. When creating a new toolbar, you will be prompted for a name and a loca
tion in which to save it (more about storing customizations later). A new toolba
r will be nothing more than a small gray box; to add commands to a new toolbar,
use the Commands tab. Commands The Commands tab on the Customize dialog box cont
ains all existing ArcMap or ArcCatalog commands (depending on which application
you are customizing). Commands can be dragged from the Customize dialog onto a t
oolbar as a button or onto a menu as a menu choice.
Introduction to Programming ArcObjects with VBA
The VBA development environment
2-6
Options The Options tab on the Customize dialog box allows you to control some b
asic properties of your customization development environment. Lock Customizatio
n: Clicking this will allow you to provide a password to protect your customizat
ions. When a user tries to access the Customize dialog box or the Visual Basic E
ditor, he or she will be required to provide the password. Change VBA Security:
Viruses may be distributed in a macro within a document, template, or add-in. Wh
en you open such a document or perform an action that triggers a macro virus, th
e macro virus might be activated, transmitted to your computer, and stored in yo
ur Normal template. The levels of security are described in the Security dialog
box to reduce the chances of macro viruses infecting your documents, templates,
or add-ins. Update ArcID module: All commands in ArcGIS have a unique identifier
(UID) that allows a programmer to easily reference it in code. This ID is store
d in a special document called the ArcID module. Update this module to write uni
que identifiers for custom interface commands (DLLs you have added from file) to
the ArcID module.
Introduction to Programming ArcObjects with VBA
The VBA development environment
2-7
Using the Customize dialog box
Commands are organized into categories All ArcMap or ArcCatalog commands are her
e
Some that are not on the interface by default
Drag commands onto toolbars or menus
Command Categories Commands
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
2-8
As mentioned earlier, the Customize dialog box contains all ArcMap or ArcCatalog
commands. These commands are available on the Commands tab and are organized in
to categories. By highlighting a category on the left side of the dialog, you wi
ll see all commands in the category listed on the right. Some familiar categorie
s are things like Selection, Pan/Zoom, and File. You will also find categories f
or Visual Basic procedures you write yourself (Macros), for creating new menus (
New Menu), and for creating new custom controls (UIControls). Because many of th
e commands you find here are not found on the default (outof-the-box) ArcGIS int
erface, you might find a few gems here: functionality that you did not know exis
ted. Once you locate a command you want to add to the interface, you can select
the command in the dialog and drag it to a toolbar as a button or onto a menu as
a menu choice. You need to be careful, however, as controls that require user i
nteraction will not work as menu choices, and some commands only work as context
menu choices (e.g., layer properties).
Introduction to Programming ArcObjects with VBA
The VBA development environment
2-8
Creating a new command
UIControls category
User-created commands
Four types
Button Tool EditBox ComboBox
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
2-9
Creating new commands (user interface controls) The Customize dialog box contain
s controls you develop yourself in a category called UIControls. You can add the
se commands to the user interface by dragging them onto a toolbar or menu, just
as you would any ArcGIS command. To create a new UIControl, click New UIControl
and choose one of the four types described below. • UIButtonControl: a simple bu
tton or menu choice. • UIToolControl: use to create a tool. Differs from a butto
n in that the developer has access to mouse and keyboard input while the tool is
selected. • UIEditBoxControl: a text line (on a toolbar or menu) that allows th
e user to type some input. • UIComboBoxControl: a pulldown list that allows the
user to choose existing items (text) or to type his or her own. Once you have cr
eated one of these controls, the next step would be to write the Visual Basic co
de behind the control user events (button clicks, mouse, keyboard, etc.) that ma
ke it work. Adding custom commands from file Custom commands are ActiveX control
s or libraries stored as OLB, TLB, EXE, OCX, and DLL files. You can add these cu
stom commands from the Customize dialog box by clicking Add From File. Once you
add a custom control from file, it will be placed in the appropriate category in
the Customize dialog box (sometimes a new category is created). Just like the o
ther controls in the dialog, you must then drag the command to the desired locat
ion on the interface. Note: These controls would have been developed in a standa
lone programming environment such as Visual Basic or C++, and cannot be created
in VBA.
Introduction to Programming ArcObjects with VBA
The VBA development environment
2-9
Setting control properties
Customize dialog box must be open Right-click a control to view and change prope
rties Characteristics that define appearance
Name Image Display text or image Begin a group
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
2-10
Command properties While the Customize dialog is open, the user interface is in
design mode. To access command properties, simply right-click on a command and u
se the context (popup) menu that appears. With the dialog open, you can modify t
he following command properties. Name The text that appears for a command if Tex
t Only or Image and Text is chosen for display. Changing the Name property does
not affect how the command is referred to in code. Button image You can choose a
new icon for any command (including menu choices) by selecting one from the men
u or browsing to one of your own. If you create your own image, it must be a bit
map (.bmp) that is 16 x 16 pixels. Text and image There are three ways in which
a command can be displayed on a toolbar: Text only (see the Name property descri
bed above), Image only, or both Image and Text. Menu commands (choices) may be d
isplayed as Text or Image and Text; you may not use the Image only choice for me
nu choices. Groups Beginning a group adds a separator line to the left of the se
lected control. Use groups to visually organize related commands.
Introduction to Programming ArcObjects with VBA
The VBA development environment
2-10
Accessing your customizations
ArcMap has three levels of storage Templates are read in order on startup
Affects all documents Affects all documents using this template Affects this doc
ument Normal Template
Base Template
This Document
ArcCatalog only uses the Normal template
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
2-11
Templates In ArcMap, there are three levels at which you can store your customiz
ations: the Normal template (Normal.mxt), an intermediate (or base) template (*.
mxt), and the current map document (*.mxd). Each level of customization is repre
sented by a document. Upon opening a map, these documents are read from top to b
ottom in the graphic above in order to incorporate customizations from all level
s. The read order is important because changes in one template can affect other
templates and the current map. For example, the Normal template may have the Add
Data command turned off, but a base template may turn on the AddData command. No
rmal template The Normal templates contain all the original ArcMap (Normal.mxt)
and ArcCatalog (Normal.gxt) graphical user interface (GUI) settings. Every time
an application starts, the Normal template is read. The Normal templates are sto
red in the user’s Windows NT Profiles directory for Windows NT or in the user’s
Documents and Settings directory for Windows 2000 and XP. Each user can have dif
ferent customizations stored in the Normal templates even if they are running th
e same installation of ArcGIS. In ArcCatalog, all customizations are stored in t
he Normal.gxt template. If the Normal template is deleted, it is re-created when
the application starts. Base template Base templates allow you to store map ele
ments for the creation of standard maps. When initially creating a new ArcMap ma
p document, you can choose to base your map on a template. While there are sever
al predefined base templates that come with ArcGIS, you can actually save any ma
p document as a template (*.mxt). Templates can also store customizations, which
will apply to all maps subsequently produced from them.
Introduction to Programming ArcObjects with VBA
The VBA development environment
2-11
Map document The most local level of customization is the map document itself (*
.mxd). Customizations stored in the map are available only in that particular do
cument. The map document is the last document to be read when opening a map, so
customizations at this level can override ones defined in the Normal or Base tem
plates.
Introduction to Programming ArcObjects with VBA
The VBA development environment
2-12
Storing your customizations
All customizations are saved
Normal template, Base template, or the current document
Current map overrides any templates
For example, controls can be added or removed
Save in:
Copyright © 2001–2004 ESRI. All rights reserved.
Normal.mxt
Introduction to Programming ArcObjects with VBA
2-13
All ArcMap customizations are stored at one of the three levels described on the
last slide. Everything from new Visual Basic forms and programs to simply chang
ing a command’s image is saved in Normal.mxt, a base template (*.mxt), or with t
he current map document (*.mxd). When a map is opened, these three documents are
read in the following order. Normal template The Normal template is always read
first when opening a map. Because the Normal template is stored in the Windows
user profiles directory, customizations stored here are global to a specific log
in. If the Normal template does not exist when ArcMap or ArcCatalog is started,
an out-of-the-box version is re-created. As a precaution, you should make period
ic backups of the Normal template if you are storing a lot of customizations the
re. Base template Base templates are designed primarily to store a set of map la
yout elements, such as north arrows, scale bars, and base layers, to aid in the
production of standard maps. These templates may also contain customizations suc
h as specialized controls or scripts. As an example, your organization might wor
k with parcel maps that all have a custom property value calculator control inhe
rited from their common template. Maps that were not produced from this template
would not have the custom control. Current map If customizations are saved in a
map document, they will only be available in that particular document. For exam
ple, you might have a map document that contains sensitive information such as a
rchaeological site locations. You could protect this particular document with a
custom startup routine that prompts for a password when the map document is open
ed.
Introduction to Programming ArcObjects with VBA
The VBA development environment
2-13
Examining a control’s source code
Commands have events (e.g., Click, Double-click, MouseUp, KeyDown, KeyUp) Code r
uns when its corresponding event occurs
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
2-14
Control source code The code behind a command is called the source code or somet
imes simply the source. By right-clicking on a custom control (UIControl or Macr
o) and choosing View Source, you can view (and edit) its source code. Because th
e existing ArcGIS commands have been compiled as DLLs (and were written in C++ a
nyway), you cannot view or edit an existing command’s source code. Code window W
hen you first create a UIControl, it only knows how to be a control but has no r
eal code to make it work. It other words, if it is a button it will click like a
ny other button, if it is an edit box it will allow you to type text in it, and
so on. It will have all the properties of a control (such as an image and a name
) but will not do anything when it’s interacted with. To add functionality to a
control, you can choose View Source as shown above to access the control’s assoc
iated code document (module). Once you are in the control’s code module, you can
write Visual Basic programs that are associated with user events (e.g., a butto
n click).
Introduction to Programming ArcObjects with VBA
The VBA development environment
2-14
Demonstration
Using the Customize dialog box to …
Create a new toolbar Add existing commands to the interface Rearrange interface
commands Create a new UIControl Change command properties Reset a toolbar to its
original appearance
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
2-15
Demonstration: Using the Customize dialog box Your instructor will now use the C
ustomize dialog box to perform some of the simple user interface customizations
discussed in this lecture.
Introduction to Programming ArcObjects with VBA
The VBA development environment
2-15
Overview
The VBA development environment Customize dialog box
Create new toolbars and commands Add, delete, and move commands Set control prop
erties
Storing and distributing customizations Visual Basic Editor
Code storage Modules Procedures
Visual Basic statements
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming Arc
Objects with VBA
2-16
The first half of this lecture introduced you to the Customize dialog box. While
the Customize dialog is used to modify the user interface and to add new contro
ls, the Visual Basic Editor is where you write code to make new controls work. Y
ou can also use the Visual Basic Editor to produce standalone programs (macros)
and user forms. In this half of the lecture, you will learn how to access and us
e the Visual Basic Editor, how code is stored and organized in ArcMap and ArcCat
alog, as well as some basic VB-related terminology (e.g., module, procedure, mac
ro). Finally, you will learn to write Visual Basic statements and how to use som
e simple Visual Basic functions.
Introduction to Programming ArcObjects with VBA
The VBA development environment
2-16
The Visual Basic Editor
Project Explorer
Projects
Code Modules
Copyright © 2001–2004 ESRI. All rights reserved.
Procedures
Introduction to Programming ArcObjects with VBA
2-17
Working with the Visual Basic Editor The Visual Basic Editor is where you will w
rite code and design user forms. There are several utilities here for writing, t
esting, and debugging your VB programs. Before looking at VB editing utilities,
let’s examine how code is organized in the Editor. Project Explorer The Visual B
asic Project Explorer window organizes all code written for a particular ArcMap
document or for the ArcCatalog application into three kinds of projects: the Nor
mal template, a base template (if one is referenced), and the current project, a
lso known as your currently opened map document. Use the Project Explorer to acc
ess all available Visual Basic programs. Projects Projects are like root directo
ries that organize several subfolders of code documents. In ArcMap, the projects
define the level of customization for code you write (Normal versus the current
document). When developing in ArcCatalog, the Normal template will be the only
project listed in the Project Explorer. In ArcMap, you will also have the curren
t map document and perhaps a base template project. Modules A module is simply a
document that contains code. In the Visual Basic Editor, you can work with thre
e types of modules: form, standard, and class. The details of these three module
types will be described later.
Introduction to Programming ArcObjects with VBA
The VBA development environment
2-17
Procedures Procedures are sometimes referred to as macros. They are nothing more
than blocks of code you will write as a Visual Basic programmer. There are thre
e kinds of procedures: event, subroutine, and function. The example above shows
the Project Explorer organizing two projects (Normal.mxt and Malaysia.mxd). Ther
e are two open modules shown (as shown in the Project Explorer, Malaysia.mxd con
tains 6 modules total). The module in the foreground contains three procedures,
and the one in the background contains one, which consists of a single statement
(MsgBox …).
Introduction to Programming ArcObjects with VBA
The VBA development environment
2-18
Understanding ArcMap software’s code storage
Project Explorer: Organizes projects (levels of customization) Project: Folder t
hat stores modules (e.g., Normal.mxt) Module: Document that stores code Procedur
e: A block of code (e.g., macros) Statement: A line of code
Module Module
Procedure Procedure
{
Statements Statements
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
2-19
Components of ArcGIS VBA code storage All code written for an ArcMap document or
for ArcCatalog can be accessed from the Visual Basic Editor’s Project Explorer
window. The Project Explorer organizes all projects that might contain Visual Ba
sic code, and these projects are analogous to the levels of customization discus
sed earlier (Normal template, base template, map document). By using the Project
Explorer, you can access existing code documents (or modules) stored with the d
ocument or application, or create new ones. Visual Basic code always lives insid
e a module, which is nothing more than a document for writing code. Modules, in
turn, consist of procedures, which are VB programs (macros). The smallest unit o
f Visual Basic code that can be executed is the statement. Statements are simply
lines of code. Compact disk analogy The code organized in the Visual Basic Edit
or is like your music collection. The Project Explorer is the rack that contains
all your compact disks. To access any of your music, you must start at the CD r
ack. Just as the Project Explorer may have several Projects, your music rack may
have several sets of CDs: your CDs and your spouse’s, for example. Each CD in t
urn contains several songs, just like a code module may contain several procedur
es. Individual songs are composed of lines of lyrics, just as procedures are bui
lt from lines of code.
Introduction to Programming ArcObjects with VBA
The VBA development environment
2-19
Writing Visual Basic statements
Carry out actions Written inside procedures May have arguments
Multiple arguments are separated with commas Some arguments are optional
Private Sub ShowMsgBox() Beep MsgBox "ESRI" End Sub
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
2-20
Statements The smallest unit of Visual Basic code that can be executed is a stat
ement. Statements are simply lines of code, and each statement carries out some
simple action. Statements, therefore, are the building blocks for constructing s
ub procedures and functions. Although individual statements can be executed in t
he Immediate window, for practical purposes all statements will exist inside of
a procedure. Statements may or may not have arguments. An argument is simply som
e extra piece of information that must be specified for a statement to work corr
ectly. In the second statement above, for example, the MsgBox statement has the
string ESRI as an argument. Without this argument, a message could not be displa
yed. Multiple arguments can be specified as a commadelimited list, as shown belo
w.
3 arguments: a Message, a Style, a Title MsgBox "Continue?", vbYesNo, "Abort op
eration?"
I don’t want to argue You will often hear the terms argument and parameter used
interchangeably, but they are not exactly the same thing. As a programmer using
a function or sub procedure, you specify arguments. As a programmer writing a su
b or function, you define parameters. In other words, they are called arguments
when they are passed and parameters when they are received.
Argument (intDollarAmount) … intTotalTax = CalcTax (intDollarAmount) Parameter
(Amount) … Public Function CalcTax (Amount As Integer) As Integer CalcTax = Amo
unt * 0.07 End Function
Introduction to Programming ArcObjects with VBA
The VBA development environment
2-20
Some common Visual Basic functions
InputBox to get information
InputBox "Enter the new Landuse Code: "
MsgBox to report a message
MsgBox "ArcMap is Great!"
Combine (concatenate) strings with & … Get the Date or Time …
MsgBox "The date is " & Date MsgBox "The time is " & Time MsgBox "The date and t
ime is " & Now
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
2-21
Visual Basic functions There are several predefined Visual Basic functions that
you can use to do things like get the current date and time from the operating s
ystem, display several types of message and input boxes, concatenate strings, an
d convert data types. Open the Visual Basic help topic Visual Basic Language Ref
erence > Functions for an alphabetical listing of VB functions. Message boxes To
display various types of message boxes, use the Visual Basic MsgBox function. T
his function has only one required argument, a message (prompt) to display. By s
pecifying values for the optional arguments below, you can further define the ap
pearance of your message box. Buttons: Use any combination of Visual Basic MsgBo
x constants to specify the type of buttons, icons, or both to appear on the mess
age box. To use several of these options, you can simply add the constants toget
her. A sample of these constants is shown below. • vbYesNo—place a Yes and a No
button on the message box • vbYesNoCancel—display a Yes, a No, and a Cancel butt
on • vbExclamation—display an exclamation mark image on the message box • vbInfo
rmation—display an I image on the message box • Several others • Title: provide
a string to appear on the message box title bar The code below will display a me
ssage box with Yes and No buttons, an exclamation image, and a title.
MsgBox "Continue?", vbYesNo + vbExclamation, "Yes or No?"
Introduction to Programming ArcObjects with VBA
The VBA development environment
2-21
Input boxes To get keyboard input from your user, you can use the InputBox funct
ion. Like MsgBox, InputBox has a single required argument, a message (prompt) to
appear on the box. When the InputBox statement is executed, your code will paus
e until the user clicks OK on the input box. Once the user clicks OK, the value
that he or she typed can be used in your program. Note: If the user clicks the C
ancel button on the input box, an empty string is returned (“”). Concatenation T
o concatenate two strings, use the ampersand (&) character. The concatenation fu
nction does not add a space between the strings. To add a space between concaten
ated strings, use one of the methods as shown below.
MsgBox "Hello, my name is " & strFirstName MsgBox "My full name is " & strFirstN
ame & " " & strLastName
Date and Time functions Visual Basic has functions that return the current date,
time, or both from the operating system. These functions have no arguments (req
uired or optional) and return values of the variant data type. Date: returns the
current calendar date (e.g., 6/14/04) Time: returns the current system time (e.
g., 3:08:47 PM) Now: returns both the current date and time (e.g., 6/14/04 3:08:
47 PM)
Introduction to Programming ArcObjects with VBA
The VBA development environment
2-22
Procedure types
Event procedures
Have an associated object (e.g., control) Code runs when the corresponding event
occurs (e.g., click)
Subroutine and function procedures
No associated object Must be called Functions return a value
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
2-23
Procedures All procedures are blocks of Visual Basic code and are simply a group
of VB statements that are executed sequentially. There are some important disti
nctions that can be made about specific types of procedures, however, as describ
ed below. Event procedures Event procedures are associated with objects. More sp
ecifically, they are associated with an object event. Execution of these procedu
res is triggered when the associated event occurs. For example, when UIButtonCon
trol3 is clicked, the code in the UIButtonControl3_Click event procedure execute
s. When the mouse cursor hovers over UIButtonControl3, the UIButtonControl3_Tool
Tip event procedure executes to display a tool tip. Every control, form, and the
document itself has a suite of events for which you can provide code. Subs and
functions Subs and functions are essentially no different than event procedures
in that they are collections of Visual Basic statements that run sequentially as
a unit of code. Subs and functions, however, are not directly associated with a
n object event. These procedures will only execute when they are explicitly told
to run. Procedures carry out an action (adding a layer to a map, for example) b
ut are not able to pass back a value. Functions, on the other hand, are generall
y used to produce some value to pass back to the procedure that called it (calcu
lating and returning a total area, for example). You will learn more about these
procedures in the next lesson.
Run a Sub called AddLayer Call AddLayer Run a Function called CalcTotalValue,
store a returned value in intTotalValue … intTotalValue = CalcTotalValue (intVal
ueA, intValueB, intValueC)
Introduction to Programming ArcObjects with VBA
The VBA development environment
2-23
Running an event procedure
Controls have a predefined set of events
You choose which ones to code
When an event is fired, the associated code executes
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
2-24
Controls respond to events All controls have a predefined set of events that the
y can respond to. A control responds to an event by running the associated event
procedure—this does not mean you need to write code for every event that a cont
rol supports, however, only those required to make your control work. A UIButton
Control, for example, has five events that can be coded, but it is quite typical
to write code only for the Click event. Each control type will have different a
vailable events available to code. A UIEditBoxControl, for example, has a Change
and a KeyDown event for responding to user keyboard input, while a UIToolContro
l has events, such as MouseDown, MouseUp, and MouseMove, to capture user input f
rom the mouse. The example When the control above (UIButtonControl1) is clicked
by the user, its Click event code is executed (UIButtonControl1_Click), which re
ports the name of a layer in a message box.
Introduction to Programming ArcObjects with VBA
The VBA development environment
2-24
Navigating event procedures in a module
Choose a control in the Object box Choose an event in the Procedure box
Object box Procedure box
MsgBox "Hi!"
Wrapper lines are added automatically
A
Copyright © 2001–2004 ESRI. All rights reserved.
Write code to run when UIButtonControl1 is clicked
Introduction to Programming ArcObjects with VBA
2-25
Finding a procedure To start coding (or just to find) an event procedure in a pa
rticular module, select an object and an event procedure from the respective dro
pdown lists. The Object box (upper left) contains all the objects available in t
he module (e.g., UIControls), while the Procedure box (upper right) lists all th
e event procedures for the object selected in the Object box. If you choose an o
bject and an event procedure for which there is already code, the module will sc
roll to this procedure. Otherwise, a new event procedure definition will be crea
ted. Wrapper code If the event procedure you chose does not exist, wrapper code
will be automatically produced for you. Wrapper code (sometimes called stub code
or template code) simply provides the procedure definition; the code you provid
e inside (between) the wrapper lines will be executed when the event is triggere
d. The example In the example above, UIButtonControl1 was chosen in the object l
ist. Upon pulling down the procedure list, the five available event procedures f
or UIButtonControl1 are displayed. After Click is chosen from the procedure list
, wrapper lines are automatically added to the code module (Private Sub … End Su
b). The code inside the wrapper lines will execute when UIButtonControl1 is clic
ked and will simply display a message box that says ‘Hi’.
Introduction to Programming ArcObjects with VBA
The VBA development environment
2-25
The ThisDocument module
Contains code associated with a document
Normal template Current map document (mxd) Base template (optional)
Customize at any level
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
2-26
How many documents do I have? As the name implies, the ThisDocument code module
is associated with a document. You may become confused, however, on opening an A
rcMap document to find three ThisDocument code modules. When you think of templa
tes as documents, however, it makes perfect sense. Each level of ArcMap customiz
ation is represented by a document: Global customizations are stored in the Norm
al.mxt template, customizations applied to a set of map documents may be stored
in a base (intermediate) template, and customizations meant for a single map doc
ument are stored in that map document itself. By writing code in the appropriate
ThisDocument module, you are controlling the scope for your programs. What kind
of code goes into a ThisDocument module? You may write any macros you want in T
hisDocument, but perhaps most importantly, all code powering your UIControls wil
l be written in one of the ThisDocument code modules. Remember that before addin
g a UIControl to the ArcMap interface, you must indicate (in the Customize dialo
g) where you want to store the new control (normal template, base template, or i
n the current document). Once you have made your choice, the code you write for
the control will be in the corresponding ThisDocument module. For example, you c
reate a new UIButtonControl, and save it in Normal. When you right-click the new
interface control and choose View Source, you will find yourself writing code f
or the control in the ThisDocument code module under the Normal project heading.
Introduction to Programming ArcObjects with VBA
The VBA development environment
2-26
Creating a new module
Module (standard module): Contains standalone code Class module: Contains a clas
s definition (Lesson 5) UserForm: Contains code and layout for a form (Lesson 3)
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
2-27
Creating a new code module New code modules can be added to your Visual Basic pr
oject by using the Insert menu on the Editor interface or by choosing Insert fro
m the Project Explorer context menu (as shown above). When adding a new code mod
ule, be especially aware of where you are placing it (Normal, Base template, Cur
rent document). There are three types of modules you may add, which are describe
d below. Module (standard module) Standard modules are used to write standalone
procedures that you might want to call from other Visual Basic programs. The mos
t common use of standard modules is to contain code that you use a lot. Instead
of having to constantly rewrite the code to add a layer to a map, for example, y
ou could place the code in a standard module in your Normal.mxt, then reference
the procedure whenever it is needed. Class module Class modules are used to desi
gn custom classes. The ArcObjects library already has classes such as Maps, Laye
rs, Symbols, and PageLayout. By writing code in a class module, you can define y
our own class to use in your programs. The specifics of programming a custom cla
ss will be discussed in more detail in Lesson 5. UserForm Module UserForm module
s are code modules associated with a form (dialog). In the Visual Basic Editor,
you can design a form by adding and rearranging controls (CommandButtons, TextBo
xes, OptionButtons, etc.) and setting their properties. After the form layout is
designed, you can write code in the associated form code module to make the con
trols work. You will design and write code for a UserForm in the next lesson.
Introduction to Programming ArcObjects with VBA
The VBA development environment
2-27
Creating a new sub or function procedure (macro)
Scope: Public or Private Sub or Function: Functions return a value Parameters: L
ist all required inputs Return Type: Type of data returned (functions only)
Scope
Name
Parameter List
Return Type
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming Arc
Objects with VBA
2-28
Creating a new procedure To add a new procedure to a code module, you can choose
Procedure from the Visual Basic Editor’s Insert menu, or you can simply type th
e procedure definition directly into the module. When defining a new procedure,
you need to provide the following information. Scope Scope defines how widely a
procedure may be used and can be defined as either Public or Private. A procedur
e that has a public scope can be called from any code module in the same project
, while a private procedure can only be called from within the same code module.
Sub versus Function The two basic types of procedures are Subs (sub procedures)
and Functions. If you only need to perform some action and do not need to retur
n a value, define your procedure as a sub. Functions can also carry out some act
ion but also have the ability to return a value. For example, you could write a
sub to add a layer to a map. The sub could simply take a pathname from the user
and add that data as a new layer. By writing the same procedure as a function, y
ou could add the data as a new layer, then also return a Boolean (true or false)
value that describes whether the operation was successful or not. Parameters Th
e parentheses following the procedure name are a required part of the procedure
definition, even if they are empty. A sub or function might require some additio
nal input to work properly, and this is where any required inputs (parameters) c
an be defined. If you were creating an AddLayer procedure, for example, you woul
d probably define a layer as a required parameter. Notice that the parameters ar
e defined with a name (e.g., Total) and a data type (e.g., As Double).
Introduction to Programming ArcObjects with VBA
The VBA development environment
2-28
Return Type (Functions) Because functions will return a value, the function defi
nition needs to include the type of data value that will be returned. Following
the parameter list for a function, indicate the type of value returned by using
the As keyword. In the example above, the Tax function will return a Double (dou
ble-precision decimal number).
Introduction to Programming ArcObjects with VBA
The VBA development environment
2-29
Defining procedure scope
Public: May call procedure from any module Private: Procedure may be called only
from other procedures in the same module
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
2-30
Procedure scope Sub procedures and functions can be defined as public or private
in scope. A public procedure can be called from any module in the same project,
while a private procedure can only be called from a sub or function inside the
same module. When you define a new procedure, you need to consider whether or no
t the procedure should be called from outside its own code module. A procedure t
hat enables controls on a particular user form would probably have a private sco
pe because no other form would need to call that procedure. A procedure that cal
culates a total area value would probably have a public scope because this proce
dure would be useful for other modules to use. Running a procedure as a macro Th
e following slides will describe how you can run your procedures as macros. In o
rder to see your macros listed in the macros dialog (Tools > Macros > Macros) or
in the Customize dialog box (Macros category), you need to make sure they have
a public scope. Procedures defined as private will not appear (and therefore can
not be run) as a macro.
Introduction to Programming ArcObjects with VBA
The VBA development environment
2-30
Running a subroutine or function procedure
No event to cause code execution Must call the procedure
Macro menu: Interface Call statement: Code
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
2-31
Running a procedure Unlike event procedures, there is no object event to signal
a subroutine or function procedure to execute. In fact, these procedures will ne
ver run unless they are explicitly told to. You can tell a subroutine or functio
n procedure to execute in one of the following ways. From the interface To execu
te a procedure from the interface, choose Macros from the Tools menu. On the Mac
ros submenu, again choose Macros. In the dialog that is launched, select the pro
cedure you want to execute, then click Run. From code Subroutine and function pr
ocedures can be called from other code in your project, depending on where it is
being called from and the scope of the procedure (review the previous slide on
procedure scope). To execute a procedure with code, you can use statements like
those below.
With the Call statement Call MyOtherProcedure Simply call it using its name My
OtherProcedure
Introduction to Programming ArcObjects with VBA
The VBA development environment
2-31
Adding a macro to a toolbar
Macros category of the Customize dialog Macro becomes a button on the toolbar
Edit the control’s properties
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
2-32
Macros that are defined with a public scope can be added to the ArcMap or ArcCat
alog interface as a button on a toolbar or a menu choice. To access your macros
and add them to the interface, launch the Customize dialog and open the Macros c
ategory on the Commands tab. Macros you find there can simply be dragged onto th
e interface like any other command in the Customize dialog. When it is placed on
the interface, the macro will be given a default icon. To change this image, yo
u may right-click the macro and choose Change Button Image. Adding a tool tip to
a macro on a toolbar Unlike UIControls, macros added to the interface do not ha
ve events such as Enabled, ToolTip, and Message for you to code. However, there
are ways to get at some of these properties programmatically. The VBA Sub below
changes the tool tip and message for a macro called Project.NewMacros.Test.
Private Sub ChangeToolTip( ) Dim pItem As ICommandItem Set pItem = _ ThisDocumen
t.CommandBars.Find("Project.NewMacros.Test") pItem.ToolTip = "My ToolTip" pItem.
Message = "My Message for the status bar." End Sub
Introduction to Programming ArcObjects with VBA
The VBA development environment
2-32
Getting help
F1 key for context-sensitive help ArcObjects Developer Help ArcGISDeveloperonlin
e.esri.com
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
2-33
ArcGIS and Visual Basic provide many ways to get help. There is help documentati
on available for Visual Basic as well as help specific to using ArcObjects. In a
ddition to the traditional sources for help described below, there are several u
tilities available in the Visual Basic Editor for helping you write code. You wi
ll be exposed to several resources for help throughout the course. Context-sensi
tive help You can obtain context-sensitive help by highlighting a word in your c
ode and pressing the F1 key on your keyboard. If the word you highlight is relat
ed to Visual Basic, the Visual Basic Help will launch and take you directly to t
he appropriate Help page; if the highlighted piece of code is related to ArcObje
cts, the appropriate ArcObject Help page will open. ArcGIS Developer Help When y
ou install ArcGIS, you have the option of also installing the ArcGIS Developer H
elp. If you installed the Developer Help, you can access it from the Windows Sta
rt menu > Programs > ArcGIS > Developer Help > VB6 Help. In addition to help on
individual ArcObjects classes, the ArcGIS Developer Help has plenty of sample co
de that you can borrow and modify for your own applications. ArcGIS Developer On
line An online version of the ArcObjects Help is available from the ESRI Web sit
e. ArcGIS Developer Online contains updated code samples and documentation. You
will find ArcGIS Developer Online at the URL listed below: http://arcgisdevelope
ronline.esri.com Visit this site frequently as it will be updated often with new
samples and detailed explanations. For versions earlier than ArcGIS 9 (8.x), th
is information can be found at ArcObjects Online: http://arcobjectsonline.esri.c
om.
Introduction to Programming ArcObjects with VBA The VBA development environment
2-33
Exercise 2 overview
Explore the Visual Basic Editor Navigate event procedures Add a new code module
Run procedures Export code to a file on disk
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
2-34
Exercise 2: Design a user form In this exercise you will do the following: • Exp
lore the Visual Basic Editor. • Write simple VB statements in the Immediate wind
ow. • Add a new control to the interface. • Write code in various project module
s. • Run a macro from the interface. • Run a macro from code. • Export code.
Introduction to Programming ArcObjects with VBA
The VBA development environment
2-34
Introduction to Programming ArcObjects with VBA
Visual Basic code: How, where, and when?
Lesson overview Object-oriented programming Example: Object-oriented terms How:
Visual Basic syntax Preset ArcObjects variables Automatic code completion Where:
Controls, documents, and forms Working with forms Setting properties at design
time Writing code for a form Using control properties at run time When: Form and
control events When: Map document events Saving your work Exercise 3 overview
3-11 3-13 3-14 3-16 3-17 3-18 3-20 3-22 3-23
contents
3-2 3-3 3-4 3-5 3-7 3-9
Visual Basic code: How, where, and when?
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
Introduction to Programming ArcObjects with VBA
Visual Basic code: How, where, and when?
3-1
Lesson overview
How?
Object-oriented programming Visual Basic syntax Application and ThisDocument var
iables
Where?
Creating forms and controls
When?
Document, control, and form events
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
3-2
Overview This lesson will discuss some of the fundamentals of writing Visual Bas
ic code. You will learn about object-oriented programming, basic VB syntax, crea
ting user forms, and coding various user events. This lesson will answer the fol
lowing questions. How … … does object-oriented programming work? … do I write a
Visual Basic statement? Where … … do I begin? … can I write code? … can I save c
ustomizations? When … … will my code execute?
Introduction to Programming ArcObjects with VBA
Visual Basic code: How, where, and when?
3-2
Object-oriented programming
Objects are …
Visual Basic: Forms, text boxes, command buttons, … ArcObjects: Maps, layers, sy
mbols, tables, …
Manipulate objects to carry out tasks
Properties: Characteristics of an object Methods: Things an object knows how to
do Events: Actions that an object can respond to
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
3-3
Treat them like objects The (perhaps over-used) term object-oriented programming
simply means that your programs work by using objects. Objects are basically an
ything you use in your Visual Basic code, whether visible or not. Things like ma
ps, layers, symbols, and spatial references are all examples of ArcGIS objects,
while UserForms, CommandButtons, and ComboBoxes are examples of Visual Basic obj
ects. In object-oriented programming, you can work with existing objects (e.g.,
get the current map the user is working in), or you can create new objects (e.g.
, make a new layer to add to the map). Once you have referenced or created the o
bjects you want to work with, you can manipulate them by using their properties,
methods, and events. • Properties: A property is a characteristic (noun) of an
object that, as a programmer, you will be able to read (get) or write (set). As
an everyday example, a computer might have properties such as RAM, disk space, a
nd monitor size. • Methods: A method is an action (verb) that an object can carr
y out. A computer might have methods such as boot up, log in, or crash. • Events
: Like methods, events are actions (verbs). Instead of actions that an object ca
rries out, however, events are actions that an object responds to (usually actio
ns triggered by the user). Events that a computer might have: type, move mouse,
click mouse.
Introduction to Programming ArcObjects with VBA
Visual Basic code: How, where, and when?
3-3
Example: Object-oriented terms
Car Property Method Event
Horsepower Accelerate Brakes are pressed
Map
MapUnits AddLayer SelectionChanged
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
3-4
Object-oriented programming terms Part of learning anything new, of course, is l
earning new terminology. Some common terms that you will hear throughout this co
urse for describing object-oriented concepts are listed here. The objects you wo
rk with in your Visual Basic code are, in reality, nothing like real-world objec
ts; they are simply blocks of code that are held in memory. Conceptually, howeve
r, they are very much like everyday objects in that they have characteristics (p
roperties), actions they can perform (methods), and actions that they can respon
d to (events). The syntax for working with object properties and methods is desc
ribed on the following page. Properties As described on the previous page, prope
rties are characteristics of an object and are generally nouns (color, for examp
le). When working with object properties, you can either get (read) them or set
(write) them. In the example above, the ArcObject called Map has a property MapU
nits. Notice that the property is a noun, indicating that it is some characteris
tic that the Map has. Similarly, an everyday object like car has a horsepower ch
aracteristic. Methods Methods are actions that an object knows how to perform. A
car, for example, can accelerate when you tell it to. The ArcObject Map has a m
ethod called AddLayer. If a programmer wants to add a layer in ArcMap, he or she
can ask a Map to do it. Events Events are another type of action that is associ
ated with an object. Instead of being actions that the object performs, however,
these are actions that an object can respond to. When you press the brake pedal
in your car, for example, the car will respond by stopping (hopefully). Likewis
e, a Map can respond to the user making a new selection by executing some code t
hat you provide (events will be covered in more detail in a later lesson).
Introduction to Programming ArcObjects with VBA Visual Basic code: How, where, a
nd when? 3-4
How: Visual Basic syntax
Get the value of a property with Object.Property
MsgBox "The map name is " & myMap.Name
Assign a value to a property with Object.Property = value
myMap.Name = "Zaire"
Call methods with Object.Method arg1, .., argN
myMap.AddLayer CityLayer myMap.SelectFeature CityLayer, KahembaPoint myMap.Clear
Selection
ArcObject events will be covered in Lesson 16
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
3-5
Visual Basic syntax Regardless of the object with which you are working, the VB
syntax is basically always the same: the name of the object variable, followed b
y a dot ( . ), followed by one of the object’s methods or properties. Properties
Follow the syntax below to set (assign) a new value to an object property.
myObjectVariable.SomeProperty = ANewValue
To get (read) an object property, use this simple syntax.
myObjectVariable.SomeProperty
Keep in mind that you may not be able to set (assign a new value to) all propert
ies of an object. Oftentimes, you will find properties that cannot logically be
given a new value. A Map, for example, has a LayerCount property. While it makes
sense to get this property, it does not make sense to (and therefore you cannot
) directly set a new value for LayerCount. Instead, this property will only be u
pdated when layers are added to or removed from the map. Oddly enough, you will
actually encounter some properties that can be set but cannot be read. (Look at
the IFieldEdit interface for some examples.) Use the Visual Basic or ArcObjects
help resources to learn whether or not you can get a given property, set a given
property, or do both.
Introduction to Programming ArcObjects with VBA
Visual Basic code: How, where, and when?
3-5
Methods Follow the syntax below to call (use) a method that has no arguments.
myObjectVariable.SomeMethod
Use a comma-delimited list for calling a method that has several arguments.
myObjectVariable.SomeMethod Arg1, Arg2, Arg3
Returning a value Use parentheses around a method or function’s argument list if
you want to return a value.
theResult = myObjectVariable.SomeMethod (Arg1, Arg2, Arg3) theAnswer = SomeFunct
ion (Arg1)
Example:
theAnswer = MsgBox ("Continue?", vbYesNo) This returns either vbYes or vbNo an
d stores the value in theAnswer MsgBox "Continue?", vbYesNo This displays a mes
sage box with a Yes and No button, but does NOT return what the user clicks.
Introduction to Programming ArcObjects with VBA
Visual Basic code: How, where, and when?
3-6
Preset ArcObjects variables
ArcObjects variables can always be accessed in VBA
Application ThisDocument
A Starting point for your code More about variables in the next lesson
MsgBox "You are currently working in " & Application.Name MsgBox "The current ma
p is " & ThisDocument.Title Object Object Property Property
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
3-7
Where to begin? In ArcMap and ArcCatalog, you have two preset variables that wil
l serve as the starting point for much of your code: Application and ThisDocumen
t. These object variables are always available as soon as you launch ArcMap or A
rcCatalog. While the number of methods and properties that are available on thes
e variables is fairly limited, they serve as a stepping stone to other objects y
ou might want to program with (maps, layers, files, etc.). Application Applicati
on is a preset variable that points to (you guessed it) the current application.
In ArcMap, Application refers to the ArcMap application, while in ArcCatalog, i
t refers to ArcCatalog. In either environment, the Application variable will alw
ays have the same methods and properties. Below is a sample of some methods and
properties available on Application. • Caption: a read/write property to get or
set the text that appears on the application’s title bar • Name: a read-only pro
perty that will always return the name of the application as a string (ArcMap or
ArcCatalog) • RefreshWindow: a method to redraw the application window ThisDocu
ment The ThisDocument preset variable points to the document that is currently o
pen in the application. In ArcCatalog, ThisDocument always refers to the Normal.
gxt template, while in ArcMap it refers to the current map document (.mxd). Unli
ke the Application preset variable, there are some differences in the methods an
d properties available on ThisDocument in ArcCatalog and ThisDocument in ArcMap.
Introduction to Programming ArcObjects with VBA
Visual Basic code: How, where, and when?
3-7
Note: You can also reference the current document by using the Document property
of the Application preset variable described above. Here are some methods and p
roperties that you will find on ThisDocument. • AddLayer: ArcMap only. A method
to add a new layer to the document (a layer is required as an argument). • Title
: a read-only property to get the name of the document (e.g., normal.mxt, UtahMa
p.mxd). • Type: a read-only property that describes the type of current document
(Normal template, Base template, Map document).
Introduction to Programming ArcObjects with VBA
Visual Basic code: How, where, and when?
3-8
Automatic code completion
Lists available properties and methods Displays when the name of an object is ty
ped
If the list is not displayed, the object is not recognized
Press Tab, Enter, or Space to select the method or property
Press Tab, Press Tab, Enter, or Enter, or Space Space
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
3-9
Those who finish with the fewest keystrokes win One of the best ways to avoid ge
tting errors in your Visual Basic code is to be lazy. The Visual Basic Editor ha
s several utilities that help you write code by providing timely help, helping y
ou navigate through code, and even completing some of your code for you. When yo
u let Visual Basic automatically complete such code as variable names, methods,
and properties, you avoid the possibility of making simple typographical errors
that may cause run-time errors in your code. Auto Quick Info Auto Quick Info is
a feature that was discussed briefly in the last lecture. As you type a statemen
t that Visual Basic recognizes, a box (that looks like a tool tip) will pop up w
ith the proper syntax required. You will be able to see all arguments required f
or the statement, as well as any optional ones (shown in square brackets). If th
e statement you are typing returns a value, you will also see the return data ty
pe (e.g., As Integer). Automatic code completion Upon typing an object variable
that Visual Basic recognizes, followed by a dot, a list of all methods and prope
rties available for that object will appear. You can then scroll through the lis
t manually or type the first few letters to choose the method or property you wa
nt to use. Upon pressing Tab, Enter, or Space, the highlighted method or propert
y will be added to your code. This automatic code completion feature is good not
only because it saves you some typing, but also because it helps catch errors.
If the code completion list does not appear when it should, it means that Visual
Basic does not recognize the object variable you typed, and it’s likely that yo
u made a mistake earlier in your code.
Introduction to Programming ArcObjects with VBA
Visual Basic code: How, where, and when?
3-9
Automatic completion of variable names In addition to the automatic code complet
ion described above for object methods and properties, there is a way to automat
ically complete variable names. After typing the first few letters of a variable
name, hold down the control key (CTRL) and press the spacebar. The variable nam
e will be completed in your code if you have typed enough letters to distinguish
it; otherwise, a completion list will appear from which you can choose the vari
able. By having Visual Basic automatically complete your variable names whenever
possible, you avoid mistyping your variables.
Introduction to Programming ArcObjects with VBA
Visual Basic code: How, where, and when?
3-10
Where: Controls, documents, and forms
Create UIControls Store macros with the document Create forms for user interacti
on
More sophisticated than message boxes and input boxes
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
3-11
Where to write code The previous lesson discussed using the Visual Basic Editor
to write standalone procedures (macros) and how to use the customize dialog to a
dd macros or UIControls to the ArcMap or ArcCatalog interface. Another place you
may want to write code is inside of a form module. Forms are nothing more than
windows (dialogs) that contain a set of controls. Forms are ideal for certain ty
pes of user interaction, especially where a lot of data input may be required. I
nstead of having to pop up several message boxes or input boxes in your code, yo
u can simply launch a single form to prompt for many pieces of information at on
ce. Forms are also much more intuitive for a user to work with: There are variou
s types of controls you can place on a form, each designed for a particular type
of data input. Some common form controls are listed below (there are many other
s). • TextBox: Displays or allows the entry of text. Use TextBoxes to display in
formation or more commonly, to allow a user to type some input. In the example a
bove, TextBoxes are used to accept latitude and longitude values from the user.
• OptionButton: Allows one selection to be made from a group of possible choices
. OptionButtons are sometimes referred to as RadioButtons, as they function like
the station preset buttons on old car radios: Upon selecting one OptionButton,
all others automatically become unselected. In the example above, OptionButtons
are used to indicate latitude (North, South) and longitude (East, West). Only on
e from each group may be selected at a given time. • CheckBox: Displays the sele
cted state of an item (checked=selected, unchecked=unselected). Use CheckBoxes t
o have the user answer yes/no questions.
Introduction to Programming ArcObjects with VBA
Visual Basic code: How, where, and when?
3-11
• CommandButton: Begins execution of an action or series of actions. The code wr
itten for the Click event determines what action the CommandButton will execute.
For example, a CommandButton may open another form, close the current form, or
perform some action based on the values in the form controls. • ListBox: Display
s a list of values from which the user can select (one or several items). ListBo
xes may appear as simple lists or as a list of CheckBoxes.
Introduction to Programming ArcObjects with VBA
Visual Basic code: How, where, and when?
3-12
Working with forms
Form = window of controls + associated code
Code module Code module Properties window Properties window
Form Designer Form Designer Toolbox Toolbox
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
3-13
Visual Basic forms When you add a UserForm module to your Visual Basic project,
you are really adding two things: a form designer, in which you can add and posi
tion controls for the form, and a form code module that stores all the code requ
ired to make the form work. Adding a new form module To add a new form to the Vi
sual Basic project, click the Insert menu on the editor interface or right-click
in the Project Explorer window and choose Insert > UserForm from the context me
nu. When adding a form to an ArcMap document, be sure to add it to the proper pr
oject (e.g., normal.mxt or the current mxd) by highlighting the desired level of
storage in the project explorer. All forms you add to an ArcCatalog project wil
l be stored in the normal template (normal.gxt). Designing a form Remember that
a form consists of a design window and a code module. A new user form will simpl
y be an empty form designer to which you can add controls and an associated empt
y code module. By clicking and dragging from the toolbox to the form designer wi
ndow, you can add several types of controls to the form. At design time for a fo
rm (in the form design window), controls behave like graphics: They can be added
, removed, repositioned, and resized. All form controls will also have a set of
properties that a programmer can define using the Properties window. Writing cod
e for a form After the desired controls have been added to the form, positioned
so they are intuitive for the user to work with, and their desired properties se
t, the next step is to write code to power them. Every control on a form will ha
ve a set of events for which you may provide code, as will the form itself. By p
roviding code in the appropriate control event procedures, you can prepare the f
orm for the anticipated user interaction.
Introduction to Programming ArcObjects with VBA Visual Basic code: How, where, a
nd when? 3-13
Setting properties at design time
Select a control View or change properties with the Properties window
Appearance: Caption, Font, BackColor Behavior: TabIndex, Locked, Enabled NAME
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
3-14
Setting form and control properties The Properties window displays design time p
roperties for the selected object (control or form) in the form designer. Upon s
electing an object (by clicking it on the form designer or by choosing it from t
he Properties window dropdown list), you can set any of its design time properti
es by clicking in the Properties window. To set a common property for several co
ntrols at once, you can hold down the shift key or click and drag a box to selec
t several controls. When more than one control is selected in the form designer,
you will only see those properties common to all selected controls in the Prope
rties window. Varying with the type of property, there are several ways in which
they are set. Properties such as Name and Caption, for example, are set by simp
ly typing in a new text value. Font, on the other hand, is set by launching the
Font Properties dialog and defining font style, font size, bold, italic, and so
forth. Some properties will toggle between true and false (e.g., Enabled), some
will require numbers (e.g., Height and Width), and others will allow you to choo
se from a finite list of possible values (e.g., BackStyle). Naming controls One
property that is common to all controls (and to the form itself) is the Name pro
perty. While the user will never care (or even know) what your controls are name
d, this property is very important to the programmer. In your code, you will alw
ays refer to controls by name. When a control is added to a form, a default name
is assigned that simply consists of the type of control and the order in which
it was added (e.g., CommandButton1). Ideally, controls should be named so the ty
pe and purpose of the control is apparent from the name alone. As a suggestion,
name controls with a three-letter prefix that indicates the control type, follow
ed by a description of what the control does (often this description will corres
pond to the control’s caption property). Note: If you will not need to reference
a control in your code, it’s OK to keep the default name.
Introduction to Programming ArcObjects with VBA
Visual Basic code: How, where, and when?
3-14
Some examples of naming controls with this convention are shown below. Object Co
mmand button Form Label Text box List box Combo box Check box Option button Pref
ix cmd frm lbl txt lbo cbo chk opt Example cmdApply frmConvertCelsius lblFahrenh
eit txtCelsius lboAttributes cboGeometryType chkWriteLogFile optLegendType
See the Microsoft Web site listed below for a comprehensive list of recommended
naming conventions:
http://msdn.microsoft.com/library/default.asp?url=/library/enus/vbcon98/html/vbc
oncodingconventionsoverview.asp
Introduction to Programming ArcObjects with VBA
Visual Basic code: How, where, and when?
3-15
Writing code for a form
UserForms consist of a designer and a code module Double-click a control to reve
al its code
Each control on a form has several event procedures
Code Module Code Module Form Designer Form Designer
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
3-16
Writing code for a form and controls Each form has a code module that stores its
associated code. All code that powers a form (including each form control) is s
tored in the form code module. After using the form designer, the form toolbox,
and the Properties window to design your form, the next step is to write the cod
e required to make the form work. Just as each type of control has a different s
et of design time properties for you to set, they also have a unique set of even
ts for which you can write code. As a programmer, you do not need to write code
for every control event, only the ones that are required to make your form work.
There are several ways to access a form’s code module. The easiest way is to si
mply doubleclick a control in the form designer, which opens the form’s code mod
ule and places your cursor in the default event for that control (e.g., the Clic
k event for a CommandButton). Optionally, you can toggle between the form design
er and its code module by choosing Code or Object from the Visual Basic Editor’s
View menu (as shown above). The Project Explorer window also has controls (at t
he top) for switching between these two components of your form.
Introduction to Programming ArcObjects with VBA
Visual Basic code: How, where, and when?
3-16
Using control properties at run time
Get/Set properties with code while the form is running Syntax: Object.Property
Controls are objects
Private Sub cmdApply_Click() strFTemp = ( txtCelsius.Text * 9 / 5 ) + 32 lblFahr
enheit.Caption = "Fahrenheit: "& strFTemp End Sub
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
3-17
Getting and setting control properties at run time The properties you set in the
form designer are used primarily to control the appearance of a form when it is
first launched. When a user begins to interact with your form, however, it may
also become necessary to get and set control and form properties during run time
. Syntax for getting and setting control properties Remember that controls are V
isual Basic objects, and the syntax for working with object properties is Object
.Property. In the example above (when the form’s Apply button is clicked), the C
elsius temperature entered by the user is referenced using the TextBox control’s
Text property (txtCelsius.Text). A temperature in Fahrenheit is calculated and
then placed on one of the form’s labels by setting the Label control’s Caption p
roperty (lblFahrenheit.Caption = "Fahrenheit: " & strFTemp). Run-time versus des
ign time properties Most control properties can be set either at design time or
at run time. Indeed, you will often provide an initial value at design time, onl
y to change it in your code at run time. There are, however, some properties tha
t may only be set at design time. Although you can get these properties at run t
ime, you will receive an error if you try to set a new value at run time. Perhap
s the best example of this is the Name property that each control has. If you pr
ovide a name at design time, you cannot change the name at run time. Controls th
at are added at run time, however, can also have their name set at run time. Con
sult the Visual Basic Help for control properties that are read-only at run time
.
Introduction to Programming ArcObjects with VBA
Visual Basic code: How, where, and when?
3-17
When: Form and control events
Code runs when an event fires Different controls have different sets of events
Form events
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
3-18
Control events Every Visual Basic control has a set of events to which it can re
spond. As a programmer, you need to anticipate how your user will interact with
the form and then write your code accordingly. Each type of control has a differ
ent set of events for which you can write code, although you do not need to code
every control event. Below are some common control events and the type of code
you might write for them. Control UserForm TextBox Event Initialize Change KeyPr
ess CommandButton OptionButton Click Click Example Set variables, fill combo or
list boxes Enable/Disable controls according to what is entered Check for a vali
d character before writing it to the TextBox (e.g., numeric values only) Execute
code with values on the form (e.g., TextBoxes), close the form Update contents
of list or combo boxes, enable/disable appropriate controls
Introduction to Programming ArcObjects with VBA
Visual Basic code: How, where, and when?
3-18
Default control events Each type of control has a default event. When you double
-click a control in the form designer, you will be dropped off at this event in
the code module. Generally, this event will usually be either Click or Change. T
he default events for several Visual Basic controls are listed below. Object Use
rForm TextBox Label CheckBox ComboBox Default Event Click Change Click Click Cha
nge
CommandButton Click
Note: If code does not exist for the default event but does for another, double-
clicking a control will take you to the existing (coded) event procedure.
Introduction to Programming ArcObjects with VBA
Visual Basic code: How, where, and when?
3-19
When: Map document events
Available in the ThisDocument module
Normal, base template, or current map (.mxd)
Event procedures for the MxDocument object
Open, close, new, change, etc.
Object List Object List
Procedure List Procedure List
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
3-20
Document events In both ArcMap and ArcCatalog, code can be associated with event
s related to the document. In ArcCatalog, the document is simply the Normal temp
late (normal.gxt), and code written here will execute every time the appropriate
ArcCatalog event fires. In ArcMap, document events can be coded for one of thre
e documents: the Normal template (normal.mxt), a base template (*.mxt), or the m
ap document itself (*.mxd). Scope of ArcMap document events The three documents
for which events can be coded in ArcMap represent different levels of customizat
ion. By writing your event code for the appropriate document, you can control th
e scope of ArcMap customization, as described below. Document event code in ArcM
ap’s Normal template will execute for all maps when the corresponding event occu
rs; this is a global customization. For example, you may want to display a custo
m splash screen with your company logo each time a map document is opened. To ac
complish this, you would supply code in normal.mxt’s OpenDocument event. Documen
t event code in an ArcMap base template (*.mxt) will execute only for map docume
nts that were based on that particular template. You may have several parcel map
s, for example, that will be produced from a template called ParcelMap.mxt. When
a user of a parcel map changes to PageLayout view, you may want to display a cu
stom toolbar. You would write such code in the ParcelMap.mxt ActiveViewChanged e
vent procedure, thus providing this behavior for all future maps that are create
d from the template. For document event code that is specific to a single map, y
ou can provide document event code in the map document itself (*.mxd). If you ha
ve one map that contains restricted information, for example, you could code the
map’s OpenDocument event procedure to require a password before opening it. No
other maps would exhibit this behavior.
Introduction to Programming ArcObjects with VBA
Visual Basic code: How, where, and when?
3-20
ArcMap document event run order Potentially, you can have code for a document ev
ent (e.g., OpenDocument) in all three of the documents described above. In such
a situation, the event code will execute in the following order: 1—Project (*.mx
d) 2—Base Template 3—Normal Template
Introduction to Programming ArcObjects with VBA
Visual Basic code: How, where, and when?
3-21
Saving your work
Save modules with a document
ArcCatalog normal template ArcMap normal template ArcMap template (*.mxt) Map do
cument (*.mxd)
Export modules
Form file (*.frm): designer and code Standard and class modules Can be imported
into other projects
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
3-22
Saving maps and templates The primary difference between VBA and regular Visual
Basic is that code in VBA must always be stored in a document. Unlike a programm
er using standalone Visual Basic, a VBA programmer has no way of compiling his o
r her code into a DLL or EXE, for example. Therefore, in ArcMap and ArcCatalog (
or any other application that uses the VBA development environment), all code is
saved with a document of some sort. In ArcCatalog, all customizations are store
d in a single document: Normal.gxt (in the user’s profiles). In ArcMap, remember
that customizations (including code) can be stored at three different levels an
d with various types of documents. Whenever you write code in ArcCatalog or ArcM
ap, you are storing that code in some document on disk, whether you realize it o
r not. All ArcGIS code is stored in either a normal template (normal.gxt, normal
.mxt), a base template (*.mxt), or a map document (*.mxd). When programming in A
rcMap, you need to be especially careful where you place your code, as this will
affect the scope of your customizations. Exporting code modules In addition to
storing your code in one of the documents listed above, you also have the option
of exporting code to a separate file on disk. To export a code module (user for
m, standard, or class module), right-click the desired module in the Project Exp
lorer and choose ‘Export …’ from the context menu that appears. You will be prom
pted for a name and a location on disk for the exported file. When exported, a m
odule’s extension will indicate whether it is a user form (*.frm), a standard mo
dule (*.bas), or a class module (*.cls). These files can then be imported into o
ther projects such as another ArcMap document, ArcCatalog, or even a standalone
Visual Basic project. Note that although you can easily export your code modules
to disk, the code cannot be executed except in the context of an application su
ch as ArcMap or ArcCatalog.
Introduction to Programming ArcObjects with VBA
Visual Basic code: How, where, and when?
3-22
Exercise 3 overview
Create a form Set initial control properties Write code to convert to decimal de
grees Test and debug the form Work with preset variables
Application ThisDocument
Save your work
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
3-23
Exercise 3: Design a user form In this exercise you will: • Create a new user fo
rm. • Add controls to the form. • Set control properties at design time. • Write
code to convert degrees/minutes/seconds values on the form to decimal degrees.
• Test your form with actual latitude and longitude values. • Write code using t
he preset Application and ThisDocument variables. • Export your form to its own
file on disk. • Save your map.
Introduction to Programming ArcObjects with VBA
Visual Basic code: How, where, and when?
3-23
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
3-24
Introduction to Programming ArcObjects with VBA
Visual Basic code: How, where, and when?
3-24
Introduction to Programming ArcObjects with VBA
Using variables
Lesson overview Variables Working with variables Dim (dimension) statement Assig
ning a value to a variable Function procedures Comparing values Decision making:
The If Then statement Controlling If Then Decision making: The Select Case stat
ement Levels of variable scope Procedure-level variables Module-level variables
Public-level variables Static variables Exercise 4 overview
4-14 4-15
4-17 4-19 4-21 4-22 4-23 4-24 4-25
contents
4-2 4-3 4-4 4-6 4-8 4-10 4-12
Using variables
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
Introduction to Programming ArcObjects with VBA
Using variables
4-1
Lesson overview
Variables defined Working with variables: Declaring, assigning values, evaluatin
g Passing and returning values
Function procedures
Comparing values Branching: Making decisions in your code Variable scope
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
4-2
Overview This lesson will cover the use of variables in your Visual Basic code.
Basics of working with variables • Declaring • Setting • Evaluating Storing valu
es in a variable • What kinds of data can be stored in a variable? • Using varia
bles to pass and return values. • Using relational operators with variables. Dec
ision-making structures • If Then • Select Case Variable scope • Procedure • Mod
ule • Public This lesson will discuss the use of variables to contain simple dat
a types, such as numbers and text. The use of object variables will be covered i
n a later lesson.
Introduction to Programming ArcObjects with VBA
Using variables
4-2
Variables
An empty box for storing values
Of a specific type (integer, date, string, etc.) The value stored can change
the VB version of: a² + b² = c², is … dblCSquare = (dblA * dblA) + (dblB * dblB
) convert Celsius temperature … intTempCelsius = InputBox ("Enter temperature (
C): ") intTempFahrenheit = (intTempCelsius * 1.8) + 32
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
4-3
Remember 7th grade algebra? Variables are simply containers (like an empty box)
that can contain a value, and if you have done any type of programming before yo
u probably had to work with variables. The values stored by a variable may be nu
meric (bytes, integers, double-precision floating point decimals, etc.), text (s
tring), dates, or even objects (such as forms, controls, maps, and layers). Vari
ables (as the name implies) can change their value. For example, a variable call
ed ‘myAge’ might have a value of 33 at one point and then be changed to store th
e value 43 shortly thereafter. According to the Visual Basic help, a variable is
… “ … a named storage location that can contain data that can be modified durin
g program execution. Each variable has a name that uniquely identifies it within
its scope. A data type can be specified or not.” Uses for variables in a Visual
Basic program Storing a value returned by a function or calculation
datThreeWeeksFromToday = Date + 21 Date is a Visual Basic function that returns
the current date from the OS
Looping a specified number of times (covered in Lesson 7)
For intCount = 0 To 200
Storing an object property
intLayerCount = theParcelMap.LayerCount
Storing user input
theAnswer = MsgBox ("Format your hard drive?", vbYesNo) Using parentheses force
s a return value.
Representing constant values
PI = 3.1415926535897932
Introduction to Programming ArcObjects with VBA Using variables 4-3
Working with variables
Declaring: Create a variable
Dim strDog As String
strDog strDog
Setting: Store a value
strDog = "Sparky"
Evaluating: Get the value
MsgBox strDog
Sparky
strDog strDog
Sparky
Sparky
strDog
A
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming Arc
Objects with VBA
4-4
Continuing with the variable-as-an-empty-box analogy, there are three things you
will need to do in order to work with your box. To start with, you will need to
create your box (define its size and the type of items it can store). You will
then need to know how to place something inside it or get something out of it wh
en you need it. Declaring variables To create a variable, you can declare it. De
claring a variable accomplishes two things: first, it specifies the name for you
r variable, and second, it defines the type of data to be stored in the variable
. Although it is not technically required, it is good programming technique to d
eclare all variables before you use them (and it is very poor programming techni
que not to declare them). The example above declares a variable called ‘strDog’,
which will contain a string (text) by using the Dim statement (more about Dim o
n the following slide). Storing a value in a variable To store a (simple data ty
pe) value in a variable, use the equal sign ( = ). Whatever is evaluated on the
right side of the equal sign will be stored in the variable. The example above i
s a simple assignment statement; the text Sparky is stored in the variable calle
d strDog. Here are some more examples of assigning a value to a variable. strNam
e = InputBox ("What’s your name?") The text typed from the
user is stored in strName intMySistersAge = intMyAge – 2 sister will always be 2
years younger strApplicationName = Application.Name Whatever my age is, my
ArcMap or ArcCatalog?
Introduction to Programming ArcObjects with VBA
Using variables
4-4
Retrieving a value from a variable To get a value from a variable, you can simpl
y refer to the variable itself. If I have a variable called intPrice, for exampl
e, and it stores the value 30000, I can calculate sales tax with a statement lik
e: intTax = intPrice * 0.0825. The example on the slide above displays the text
stored in the variable strDog in a message box. Notice that the string ‘strDog’
doesn’t appear in the message box—rather, the value stored in the variable is di
splayed. AML and Avenue comparison In AML, all variables are treated as gigantic
strings (regardless of size), and all are put into the same refrigerator-sized
box. Although AML makes it easy to work with variables, it does so at the expens
e of storage space. Visual Basic lets you choose the right kind of variable for
the task. Likewise, in Avenue, a programmer does not need to declare variables,
which makes the code more succinct but makes debugging much more difficult.
Introduction to Programming ArcObjects with VBA
Using variables
4-5
Dim (dimension) statement
Declares a variable for future use Defines the variable as a particular type
Declare variables Dim strFilePathName As String Dim datSparkysBirthday As Date
Dim intCount As Integer Other ways to declare variables (to be discussed later)
.. Private strFilePathName As String Public datSparkysBirthday As Date Static in
tCount As Integer
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
4-6
Dim statement To declare a variable in Visual Basic, it is common to use the Dim
keyword. Dim is short for Dimension (although using the word Dimension would gi
ve you an error). As the name implies, Dim defines what will be stored in your v
ariable and therefore the amount of memory required for it. There are three part
s to a Visual Basic variable declaration statement: the declaration keyword (Dim
, Private, or Public), the name of the variable, and the type of data (or object
) to be stored. The significance of using the Dim, Private, or Public keywords w
ill be discussed shortly. When using the Dim statement, it is a good practice to
declare all variables using mixed case with the first letter in lower case. Usi
ng mixed case in variable names will allow for easier debugging later (as you wi
ll soon discover). Listed below are the simple data types that you can dimension
a variable to store, as well as the amount of memory allocated. Type (bytes) St
ring (10+length) Boolean (2) Date (8) Byte (1) Integer (2) Long Integer (4) Sing
le (4) Double (8) Variant (>16) Sample value Elm Street True or False 1/1/100 to
12/31/9999 0 to 255 -32768 to 32767 -2,147,483,648 to 2,147,483,647 1.401298E-4
5 to 3.402823E38 positive 1.79769313486232E308 maximum Any type
Introduction to Programming ArcObjects with VBA
Using variables
4-6
Variable naming rules Must begin with a letter Cannot contain periods Cannot con
tain data type characters (@, $, %, &, #) Can contain an underscore ( _ ) No mor
e than 254 characters Reserved words cause errors (For, And, Loop) Should have u
nique names within the same scope (more about scope later) Variable naming conve
ntions Using standard variable naming is important for making code easier to fol
low (especially by someone other than the author of the code) and to avoid ambig
uity. The standard developed by Microsoft, and used by most programmers, is to u
se lowercase and uppercase in variable names and to name the variable with a thr
ee-letter prefix indicating the data type. If you follow such a naming conventio
n, other programmers will find it easier to understand your code. Below is a sam
ple of the Microsoft naming convention (commonly referred to as Hungarian notati
on). Type Boolean Byte Date Double Integer String Variant Prefix bln byt dat dbl
int str var Example blnStatus bytAge datBirth dblLatitude intDistance strAddres
s varLongitude
Introduction to Programming ArcObjects with VBA
Using variables
4-7
Assigning a value to a variable
Assign a value directly or with a return value
Use parentheses to return a value from a function
Assign values directly intCount = 23 Assign a function return value strFilePat
hName = InputBox("File to open: ") Assign an object property strMapName = ThisD
ocument.Title
!
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
4-8
To assign a value to a variable, use the equal sign. Whatever appears or is eval
uated on the right side of the equal sign will be stored in the variable. Variab
les may be given a value explicitly, or may derive a value from a calculation, f
unction, or object property. Fun with variables It is safe to say that most pitf
alls encountered when debugging an application can be directly attributed to var
iables. Below are illustrated some common problems. Order of evaluation is alway
s left to right. Use parentheses to change this order.
dblAnswer = 2 * 4 + 8 / 4 – 1 This evaluates to 9.0000 This evaluates to 10.66
67 dblAnswer = (2 * 4) + 8 / (4 – 1)
Storing a decimal number in an integer variable will not give an error; instead,
the number will be rounded behind your back.
Dim intAnswer As Integer intAnswer = 3 / 4 intAnswer now contains the value 1
A value will not be returned from a function unless you place parentheses around
the argument list. intAnswer = MsgBox "Will you marry me?", vbYesNo, "A Proposa
l"
This will give an error intAnswer = MsgBox ("Will you marry me?", vbYesNo, "A P
roposal") This works.
Introduction to Programming ArcObjects with VBA
Using variables
4-8
Avenue comparison In Avenue, there are several requests for changing values betw
een strings (AsString) and numbers (AsNumber). This step is not required in Visu
al Basic, as the software will automatically treat your variable as a string or
as a number depending on the context in which it appears. Below is an example of
code that would not work in Avenue but will in Visual Basic.
Dim strAge As String Dim intNextYearsAge As Integer strAge = "32" intNextYearsAg
e = strAge + 1 number. Here strAge is treated like a
MsgBox "Next year you will be " & intNextYearsAge " Years old" Here intNextYea
rsAge is treated as a string.
Introduction to Programming ArcObjects with VBA
Using variables
4-9
Function procedures
Functions return a value
… by assigning a value to the function name Syntax for calling a function: Value
= Function ( arguments )
Call the TotalPrice function Private Sub Purchase() dblPrice = InputBox ("Enter
price before tax:") dblTotal = TotalPrice(dblPrice) MsgBox "Here is the price i
ncluding tax: " & dblTotal End Sub The function procedure TotalPrice Private Fu
nction TotalPrice(Price As Double) As Double TotalPrice = Price * 1.0775 End Fun
ction
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
4-10
Remember that the only difference between a vanilla-flavored sub procedure and a
function is that a function procedure has the ability to return a value. Visual
Basic has some built-in functions that you have already worked with such as Msg
Box and InputBox. As a programmer using these functions, you can treat them simp
ly as black boxes; you know what needs to be put in, you know what you will get
out, but you do not need to be concerned with how the function actually works. I
n addition to using the standard Visual Basic functions, you may want to write y
our own. Functions can make your life easier as a programmer because they give y
ou the ability to centralize useful pieces of code into reusable units. For exam
ple, you might write a function that returns the average area for a polygon laye
r. Anytime you need this functionality, you can simply call your function, passi
ng in the required layer argument, instead of having to rewrite the functionalit
y (sub procedures can also be reused to perform common tasks; they cannot, howev
er, return a value). Returning a value from a function As a programmer writing a
function procedure, you have the ability to return a single value or object (ho
wever, this single object could be a Collection object that contains several obj
ects). In the function definition, the programmer specifies the type of object o
r value to be returned, as well as any required inputs (parameters). Inside the
function, the programmer can refer to values passed to the function by the names
listed in the function definition. In the code above, for example, Price is lis
ted as a required function parameter (as a double). Inside the function procedur
e, the variable Price will refer to whatever was passed in when the function was
called, regardless of what this variable may have been named in the calling pro
cedure. To pass a value back from a function, the programmer simply sets the nam
e of the function equal to the value he or she wants to return.
Introduction to Programming ArcObjects with VBA
Using variables
4-10
Capturing a function’s return value It is possible to call a function without ca
pturing the return value. Some functions, for example, are used primarily to per
form some action (such as deleting a file from disk) and return a value simply t
o indicate the success of the operation (e.g., True or False). If you are confid
ent that such a function will work (or you simply do not care), you would not ne
cessarily require the return value. To store the result of a function in a varia
ble, you need to place parentheses around the argument list when calling the fun
ction (if there are no required function parameters, you can return a value with
or without using empty parentheses). In the example above, the TotalPrice funct
ion is called from the Purchase sub procedure, with the one required parameter s
urrounded in parentheses. This ensures that the return value will be stored in t
he dblTotal variable.
Introduction to Programming ArcObjects with VBA
Using variables
4-11
Comparing values
Use relational operators ( <, >, <>, = )
Return a Boolean result (true/false)
intAnswer = MsgBox ("Delete File?", vbYesNo) MsgBox intAnswer = vbYes
Functions
IsDate IsNumeric IsNull TypeName
MsgBox "Number? " & IsNumeric(VagueVariable)
strType = TypeName (VagueVariable) MsgBox "Variable is of data type " & strType
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
4-12
Boolean expressions evaluate to True or False In order to make decisions in your
code at run time, you might need to evaluate certain conditions. Common decisio
n making in Visual Basic uses a Boolean value (True or False) in order to run co
rresponding sets of code. To evaluate a variable and return a True or False resu
lt, you can use familiar relational operators such as < (less than), > (greater
than), = (equal to), and <> (not equal to). Visual Basic MsgBox constants The Vi
sual Basic message box function does not return a Boolean result. Instead, it re
turns a numeric value that can be referred to by a constant name. The Visual Bas
ic MgBox constants are: vbYes, vbNo, vbCancel, vbAbort, vbIgnore, vbRetry, and v
bOK. If you need a Boolean value, you can compare the message box result with a
particular constant (as shown in the first example above). Connectors In order t
o check several criteria and return a single Boolean value, you can string toget
her more complex expressions by using connectors such as and, not, and or. To re
turn a True result, both conditions of an and statement must be true; only one c
ondition of an or expression needs to be true to return a True result. The not c
onnector is used to reverse the result of an expression.
Introduction to Programming ArcObjects with VBA
Using variables
4-12
Below are some examples of simple Boolean expressions and their results. Express
ion 13 < 108 "Bob" < > "Sally" "Bob" = "Sally" 13 < 108 AND 10 > 25 13 < 108 OR
10 > 25 NOT 1 > 99934599 "ArcMap" Like "Arc Map" Functions for evaluating variab
les Visual Basic has some functions for evaluating variables. There are three fu
nctions for checking the type of value stored in a variable: IsDate, IsNumeric,
and IsNull. These functions return a Boolean value that indicates whether the va
riable contains a value that can be used as a date or a number or whether the va
lue is Null. The Visual Basic TypeName function returns a string that describes
the data type of a specified variable. Below is an example of how the IsNumeric
function might be used.
Dim strSalary As String strSalary = InputBox ("Enter your salary" ) string varia
ble Dim blnIsNumber As Boolean blnIsNumber = IsNumeric (strSalary) If any non-
numeric characters were entered, this will be False (e.g., dollar signs or comm
as) MsgBox "Did you type only numeric characters? " & blnIsNumber strSalary is
a
Evaluation True True False False True True False
Introduction to Programming ArcObjects with VBA
Using variables
4-13
Decision making: The If Then statement
Branch based on a condition
Use a Boolean expression Make decisions
Syntax example: If a condition is true Then do something... End If
?
If intLayerCount < 1 Then MsgBox "There are no layers in your map!", vbExclaimat
ion End If
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
4-14
If Then The If Then statement in Visual Basic is used to provide a decision maki
ng mechanism in your code. There may be situations in which your program will br
eak under certain conditions such as dividing by zero. In order to avoid such pi
tfalls and to gracefully handle these situations, you can write an If Then state
ment like the one below.
Dim intNumber As Integer intNumber = InputBox ("Enter a number to divide 10 by")
If intNumber = 0 Then MsgBox "No division by zero!!" executes if intNumber = 0
Code here to exit the procedure .. End If MsgBox "Ten divided by " & intNumber
& " is " & 10 / intNumber intNumber can never be 0 at this line above This
code only
Any expression or variable that evaluates to a Boolean value (True or False) may
be used as the basis of an If Then statement, like all of those shown below.
IsNumeric (strApples) MsgBox ("Continue?", vbYesNoCancel) = vbYes myMap.LayerCou
nt > 0 And Not IsNull (intParcels) blnAnswer True
Note: Parentheses may be used for clarity but are not a required part of the If
Then syntax.
If (strName = "Paxton") Then works the same as … If strName = "Paxton" Then
Introduction to Programming ArcObjects with VBA
Using variables
4-14
Controlling If Then
Exit Sub: Exits procedure before completion ElseIf: Check another condition Else
: Code for a False condition
Private Sub WelcomeUser() If strUser = "Mark" Then MsgBox "Welcome Mark" ElseIf
strUser = "Dana" Then MsgBox "Welcome Dana" Else MsgBox "You are not an authoriz
ed user!" Exit Sub End If Code here to add layers to the map … Code here to st
art an edit session … End Sub
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming Arc
Objects with VBA
4-15
Controlling the flow of an If Then statement If Then statements in Visual Basic
can be more complex that those that simply evaluate a single condition. If neede
d, a programmer can evaluate numerous conditions in a single If Then block by us
ing keywords such as ElseIf and Else. Inside an If Then block, execution of the
entire procedure may also be terminated early by using Exit Sub. Exit Sub When t
he Exit Sub line of code is encountered, execution of the procedure is terminate
d immediately. Exit Sub will generally only appear inside of an If Then block in
the context described below. Often, the purpose of an If Then statement in your
Visual Basic code is to check for a condition that will cause a run-time error.
If your code asks the user to input a currency amount, for example, you would w
ant to verify that the input is numeric (e.g., 20.00 instead of $20.00, or twent
y) before attempting to use it in a mathematical operation. If the value is not
numeric, you need to stop execution of the procedure before an error occurs, as
shown below.
dblPrice = InputBox ("Please enter a price (without a dollar sign or commas)" )
If Not IsNumeric (dblPrice) Then NOT numeric check to see if the input is
MsgBox "Please enter only numbers!", vbExclaimation, "Exiting" Exit Sub **Stop
execution of the procedure if the error causing condition is true!** End If dbl
Discount = dblPrice * 0.20 calculate a 20% discount on the price, this line w
ill only execute if dblPrice is numeric
Introduction to Programming ArcObjects with VBA Using variables 4-15
ElseIf and Else To check more than one condition in an If Then block, a programm
er can use the ElseIf keyword. ElseIf requires another Boolean condition to eval
uate. Using ElseIf, it is possible to evaluate a (potentially) infinite number o
f conditions. To provide code for a false condition in an If Then statement, use
the Else keyword. Else does not require another expression, as it provides the
code that will run when none of the other conditions in the If Then … ElseIf blo
ck are true.
theAnswer = MsgBox ("Save edits?", vbYesNoCancel) If theAnswer = vbYes Then Cod
e here to save edits, stop editing ElseIf theAnswer = vbNo Then Code here to st
op editing without saving Else User pressed Cancel Exit Sub End If MsgBox "Edit
session is complete"
Introduction to Programming ArcObjects with VBA
Using variables
4-16
Decision making: The Select Case statement
Branches based on a value
May use a range or list of values Case sensitive
Alternative to several If Then Else statements
Select Case someVariable Case Is = someValue Do this Case someValueA, someValue
B, someValueX Do that Case startValue To endValue Do the other Case Else MsgBo
x "Invalid entry!" End Select
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
4-17
Select Case In addition to the If Then branching construct, a Visual Basic progr
ammer can also use a Select Case statement to make decisions in his or her code.
Unlike an If Then statement, Select Case makes decisions based on the value of
a variable instead of using Boolean expressions. These values do not have to be
numeric; a Select Case statement could also use variables that contain strings,
dates, and so on. For this reason, Select Case is better suited for evaluating a
value against a range or list of values, as shown in the example below.
intBirthDay = InputBox("Enter your age on your next birthday") Select Case intBi
rthDay Case Is < 0 Case 1 To 5 Case 16, 18, 21 Case 55 **evaluate a rela
tionship **evaluate against a range **evaluate against a list **evaluate against
a single value MsgBox "C’mon! You aren’t even born yet??!!" MsgBox "Enjoy yours
elf before you begin school!" MsgBox "Your next birthday will be a landmark!" Ms
gBox "Congrats! You’re eligible for the Senior Discount!" Case Is > 100 Case Els
e **evaluate a relationship **if none of the cases above are true MsgBox "Wi
llard Scott will read your name on the air!" MsgBox "There’s nothing interesting
about your next birthday" End Select
Introduction to Programming ArcObjects with VBA Using variables 4-17
In the example above, the Select Case statement evaluates a numeric input (any t
ype of variable, however, can be used in a Select Case statement). Once a case i
s found that fits the variable’s value, no other cases are evaluated. This means
that even if more than one of the cases fits, only the first one encountered wi
ll execute for a given variable. If none of the cases fit the variable’s value,
the Case Else block of code will execute. If a Select Case statement does not ha
ve a Case Else, no code within the block will execute unless the variable’s valu
e fits one of the cases. The End Select statement must be used to terminate a Se
lect Case statement.
Introduction to Programming ArcObjects with VBA
Using variables
4-18
Levels of variable scope
Procedure-level: Local to a single procedure Module-level: Local (private) to a
single module Public-level: Available to all project modules
Module-level
Public-level Procedure-level
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
4-19
Variable scope The term scope, when referring to a variable, describes the lifet
ime of a variable or how widely it can be used within a Visual Basic project. As
you will see, depending on how you declare a variable, it might be available th
roughout your entire project, within a single procedure, or somewhere in between
. In a Visual Basic project, you will work with three levels of variable scope:
procedure level, module level, and public level. House pets analogy You can thin
k of variables as house pets, each one with a different scope, or range of terri
tory. Procedure-level variables: Procedure-level variables are local to a single
procedure (sub or function). Like the goldfish in the slide above, they are res
tricted to a single goldfish bowl (procedure), outside of which they cannot live
. Module-level variables: Module-level variables are variables that can work wit
hin a single module. Like the housecat above, these variables can roam within a
single house (module) and can visit each goldfish bowl (procedure) inside the ho
use. The housecat is not allowed outside of the house, however, as she will inst
antly be hit by a garbage truck. Public-level variables: Public-level variables
have the widest scope; they are global to an entire Visual Basic project. Public
-level variables are like the dog in the slide above. They can freely roam the n
eighborhood (project) and are welcomed in every house (module) they come to (OK,
so they are not exactly like dogs). Public-level variables are not destroyed un
til the project closes.
Introduction to Programming ArcObjects with VBA
Using variables
4-19
Variable naming conventions II In addition to some of the variable naming conven
tions described earlier, it is common for some programmers (and a good practice)
to name variables with an additional prefix describing their scope, as shown be
low. Public-level: prefix with ‘g_’ (for global) Module-level: prefix with ‘m_’
Procedure-level: no prefix
Introduction to Programming ArcObjects with VBA
Using variables
4-20
Procedure-level variables
Declared within a procedure Not recognized outside its procedure Destroyed when
procedure ends
Procedure1 Private Sub cmdSet_Click() Dim intNumber As Integer intNumber = intN
umber + 1 lblnumber.Caption = intNumber End Sub Procedure2 Private Sub someOthe
r_Event() lblnumber.Caption = intNumber Procedure 2 can’t see it and causes an
error. End Sub
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming Arc
Objects with VBA
1
4-21
Procedure-level variables (often called Local variables) can be seen only in the
procedure in which they are created (declared). Procedure-level variables are d
eclared using the Dim statement inside a procedure (sub or function). Any variab
le that is declared inside of a procedure will automatically be procedure-level
in scope. Procedure-level variables are re-dimensioned each time the procedure e
xecutes. They are also destroyed each time the procedure ends, which means their
value cannot be retained between calls to the procedure (this is not true for S
tatic variables, which will be described later). The example In the example abov
e, the first procedure declares a procedure-level variable called intNumber. Whe
n the procedure is executed, the Dim statement will create this variable and ini
tialize it to 0. (In Visual Basic, numeric variables are set to 0 when they are
declared; this is not true for many other languages such as C++.) The next line
of code increases the value of intNumber by 1. Finally, the value is placed on a
label on the form. Because intNumber is a procedure-level variable, however, it
is destroyed each time the procedure finishes, then recreated (and set to 0) wh
en it runs again. This means the label will always read ‘1’ no matter how many t
imes the user clicks the button. The next procedure in the example tries to use
the intNumber variable. Because intNumber was declared in another procedure, it
is not recognized here, and an error is reported when the code is executed.
Introduction to Programming ArcObjects with VBA
Using variables
4-21
Module-level variables
Declared with Dim or Private in a module’s General Declarations section Must ini
tialize (assign a value) within a procedure Available to all procedures in a mod
ule
Declaration Declaration Initialization Initialization
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
4-22
Module-level variables are variables that can be used throughout an entire code
module. Unlike procedure-level variables, module-level variables are not destroy
ed after the execution of a procedure. Therefore, the values of module-level var
iables can be retained and referenced (or changed) by any procedure inside the m
odule. The variables declared in a module will, however, be destroyed when (if)
the object represented by the module is destroyed (i.e., user forms and classes)
. Module-level variables, of course, cannot be referenced by procedures in other
modules. Module-level variables can be declared in any code module (standard mo
dule, form module, or class module). To declare a module-level variable, simply
place the declaration statement in the module’s General Declarations section (wh
ich is simply the very top of any code module). The declaration statement for a
module-level variable can use the familiar Dim keyword or the keyword Private. T
here is no difference between using Dim or Private in a module-level variable de
claration, although the Private keyword is preferred for clarity (you are, after
all, declaring a variable that will be private to the module). Although module-
level variables must be declared in a module’s General Declarations section, the
y cannot be initialized (set) there. You can only assign values to a variable wi
thin a procedure. Module-level variables in a User Form It is quite common to us
e module-level variables in a form module. Remember that modulelevel variables a
re declared in General Declarations but cannot have values assigned there. When
using module-level variables in a form module, therefore, the best (and therefor
e most common) place to initialize module-level variables is in the UserForm_Ini
tialize event procedure. Because Initialize is the first event procedure to fire
for a form, all later event procedures (button clicks, etc.) will have access t
o the module-level variable values.
Introduction to Programming ArcObjects with VBA
Using variables
4-22
Public-level variables
Declared with Public in the General Declarations section of a module If declared
in a form, other modules must reference form
MsgBox “Hello ” & GetName(frmHello.g_intID)
Available anywhere in the project
frmHello Public g_intID As Integer Private Sub SetID() Randomize g_intID = Int(1
1 * Rnd) more code here End Sub
Copyright © 2001–2004 ESRI. All rights reserved.
Module1 Public Function GetName()as String Select Case frmHello.g_intID Case 0 G
etName = “Hercules” Case 1 more code here End Sub
Introduction to Programming ArcObjects with VBA
4-23
Public-level variables have the widest scope of all Visual Basic variables. They
can be referenced from any procedure in any module inside the project, making t
hem truly global variables. Public-level variables can be declared in any code m
odule (standard module, form module, or class module). To declare a public-level
variable, simply place the declaration statement in the module’s General Declar
ations section (just as you would for a module-level variable). The declaration
statement for a public-level variable must use the Public keyword. Although modu
le-level and public-level variables are always declared in a module’s General De
clarations section, they cannot be initialized (set) there. As a reminder, value
s are always assigned to any variable inside a procedure. Tips for using public-
level variables As a general rule, the use of public-level variables should be a
voided whenever possible. Public variables will remain in memory for as long as
your application is running, unless you explicitly destroy them. This can take u
p valuable memory resources and may be difficult to manage. If you need to use p
ublic variables, it is best to declare them in their own standard module. This w
ay, you can easily keep track of the variables that you have defined with a publ
ic scope. You should be careful when declaring public-level variables in a form
module because even though they are public-level in scope, these variables will
be destroyed when the associated form is unloaded from memory. When referring to
a public-level variable that was declared in a form module, you must preface th
e variable name with the name of the form, as shown in the slide above.
Introduction to Programming ArcObjects with VBA
Using variables
4-23
Static variables
Initialize first time their procedure runs
Does not reinitialize variables (Dim does)
Preserve the value between procedure executions Used for procedure-level variabl
es only
Private Sub cmdSet_Click() Static intNumber As Integer intNumber = intNumber + 1
lblNumber.Caption = intNumber End Sub Click Set a second time: Click Set a th
ird time:
1
2 3
Introduction to Programming ArcObjects with VBA
Copyright © 2001–2004 ESRI. All rights reserved.
4-24
Static variables are simply another flavor of procedure-level variable. Although
static variables can still only be referenced inside the procedure in which the
y were declared, they have the advantage of remembering their last value. In oth
er words, each time you call a procedure that uses a static variable, you can ge
t at its last value. The Static keyword is used to declare procedure-level varia
bles only. You cannot declare a module-level or public-level variable with the S
tatic keyword. Module-level and public-level variables are, by nature, static. T
hey retain their values until their associated module or project are unloaded fr
om memory. The example Remember the earlier example for procedure-level variable
s? In that example, the Dim statement was used to declare the variable, which me
ant that the variable’s value would be destroyed each time the procedure finishe
d and then reinitialized (to 0) when the procedure was called again. In the exam
ple above, intNumber is still procedure-level in scope, which means it cannot be
recognized outside of this procedure (Private Sub Count). Its value, however, w
ill not be destroyed when the procedure finishes execution. This means that the
variable can now act as a counter and effectively keep track of how many times t
he user calls the procedure (clicks the Set button).
Introduction to Programming ArcObjects with VBA
Using variables
4-24
Exercise 4 overview
4A: Review variable scope 4B: Create a guessing game
Generate a random number Pass the number to a function that selects a state Get
the user’s guess from an inputbox Compare each guess to the selected state’s nam
e Keep track of the number of guesses the user makes Write code to give hints ab
out the selected state
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
4-25
Exercise 4A: Work with variable scope In this exercise, you will explore variabl
es of different scope by typing variables and declaration statements into a pred
efined form. Exercise 4B: Create a guessing game In this exercise, you will expl
ore variables of different scope and data types by creating a guessing game. The
application will randomly select one of the states in the United States, zoom i
n to it, then ask the user to guess which state they are looking at. You will al
so write code to keep track of how many guesses the user has made, as well as ho
w many states he or she has guessed correctly. The scope of variables used is an
important factor in the design of this application. It also illustrates some co
mmon uses of variables such as storing an object’s property (state name), storin
g a value returned from a function (the Visual Basic Rnd function), passing valu
es to functions or subs (passing a random number to a procedure that chooses a s
tate), and incrementing a count (number of guesses).
Introduction to Programming ArcObjects with VBA
Using variables
4-25
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
4-26
Introduction to Programming ArcObjects with VBA
Using variables
4-26
Introduction to Programming ArcObjects with VBA
Programming with class
Lesson overview Class Classes and objects Class libraries ArcObjects Class Libra
ries Exploring class libraries with the Object Browser Object Browser icons Crea
ting objects at design time Instantiating an object in code To Set or not to Set
? Coding a class with Visual Basic Client and server environment Distributing yo
ur classes Demonstration: Creating a simple class Exercise 5 overview
5-7 5-9 5-10 5-11 5-13 5-14 5-15 5-16 5-17 5-18
contents
5-2 5-3 5-4 5-5 5-6
Programming with class
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
Introduction to Programming ArcObjects with VBA
Programming with class
5-1
Lesson overview
Understanding objects and classes Class libraries Instantiating objects Declarin
g and setting object variables Creating your own classes Distributing classes
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
5-2
Overview This lecture will discuss some of the more important concepts of object
-oriented programming. Classes defined The difference between an object and a cl
ass Where classes come from Class libraries Referencing additional class librari
es How to work with existing classes Using the Visual Basic Object Browser Insta
ntiating objects Working with object variables How to write your own class Clien
t versus server code How to share your classes with other users Exporting code m
odules
Introduction to Programming ArcObjects with VBA
Programming with class
5-2
Class
A blueprint for creating objects Defines the properties and methods of an object
Some objects can be created new
Ferrari Class
New Ferraris
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
5-3
A class is really nothing more than a blueprint (or template) that defines how o
bjects created from the class will look and behave. A class defines all the prop
erties and methods that a particular type of object will have. As a familiar exa
mple, all the command buttons you have added to your Visual Basic forms belong t
o the CommandButton class. The CommandButton class defines all properties, metho
ds, and events that any CommandButton object will have. In other words, every Co
mmandButton you create (add to a form) has the same set of properties available
in the Visual Basic properties list such as Caption, BackColor, Name, Font, and
Height. It has the same set of events that you can write code for such as Click,
DblClick, and MouseDown. Does this mean that every CommandButton you create wil
l look exactly the same? Of course not. Although the same properties, methods, a
nd events will be available on each object created from the CommandButton class,
they can be coded uniquely. Code that defines a class is stored in a special ty
pe of module, called a Class module. Later in this lesson, you will learn how to
create your own classes by writing code in a Class module. Car analogy Cars pro
vide a good analogy for classes and the objects they create. You can think of th
e car factory as the Class. The factory knows how to produce a certain type of c
ar—a Ferrari, for example. The blueprint of the car used by the factory dictates
that each Ferrari produced will have certain characteristics and behaviors. The
factory can produce new Ferraris, and each one will be made from the same defin
ition.
Introduction to Programming ArcObjects with VBA
Programming with class
5-3
Classes and objects
Ferrari class
Color Engine Year Convertible
Color: Red Engine: V12 Year: 1997 Convertible: False
Color: Blue Engine: V12 Year: 1998 Convertible: True
Objects of the Ferrari class
Map class
Label Extent Layers Scale Projection
Objects of the Map class
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming Arc
Objects with VBA
5-4
The terms Class and Object are often used interchangeably, although there is an
important difference between the two. Remember that a class is the definition fo
r how an object will look and behave. In this respect, a class is abstract; it i
s not real. An object, on the other hand, is a concrete thing that has been crea
ted from a class. An object, of course, has all the characteristics and behavior
s that have been defined on the class, but it is a real object that can be manip
ulated in your code. In other words, you are able to get and set an object’s pro
perties, call its methods to carry out tasks, or write code to respond to its ev
ents. Car analogy continued To continue with the car analogy, the Ferrari factor
y (Class) will create new Ferraris (Objects) that have identical designs (method
s, properties, events). Each Ferrari object that is produced, however, can have
different values for its predefined properties. For example, one Ferrari might h
ave the value Blue for its Color property, while the next has the value Red for
this same property. Although the Ferrari factory knows how to create new cars, y
ou could not put a key in the factory, start it up, and drive off. Likewise, you
could not ask a Ferrari object to make a new Ferrari. An ArcObjects example The
re is an ArcObjects class called Map. The Map class defines the properties and b
ehaviors that all maps have. Obviously, this does not mean that all maps you wor
k with in ArcMap will be identical—simply that they will all have the same famil
iar properties such as Scale, Spatial Reference (Projection), and Layers (none,
one, or several). Every map is produced from this same mold, ready to be manipul
ated by the map user.
Introduction to Programming ArcObjects with VBA
Programming with class
5-4
Class libraries
Libraries contain class definitions
Stored in files (DLL, OLB, TLB, EXE, OCX) ArcObjects are stored in many class li
braries
Can reference additional libraries
ArcMap/ArcCatalog references all the ArcObjects class libraries
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
5-5
A class library is simply a collection of several classes that are contained wit
hin a single file. Class libraries are generally stored in files with extensions
such as .DLL, .OLB, .EXE, or .OCX. Visual Basic for Applications has its own li
brary that contains all the classes you work with in VBA such as Strings, Math,
and Collection. The Microsoft Forms library contains all the classes you have wo
rked with to create user forms such as Forms, CommandButtons, and TextBoxes. All
of the ArcGIS objects are defined in ArcObjects libraries and contain classes s
uch as Map, Layer, Polygon, and Table. Referencing a class library As a programm
er, you have the ability to control which class libraries you work with in a giv
en project. You can bring in additional libraries or remove existing ones from y
our Visual Basic project by choosing References from the Tools menu on the Visua
l Basic Editor toolbar. The References dialog (shown above) allows you to browse
available class libraries, remove libraries that are currently referenced, or c
heck libraries to bring them into the project. By referencing additional librari
es, you give yourself access to more objects, and you may be surprised by the nu
mber of class libraries available on your machine. If you have Internet Explorer
, Crystal Reports, or Visio, for example, you can reference and use the classes
available in those applications in your own application. Note that when programm
ing an application with VBA, you will always have a default set of class librari
es referenced. In ArcMap and ArcCatalog, for example, you will always have a ref
erence to the ArcObjects libraries, as well as the VBA and the Microsoft Forms l
ibrary. All classes defined in these libraries will be available in your project
as soon as you start the application. You only need to make a reference to a cl
ass library if you want to bring in classes that are not defined in one of these
default libraries.
Introduction to Programming ArcObjects with VBA
Programming with class
5-5
ArcObjects Class Libraries
ArcObjects contained in many class libraries Logically grouped based on function
ality
Geodatabase Geometry Cartography
VBA references all class libraries for you by default Developer Help contains in
formation on which library an object belongs to
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
5-6
At ArcGIS 9.x, the ArcObjects have been placed into many different class librari
es, based on functionality (Geometry, GeoDatabase, Cartography, Editor, etc.). T
his is to allow for smaller, more manageable and modular arrangement of the clas
ses. If you click on Tools > References in the Visual Basic Editor, you will not
ice that all of ESRI’s class libraries are referenced for you. These libraries a
re stored in the C:\Program Files\ArcGIS\com directory. If you are working with
previous versions of ArcGIS (8.x), you will notice that all the ArcObjects were
grouped in one large library named esriCore.olb. If you would like to know what
class library a particular ArcObject belongs to, the ArcGIS Developer Help is a
useful resource. For example, within the Developer Help, if you type in the word
Map CoClass into the Index tab and hit enter, you will see information regardin
g this class, including the class library it’s contained in (ESRICarto). There i
s also a handy Library Locator utility that will find which library a particular
class belongs to. The LibraryLocator.exe can be found in C:\Program Files\ArcGI
S \DeveloperKit\tools if you install the Developer Kit with ArcGIS Desktop. Furt
her discussion on the various class libraries will be left for Lesson 17 and the
Extending ArcGIS Desktop Applications instructor-led course.
Introduction to Programming ArcObjects with VBA
Programming with class
5-6
Exploring class libraries with the Object Browser
Library Library list list Search Search string string Search Search matches matc
hes
Classes Classes list list
Properties Properties and and methods methods Arguments and Arguments and return
values return values
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
5-7
The Visual Basic Object Browser The Visual Basic Editor comes with a utility for
browsing the contents of class libraries called the Object Browser (remember th
at object and class are often used interchangeably, so it would be more accurate
to call this a class browser). This utility can be very helpful for writing you
r Visual Basic code. It provides a quick reference for which classes are availab
le, as well as what they can do for you. In later lessons, you will explore some
other utilities that give you information about classes, such as the ESRI Objec
t Browser and the ArcObjects object model diagrams. Using the Object Browser The
Object Browser can be launched by pressing the button shown above or by choosin
g ‘Object Browser …’ from the View menu. At the top of the Object Browser is a p
ulldown list for choosing a class library to search. You will see all referenced
class libraries listed here (including the current project and the Normal.mxt f
ile, which are also considered libraries). By default, the Object Browser will s
earch all referenced libraries. Below the library list is a text box for typing
a search keyword. After providing a keyword and pressing enter (or clicking the
search button to the right), the Object Browser will display all matches for the
string (whether it appears in a class name, property, method, etc.). By selecti
ng a match in the search results list or a class in the class list, a list of me
mbers will be displayed in the Object Browser. Members are basically methods and
properties but could also include events. To get more information about a membe
r, highlight it in the member list and a description of its syntax (e.g., requir
ed arguments) will be displayed at the bottom of the browser.
Introduction to Programming ArcObjects with VBA
Programming with class
5-7
‘I’ is for interface Many of the classes that you will see in the Object Browser
begin with the letter ‘I’, which stands for interface. Interfaces will be cover
ed in great detail in a later lesson. For now, you only need to know that interf
aces are special classes that organize a set of properties and methods. It is th
rough an interface that a programmer communicates with an object. For example, t
he IMap interface has methods such as AddLayer and DeleteLayer and properties su
ch as Extent and Scale. The Map class uses this interface, which gives programme
rs access to these properties and methods.
Introduction to Programming ArcObjects with VBA
Programming with class
5-8
Object Browser icons
Property Method Event Module Class Others …
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
5-9
The Object Browser uses many different symbols to represent items found in a cla
ss library. These icons give you a quick way of distinguishing the various types
of things illustrated in the Object Browser. Although there are several of thes
e symbols, the handful shown above are the ones you will generally be concerned
with. Notice that the icons that appear in the Visual Basic Object Browser are t
he same ones that appear in the Visual Basic code completion list when you are t
yping your code.
Introduction to Programming ArcObjects with VBA
Programming with class
5-9
Creating objects at design time
ArcMap: Customize dialog box VBA: UserForm Toolbox
Objects Objects Class Class
Class Library Class Library Object Properties Object Properties
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
5-10
Design time The term design time refers to the part of the application developme
nt process when you are creating forms and controls, changing control properties
, modifying the user interface, and so on. At design time, you work in an intera
ctive environment with objects such as forms and controls. Creating objects at d
esign time Whether you realized it or not, you have already created objects in t
his course. At design time when you add a new UIControl to the ArcMap or ArcCata
log interface, you are creating a new object. When you create a new user form or
add new controls to a user form, you are also creating new objects. These objec
ts have been defined in one of the available class libraries, and by placing the
m on the interface or on a form, you are producing an instance (or object) from
that class. The example: classes and objects revisited In the slide above, you c
an think of the Toolbox as a visual representation of a class library. It contai
ns all the possible controls you can place on a form. Each of the controls on th
e Toolbox is like a class; they define the methods, properties, and events for e
ach type of control. If you click one of the controls in the Toolbox, does it do
anything? Can you change the properties of one of these controls? No—the contro
ls in the Toolbox simply provide the template for actual controls. Once you drag
a control from the Toolbox to the form, however, you have created an object (an
instance of that particular class of control). Now, working with the object, yo
u can change its properties. You can resize it, change its name and its color, a
nd write code for its click event. If you add another control of the same type (
class), it will have the exact same set of methods, properties, and events, but
you may choose to use them differently.
Introduction to Programming ArcObjects with VBA
Programming with class
5-10
Instantiating an object in code
1. Declare an object variable (As Class) 2. Use Set when assigning an object to
a variable
Use New to create
3. Use methods and properties
Dim myDog As Dog Set myDog = New Dog myDog.Bark
DOG Bark Growl CallPet Name Color
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
5-11
Run time The part of the development process dedicated to executing code is refe
rred to as run time. Declaring an object variable Working with objects in code i
s similar to working with intrinsic data values (such as numbers and strings) in
that the first step is to declare a variable. Object variables are declared the
same way as variables that store standard data types: by using the Dim, Static,
Private, or Public keyword and specifying an object type to store. Just as you
would declare a variable as Integer, String, or Date, you can declare a variable
as CommandButton, Collection, or IPageLayout (more about interfaces later). Onc
e you have declared a variable as a particular type of object, it will only be a
ble to store that type of object. Instantiating or creating an object variable S
etting an object variable equal to a new or existing object is called instantiat
ing an object. Making an object brand new is referred to as creating an object.
As you will learn in more detail later, not all classes allow you to create thei
r objects new. Whenever you instantiate any object variable (unlike intrinsic da
ta variables), you must use the Set keyword. As with intrinsic data variables, w
hatever is evaluated on the right side of the equal sign is stored in the object
variable. For classes that allow objects to be created new, use the Visual Basi
c New keyword. Below are examples of instantiating an object variable with an ex
isting object (a layer in the map) and creating an object with the New keyword (
a new Visual Basic Collection object).
Introduction to Programming ArcObjects with VBA
Programming with class
5-11
Existing instance of a layer Dim pLayer As ILayer Set pLayer = pDoc.SelectedLay
er New instance of a collection Dim myList As Collection Set myList = New Colle
ction
The example The code above works with a class called Dog. By looking at the simp
le diagram of the Dog class (more about object model diagrams in a later lesson
… much more), you can see the methods and properties that are defined for the cl
ass (arrows for methods, boxes for properties). As programmers using the Dog cla
ss, you do not need to be concerned with how a Dog object works, only with what
it can do for you (Bark, Growl, etc.). In this case, the Dog class would be refe
rred to as Server code, while the code that uses a Dog object is called Client c
ode. The server provides a service that the client (somewhat ignorantly) takes a
dvantage of. For your purposes, most of the code you write will be client code.
The ArcObject classes will provide most of the server code. The first line of co
de declares a variable of the appropriate type, Dog. The variable is then instan
tiated (set) by creating a New Dog. The myDog variable now contains an instance
(object) of the Dog class. Finally, because you know (from the diagram) what is
defined on the Dog class, you can successfully call methods such as Bark.
Introduction to Programming ArcObjects with VBA
Programming with class
5-12
To Set or not to Set?
Using VB objects Dim myButton As CommandButton Set myButton = frmMain.cmdApply
Using ArcGIS objects Dim pMap As IMap Set pMap = New Map Using variables of "i
ntrinsic" data types Dim x As Integer x = 1234 ------ No SET keyword
p = pointer to an object variable
Naming convention used for COM object variables
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
5-13
When to use Set One of the most common pitfalls for new Visual Basic programmers
is knowing when—and when not—to use the Set keyword with variables. The answer
is really quite simple, although it may take a little practice before it sticks.
You must use Set when you are instantiating an object variable of any kind. You
must not use Set when you are assigning a value to a variable of a standard dat
a type (strings, numbers, dates, etc.). Can you write it down? A quick way to re
member the rule for using Set is to keep in mind that anything you can write dow
n on a piece of paper is an intrinsic (standard) data type. Anything you cannot
write down on a piece of paper (drawing pictures does not count) will require th
e use of the Set keyword. Variable datBirthday intAge blnMarried strName pMap Se
t pMap = New Map Variable naming conventions continued There is one more convent
ion to add to your list of naming standards. In much of the code you encounter (
and a lot of it in this course), you will notice that object variables are named
with a preceding lowercase ‘p’. This stands for pointer, as object variables do
not really contain the object (the way an integer variable contains an integer)
; instead, they simply point to the referenced object. Type Date Integer Boolean
String Object Write It? 2/28/67 33 False Wendy ? Use Set? No No No No Yes
Introduction to Programming ArcObjects with VBA
Programming with class
5-13
Coding a class with Visual Basic
Class module
Define methods Define properties
Use the class
Set properties Get properties Call methods
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
5-14
Class module: Methods The general procedures of the Dog class module define the
class’s methods. In the example, the Bark procedure contains code that will run
when any Dog instance calls its Bark method. Class module: Properties A class mo
dule also contains property procedures that can store and return values. For exa
mple, the Get and Let property procedures below set up storage and retrieval for
Dog’s Name property.
This is server code. Private m_pDogName as string Public Property Get Name() As
String Name = m_pDogName End Property Public Property Let Name(ByVal vNewName A
s String) m_pDogName = vNewName End Property
Instantiate a dog and set its Name property:
This is client code. Dim pDog as Dog Set pDog = New Dog pDog.Name = "Rex"
Introduction to Programming ArcObjects with VBA
Programming with class
5-14
Client and server environment
Classes are server code
Class modules, class libraries (e.g., ArcObjects)
Client code uses these predefined classes Server Server
Map MyClass Table Layer Text Box Form
Client Client
ArcObjects Libraries
Microsoft Forms Library
Command Button
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
5-15
Client and server relationships In COM there is a relationship between client co
de and server classes. The server provides functionality that a client uses. COM
facilitates the communication between components. In a COM system, the client,
or user of functionality, is completely isolated from the server, or provider of
that functionality. All the client needs to know is that the functionality is a
vailable. With that knowledge, the client can make calls to the server and expec
t the server to honor them. In this way COM acts as a contract between client an
d server. If the server breaks that contract, the system may not respond as expe
cted. In this way COM development is based on trust between the implementer and
the user of functionality. A developer using ArcObjects can assume all these pro
perties and methods have been fully implemented and are there to use if they are
present on the object diagrams. Server storage: EXEs and DLLs The client and it
s servers can exist in the same process or in a different process space. In proc
ess servers are packaged in DLL form and loaded into the client’s address space
when the client first accesses the server. Out of process servers are packaged i
n EXEs and run in their own address spaces. There are diametrically opposed pros
and cons to each packaging method. DLLs load into memory faster, and DLL functi
ons are faster to call. Executables, on the other hand, provide a more robust so
lution (if the server fails, the client will not crash) and better security beca
use the server has its own security context. In a distributed system, EXEs are m
ore flexible, and it does not matter if the sever has a different byte ordering
to the client.
Introduction to Programming ArcObjects with VBA
Programming with class
5-15
Distributing your classes
Save the class in a map or template Save the class module in its own file
Export to create a CLS file Others can load CLS file into their project
Create a DLL, OCX, or EXE file
Cannot do this with VBA Use Visual Basic 6, C++, or similar program
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
5-16
Export a class file You can share your class with others by exporting your class
(CLS) file. Anyone with Visual Basic can import the file. If your file is depen
dent on any libraries, anyone importing the class file will also need those libr
aries. Save a map When you save a map, all code modules are saved with that map.
Your class can be used by anyone opening a map with class modules. The same goe
s for saving modules to template files. Anyone using a template has access to th
at template’s code modules.
Introduction to Programming ArcObjects with VBA
Programming with class
5-16
Demonstration: Creating a simple class
Create a class module to define a Dog Define some simple properties (public vari
ables) Define a Bark method (function) Define a RespondToCall method (sub) Use t
he class in a form’s code
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
5-17
Instructor demonstration Your instructor will now demonstrate how to create your
own class using Visual Basic for Applications.
Introduction to Programming ArcObjects with VBA
Programming with class
5-17
Exercise 5 overview
Write client side code to create NEW Country object Set properties and call meth
ods Instantiate NEW City object
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
5-18
Exercise 5: Create your own class In this exercise, you will: Create a new class
module. Write code to represent a country object. Use a country object in some
client code.
Introduction to Programming ArcObjects with VBA
Programming with class
5-18
Introduction to Programming ArcObjects with VBA
COM before the storm
Lesson overview Introducing COM COM classes have interfaces Working with ArcObje
cts COM classes More on interfaces … Polymorphism ArcObjects polymorphism Using
methods and properties Getting other interfaces Testing an object reference COM
class code Using library names Using the ESRI Object Browser Demonstration: Crea
ting a COM class Exercise 6 overview 6-5 6-6 6-7 6-8 6-9 6-10 6-12 6-14 6-16 6-1
7 6-18 6-19
contents
6-2 6-3 6-4
COM before the storm
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
Introduction to Programming ArcObjects with VBA
COM before the storm
6-1
Lesson overview
COM: Component Object Model Working with COM classes
Interfaces Polymorphism QueryInterface
Testing an object reference
Is it nothing? What type of object is it?
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
6-2
Components For GIS, an object-oriented approach is more flexible compared to the
object approach (e.g., ArcView GIS 3.x) because it adds a framework for anyone
to extend the data model, and end users or third party developers are not restri
cted to developing with a proprietary language (e.g., Avenue or AML). In the bas
ic object model approach, only the original GIS software vendor has complete cus
tomization capabilities and is free from performance and functionality bottlenec
ks. Also, because of the closed nature of the object model approach, users are b
ound to proprietary macro languages for their customization efforts. With the ob
ject component approach, users can extend the data model with exactly the same t
echnology as the GIS software vendor. As a result, users have more options, and
they cannot tell the difference between your custom objects and the GIS vendor-s
upplied objects. COM: Component Object Model COM is a protocol that connects one
software component, or module, with another. With this protocol, it is possible
to build reusable software components that can be dynamically interchanged in a
distributed system. Interfaces All classes used to build ArcMap and ArcCatalog
are COM classes and referred to as ArcObjects. These ArcObjects COM classes use
interfaces to organize properties and methods. Classes may have many interfaces.
QueryInterface COM objects use COM interfaces to communicate with each other. W
hen working with ArcObjects COM objects, the developer never works with the COM
object directly, but via one of its interfaces. When you instantiate a class, yo
u can only use one interface. However, after instantiation, you can query for an
y other interface. Polymorphism Classes can share the same interface but have un
ique implementation.
Introduction to Programming ArcObjects with VBA COM before the storm 6-2
Introducing COM
COM is a standard for creating classes Classes can be reused between application
s
Independent of programming language
All ArcObjects are COM classes Technologies based on COM
Object Linking and Embedding (OLE) OLE DB ActiveX is any technology built on COM
DCOM and COM+
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
6-3
COM is a standard that specifies how classes should be programmed, not a languag
e. COM is a binary specification that establishes a common method of building so
ftware components. These components can then be dynamically interchanged between
applications. The Country class of the previous lesson can only be used in Visu
al Basic. If it were created as a COM class and compiled as a COM DLL, any other
COM-compliant language would be able to use it. Reuse COM allows components to
be reused at a binary level, meaning third party developers do not require acces
s to source code, header files, or object libraries in order to extend the syste
m, even at the lowest level. For this reason, an ArcObjects programmer can work
with a FeatureLayer class without knowing the nuts and bolts of how the class wo
rks; he or she only needs to know what the class is able to do. Because the ArcO
bjects are COM classes, you can easily work with them in conjunction with other
COM objects and applications. Technologies There are many terms in circulation t
hat refer in part to COM: OLE DB, ActiveX, DirectX, and so on; all are technolog
ies based on the COM specification. COM provides support for distributed computi
ng, which is often referred to as DCOM. COM components that interact with each o
ther can be on the same machine or on different machines on the network, and if
the operating system supports COM, these machines can even use different operati
ng systems.
Introduction to Programming ArcObjects with VBA
COM before the storm
6-3
COM classes have interfaces
Objects have one or more interfaces Interfaces define a logical group of methods
and properties Communicate with an object through an interface
GarbageTruck IDrive Fuel Accelerate Brake IGarbage Dump PickUp IRace IDrive Race
Car Fuel Accelerate Brake LapTime PitStop
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
6-4
COM interfaces Developing with COM means developing using interfaces. All commun
ication between COM components happens via the components’ interfaces. Interface
s are standardized by COM rules, so it does not matter what language is used to
create a class. Interfaces help a class evolve over time because new interfaces
can be added. However, once an interface is added, it can never be removed. The
actual implementation can be altered (e.g., an algorithm can be updated without
breaking any third party developer code), but the interface is permanent. Why in
terfaces? Some object-oriented programming languages use only classes and object
s without interfaces. Problems can arise when a class needs to be updated and co
de changes. As the class and its code evolve, client code could become obsolete,
and any client code using the class (instantiating it and using its properties
and methods) may be caused to fail. For example, imagine a car dealer installing
the latest stereo in your car. The new stereo has an AM/FM radio and a CD playe
r. But what if you own cassettes, not CDs? Programming with interfaces would all
ow the dealer to install the new CD interface without changing or removing the c
assette interface. Interfaces solve this problem of evolving code. Once written,
code for an interface never changes; therefore, client code is less likely to b
reak. The client code can assume an interface will never change. If the class ne
eds to be reprogrammed, new interfaces are created. The class evolves without ca
using headaches for the existing client code. When a new interface comes out, th
e class stays the same, but the client can interact with the class through the n
ewest interface.
Introduction to Programming ArcObjects with VBA
COM before the storm
6-4
Working with ArcObjects COM classes
Instantiate COM classes with an interface
Dim <variable> As <some interface>
Interfaces group properties and methods
GarbageTruck Dim pGarbage As IDrive Set pGarbage = New GarbageTruck pGarbage.Fue
l = "Full" pGarbage.Accelerate IDrive Fuel Accelerate Brake Dump PickUp
IGarbage
p = pointer to an object variable
Naming convention used for COM object variables
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
6-5
Interface programming When programming with ArcObjects, you are programming with
objects. More importantly, however, you are communicating with the objects thro
ugh interfaces. You need to remember that methods and properties are not availab
le on an object; they are only exposed through an interface. An object may have
several interfaces, each with a different set of available methods and propertie
s. How do I know which interface to use? Before writing your code, you need to u
nderstand the interfaces that are available for the objects you are using and wh
ich ones contain the methods and properties you require. The next lesson will di
scuss one of the most useful tools for this purpose: the object model diagrams.
Later in this lesson, help utilities such as the Visual Basic and ESRI Object Br
owsers will be discussed. How do I specify the interface I want to use? The inte
rface used to work with an object is specified when the object variable is decla
red. When you declare a variable as a pointer to a particular interface, that va
riable can be used on any object that uses (supports) that interface. Only the m
ethods and properties that exist on that interface may be used, however, and a p
rogrammer will need to declare additional variables for each interface he or she
wants to work with—even if they are on the same object. The example The example
above illustrates declaring a variable (pGarbage) as a pointer to an interface,
IDrive. This variable could be used on any object that supports the IDrive inte
rface. Variables are declared as an interface; they are instantiated, however, t
o point to a specific object. In the example above, pGarbage is set equal to a n
ew GarbageTruck object. Using this variable, you can use only those methods and
properties defined on IDrive. The code above sets the fuel level using the Fuel
property, then accelerates by calling the Accelerate method. At this point, you
could not call the Dump method, as it exists on a different interface.
Introduction to Programming ArcObjects with VBA COM before the storm 6-5
More on interfaces …
Boom box analogy
One object can play radio, tapes, or CDs Must use the proper interface If Tape i
s selected, will not hear the radio Dim pBBox As ITape Set pBBox = New BoomBox p
BBox.FM = True
IRadio ITape ICD
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
6-6
The Boom Box analogy An ArcObject that you work with in your code can be compare
d to a boom box like the one shown above. Although it is a single entity (a part
icular Map, FeatureLayer, Symbol, etc.), the characteristics of the object, as w
ell as the things it’s able to do, are organized on different interfaces. In ord
er to get to the desired characteristics or functionality, you need to make sure
you have tapped into the correct interface. If, for example, you wanted to hear
the radio, you would have to make sure the switch on the boom box was set to th
e Radio setting. Does this mean that you cannot play a tape? No … you would simp
ly need to change interfaces and move the switch to the proper setting (Tape). M
any of the ArcObjects you program with will have functionality that is spread am
ong several interfaces. Just remember that the key to accessing an object’s func
tionality is using variables that point to the appropriate interface. The exampl
e The code above shows an example of a common error when programming with interf
aces. The FM property is not defined on ITape, which is what the pBBox variable
has been defined as. Therefore, Visual Basic does not recognize the property and
gives the error Method or Data Member not Found. The code below, of course, wou
ld fix this problem.
Dim pBBox As IRadio Set pBBox = New BoomBox pBBox.FM = True
Introduction to Programming ArcObjects with VBA
COM before the storm
6-6
Polymorphism
Many classes can support the same interface
All methods and properties May implement methods and properties differently
IDrive
Fuel Accelerate Brake
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
6-7
Interfaces COM interfaces are abstract, meaning there is no implementation assoc
iated with an interface; the code associated with an interface comes from a clas
s implementation. An interface defines properties and methods of an object that
chooses to implement the interface. How that interface is implemented can be dif
ferent depending on the object. The objects inherit the type of interface, not i
ts implementation, so it is called Type Inheritance. A programmer who defines an
interface simply provides definitions for how an object should be interacted wi
th. In the example above, a programmer decided that any vehicle implementing his
or her interface should have a Fuel property that can be written or read, a met
hod called Accelerate to speed the vehicle up, and one called Brake to slow it d
own. The programmer also decided that these two methods will not have any argume
nts passed in. Because an interface does not have any implementation (i.e., code
that makes the properties or methods work in a certain way), all classes that c
hoose to support a given interface can decide how each method and property shoul
d be executed. In the example above, every vehicle could implement the IDrive in
terface. If this were the case, each vehicle could potentially carry out each me
thod and property differently. Even though a boat, for example, would accelerate
differently than a horse and buggy, the code a programmer uses to call Accelera
te on the IDrive interface would be the same.
Dim pWagon As IDrive Set pWagon = New HorseAndBuggy pWagon.Accelerate Dim pTitan
ic As IDrive Set pTitanic = New Boat pTitanic.Accelerate
Introduction to Programming ArcObjects with VBA
COM before the storm
6-7
ArcObjects polymorphism
Many ArcGIS classes exhibit polymorphism General interfaces for all subtypes
ILayer: All layer types (raster, tin, feature, etc.) IGxFile: All ArcCatalog fil
e types (shapefile, map, table, etc.) IActiveView: Map (data view) and PageLayou
t (layout view) Several others …
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
6-8
As an ArcGIS programmer, you will encounter several examples of polymorphism in
ArcObjects. Remember that the advantage of polymorphism is that several classes
can use the same interface (with the exact same methods and properties available
), but each class can implement methods and properties differently. This can be
convenient for a programmer. ILayer All layers that can be brought into ArcMap s
upport the ILayer interface. There are, of course, several different types of la
yers: FeatureLayers (point, line, polygons), RasterLayers (images), and Graphics
Layers, to name a few. As an ArcObjects programmer, you can access any layer in
the map, and be assured that you can use the ILayer interface in order to work w
ith methods and properties that are common to every layer (e.g., change the name
, or turn it on and off). IGxFile All files listed in the ArcCatalog application
support the IGxFile interface. Because all files have a Path property (a locati
on on disk) and can be opened, saved, edited, or closed, these properties and me
thods are defined on this common interface. IActiveView When working in ArcMap,
a user can be in Data view (referred to as Map in ArcObjects) or in Layout view
(PageLayout). In either case, an ArcObjects programmer can access some functiona
lity that is common to both views such as refreshing the display, getting the vi
sible extent, or getting the active data frame.
Introduction to Programming ArcObjects with VBA
COM before the storm
6-8
Using methods and properties
Dim the variable pointing to an interface Instantiate the object (Set) Call meth
ods, set properties
Create a new RaceCar with IDrive Dim pDrive As IDrive IDrive Set pDrive = New R
aceCar pDrive.Accelerate pDrive.Fuel = "Full"
IRace RaceCar Fuel Accelerate Brake LapTime PitStop
pDrive.PitStop
Only use methods and properties for the declared interface
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming Arc
Objects with VBA
6-9
To work with an ArcObjects COM class, you need to dimension a variable that poin
ts to an interface supported by that class. Dimensioning an interface variable,
however, does not give you access to any particular object; it simply defines ho
w you will eventually communicate with the object once it is referenced. The nex
t step, therefore, is to initialize the variable to point to an actual object. S
ome objects can be created by using the New keyword, while others can only be re
turned from another object (a Table can create a Row, for example). Once you poi
nt your variable to a specific object, you can use any methods or properties tha
t exist on that particular interface. The code above, for example, returns an er
ror because the PitStop method exists on an interface other than the one you use
d to declare your variable (Dim pDrive As IDrive). If you need to access methods
, properties, or both on a different interface, you will need to declare another
variable that points to the required interface.
Introduction to Programming ArcObjects with VBA
COM before the storm
6-9
Getting other interfaces
QueryInterface (QI) Access other methods and properties
Create a new RaceCar with the IDrive interface Dim pDrive As IDrive Set pDrive
= New RaceCar pDrive.Accelerate IDrive I Q Switch interfaces Dim pRace As IRace
Set pRace = pDrive IRace pRace.PitStop pDrive.Accelerate **pDrive and pRace po
int to the same object** RaceCar Fuel Accelerate Brake LapTime PitStop
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
6-10
Remember that COM classes have at least one interface. In reality, most of them
have several, and it is not uncommon for an ArcObjects COM class to have ten or
more interfaces. Because you may need functionality that exists on different int
erfaces, you may need to declare more than one variable when working with a sing
le object. Indeed, you will need to dimension a variable for each interface you
want to access. A common point of confusion for programmers new to the concept o
f interfaces is that, contrary to other programming they may have done, one obje
ct does not mean one variable. In fact, you may require several variables to wor
k with a single object in your code. QueryInterface The term QueryInterface refe
rs to the process of using additional interfaces on the same object. You will he
ar this term used often throughout this course, and in the code you will often s
ee it abbreviated as ‘QI’. Here is the basic form for QueryInterface:
Dim A As IInterfaceA Set A = New SomeObject This instantiates the object variab
le (A) Dim B As InterfaceB Set B = A This is QueryInterface. Both A and B are
using the same object from different interfaces
Introduction to Programming ArcObjects with VBA
COM before the storm
6-10
The example In the example above, a variable (pDrive) is declared to point to th
e IDrive interface. This variable is then used to access any methods or properti
es that are needed on IDrive. Eventually, however, it becomes necessary to call
a method (PitStop) that exists on another interface. In order to access this met
hod, the first step is to dimension a variable that points to the new interface
(IRace). A new variable (pRace) is declared, therefore, that points to the IRace
interface. Dimensioning the variable does not point it to an object, however, s
o the next step is to instantiate the pRace variable. A common mistake at this p
oint is to set pRace equal to a New RaceCar. This will give access to the IRace
interface, but on an entirely different RaceCar object. In order to access the I
Race interface on the same RaceCar that pDrive is pointing to, code like this is
needed: Set pRace = pDrive. After this line of code (QueryInterface), both vari
ables are pointing to the same RaceCar object: pDrive using the IDrive interface
and pRace using the IRace interface. Each of these variables can then be used t
o control different aspects of the same RaceCar.
Introduction to Programming ArcObjects with VBA
COM before the storm
6-11
Testing an object reference
Is an object Nothing?
If pLayer Is Nothing Then MsgBox "You must select a layer." Exit Sub End If
What TypeOf object is it?
If TypeOf pLayer Is IFeatureLayer Then MsgBox "You selected a Feature Layer. " E
lse MsgBox "This layer is not a Feature Layer." End If
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
6-12
As an ArcObjects programmer, you will often find it necessary to test the object
variables you are using. The most common tools for testing an object reference
are to see if it is Nothing or to see what TypeOf object it is. Nothing If an ob
ject variable does not reference an object, it will contain Nothing. Nothing is
a Visual Basic keyword that you can use in your code to verify that an object va
riable was properly instantiated. This is particularly important for code that r
elies on the user to provide input. By using an If/Then structure like the one a
bove, your code can handle invalid input a little more gracefully by reporting t
he error to the user and then stopping execution of the procedure. Nothing is us
ed for object variables only. To check for an empty string variable, for example
, use the following syntax:
If strMyString = "" Then
Notice that the empty string is used instead of Nothing, and equals (=) is used
in place of the Is keyword.
Introduction to Programming ArcObjects with VBA
COM before the storm
6-12
TypeOf You may have code that works for several types of objects: a procedure th
at works with the selected layer in the map, regardless of the specific type of
Layer object, for example. In such a case, you would first need to check that th
e selected layer is not Nothing (as described above). Next, you would need to ev
aluate the type of layer that was selected. The tool used for this is the TypeOf
statement. Although it is not proper English, the syntax of the TypeOf statemen
t is:
If TypeOf SomeObjectVariable Is SomeInterface Then …
What the TypeOf statement is really asking is, Does this object support this int
erface? This can be useful for avoiding errors when setting object variables, as
in the example below:
If TypeOf pMxDoc.SelectedLayer Is IRasterLayer Then Dim pRLayer As IRasterLayer
Set pRLayer = pMxDoc.SelectedLayer layer supports IRasterLayer End If You can
be sure that this
Introduction to Programming ArcObjects with VBA
COM before the storm
6-13
COM class code
Class module
Implement methods and properties
Interface module
Define methods and properties
Interface Interface
Server
Client module
Instantiate class Use methods and properties Client
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
6-14
COM classes under the hood The class (Country) that you used in the last exercis
e consisted of a single class module that defined methods and properties. ArcObj
ects COM classes are also written class modules, but are organized quite differe
ntly. To rewrite your Country class as a COM class, you would need to also write
at least one interface for the class to implement (ICountry, for example). Inte
rfaces are also written in a class module and are nothing more than definitions
for methods and properties a class should implement. Interfaces To create an int
erface, simply write the stub code for methods (subs or functions) and propertie
s you want to define. When developing an interface, you need to make sure you pr
oduce a group of methods and properties that form a logical group. It is also th
e interface developer’s duty to define any parameters required for the methods d
efined and whether properties are read-only, write-only, or read–write. Class mo
dules that define interfaces are generally named with a leading ‘I’ (e.g., ICoun
try). Classes Class modules that define a COM class use the Implements statement
in the General Declarations section to list the interface(s) that the class wil
l support. By using the Implements statement, a COM programmer is agreeing to wr
ite code for every method and property that has been defined on the interface. R
emember that it is the Class module that actually implements (performs some acti
on) for methods and properties; therefore, other Class modules could implement t
he same interface and use different code for the interface’s procedures (polymor
phism).
Introduction to Programming ArcObjects with VBA
COM before the storm
6-14
Clients and servers Classes, such as the ArcObjects, provide a service. A progra
mmer using these classes does not need to know how the code works inside (and th
ere is usually no way of finding out anyway); he or she only needs to know what
kind of functionality is available. In other words, what kind of services are pr
ovided. As an ArcObject programmer, you will spend the great majority of your pr
ogramming time writing client code. As the name implies, client code is code tha
t simply takes advantage of services provided by pre-defined classes. Client cod
e uses objects that have been defined by a server (a class library, DLL, or clas
s module, etc.), and uses the methods or properties defined there.
Introduction to Programming ArcObjects with VBA
COM before the storm
6-15
Using library names
Many libraries may share interface or class names
Can explicitly refer to the library first
Create a new point and line from the esriGeometry library Dim pPoint As esriGeo
metry.IPoint Dim pLine As esriGeometry.ILine Set pPoint = New esriGeometry.Point
Set pLine = New esriGeometry.Line
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
6-16
To be more specific with the objects and interfaces you are using in your code,
you may choose to preface class and interface names with the name of the library
from which they are coming. This is particularly important if there are potenti
al conflicts with class or interface names between different libraries. Some cla
ss names may be particularly common in several class libraries, classes such as
Field, Row, or Point, for example. By using the library name, you can be sure th
at you are referencing the right class. To determine what class library a class
or interface belongs to, the ArcGIS Developer Help is a useful resource. In the
Index tab, type the name of the class or interface in question and hit Enter. At
the top of the page, in brackets will be the name of the class library. If you
do not use the library name, and there is a conflicting class or interface name,
the class or interface in the first library encountered will be used.
Introduction to Programming ArcObjects with VBA
COM before the storm
6-16
Using the ESRI Object Browser
Lists classes, interfaces, properties, and methods
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
6-17
The ESRI Object Browser The ESRI Object Browser is a utility for browsing object
libraries. The browser displays details of the coclasses, interfaces, propertie
s, methods, enumerations, and structures contained in one or more object library
. You can load type library information contained in TLB, OLB, DLL, OCX and EXE
files. You can browse all of the objects contained in the loaded object librarie
s, or you can use a search string and search criteria to find specific objects.
For example, you can perform a search to find all the coclasses that use a parti
cular interface. To run the ESRI Object Browser 1) Click Start Button > Programs
> ArcGIS > Developer Tools > Object Browser. 2) File > Object Library Reference
s. 3) Click on Add. 4) Select the second radio button that states – Select from
registry. 5) Reference the class library you would like to browse. 6) Click on O
k. See the ArcGIS Developer Help for further details.
Introduction to Programming ArcObjects with VBA
COM before the storm
6-17
Demonstration: Creating a COM class
Design an interface Create a class that uses (implements) the interface Work wit
h the class in some client code
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
6-18
Instructor demonstration Your instructor will now demonstrate the process for de
fining a simple COM class that implements an interface.
Introduction to Programming ArcObjects with VBA
COM before the storm
6-18
Exercise 6 overview
Write client code to create a COM Country object Use QueryInterface Create a new
instantiate of a City COM class
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
6-19
Exercise 6: Work with COM objects In this exercise you will create COM classes w
ith interfaces, instantiate your classes, and use QueryInterface to get other in
terfaces on an existing object. First, you will design an interface for use on a
Country class. You will define a logical set of methods and properties on the i
nterface. Next, you will rewrite the Country class you made in the last exercise
as a COM class that implements your interface. Finally, you will use the Countr
y COM class in some client code.
Introduction to Programming ArcObjects with VBA
COM before the storm
6-19
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
6-20
Introduction to Programming ArcObjects with VBA
COM before the storm
6-20
Introduction to Programming ArcObjects with VBA
Understanding object model diagrams
Lesson overview ArcObject object model diagrams Relationship symbols ArcMap obje
cts Creatable Class (CoClass) Instantiable Class (Class) Abstract class Inherita
nce Property and method symbols Getting properties Setting properties Finding in
terfaces Wormholes Exercise 7A overview Lesson overview Finding object model dia
grams Finding the right OMD: Step 1 Finding the right OMD: Step 2 7-2 7-3 7-4 7-
5 7-6 7-7 7-8 7-9 7-10 7-11 7-12 7-13 7-14 7-15 7-16 7-17 7-18 7-19 7-22 7-23 7-
24
contents
Finding the right OMD: Step 3 Finding the right OMD: Step 4 Where to begin? Gett
ing into the OMD Example: MxDocument > Map > layer Exercise 7B overview
7-20 7-21
Understanding object model diagrams
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
Introduction to Programming ArcObjects with VBA
Understanding object model diagrams
7-1
Lesson overview
Lesson 7A
Reading an object model diagram
Types of classes Relationships between classes
Symbols for interfaces, properties, and methods Interpreting OMDs to write code
Lesson 7B
ArcObject object model diagrams
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
7-2
Object model diagrams The ArcGIS Developer’s Help includes several object model
diagrams that describe how the ArcObject libraries are put together. As a progra
mmer, these diagrams are invaluable tools that help you plan how to write your c
ode. Specifically, they indicate how to work with certain classes (can objects b
e created brand new or must they be obtained from an existing object, for exampl
e), and how each class is related to others (a Map is composed of several Layers
, for example). This lesson will introduce you to the ArcObject object model dia
grams. You will learn the symbology used to describe ArcObject classes and class
relationships. Code examples based on the diagrams will illustrate the importan
ce of understanding these diagrams in order to work with the ArcObjects.
Introduction to Programming ArcObjects with VBA
Understanding object model diagrams
7-2
ArcObject object model diagrams
OMDs help you write code
Show interfaces, methods, and properties for each class Show relationships betwe
en classes
Over 2,700 classes on several diagrams Over 3,000 interfaces
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
7-3
Conceptually, there is only one ArcObject object model. All of the ArcObject cla
sses are defined in a series of libraries with an .olb extension that work toget
her to create this one conceptual object model. With a default installation, the
se libraries are stored in C:\Program Files\ArcGIS\com. Each ArcObject class is
somehow related to the other ArcObjects because all the libraries work together
to compose ArcGIS. ArcObject object model diagrams, which describe logical subse
ts of ArcObject classes, can be used to determine how one ArcObject is related t
o another ArcObject. If you are writing code to change the projection for a data
frame, for example, you would consult the Geometry Spatial Reference object mod
el diagram. You will find the object model diagrams useful for answering the fol
lowing questions … • Which interfaces does this class support? • Which objects w
ill I need to complete my task? • How can I reference an object of this class? •
Can I create a new instance based on this class? The object model diagrams, how
ever, are not the only source of help you will use when writing code. The diagra
ms are commonly used in conjunction with other sources of help, such as the Visu
al Basic object browser and ArcObject class help. The diagrams, for example, are
not designed to always answer these questions … • What methods and properties a
re on this interface? • Are there any hidden methods or properties on this inter
face? • Are there any other classes that support this interface?
Introduction to Programming ArcObjects with VBA
Understanding object model diagrams
7-3
Relationship symbols
Is a type of Is composed of Creates a Multiplicity Association *
_____ Chicken
CoClass
Bird
Abstract
Nest
CoClass
*
Feather
Class
Egg
2 Class
Wing
Class
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
7-4
Object model diagram symbology In many ways, an object model diagram is like a m
ap. Symbols are used to represent different types of features (i.e., classes) fo
und on the diagram, as well as to show how the classes are related. Just like re
ading a map, in order to understand an object model diagram, you need to consult
the legend. Each diagram has a legend that indicates which types of classes and
relationships the symbols in the diagram represent. Below is a short descriptio
n of the most common symbols found on the object model diagrams. • Inheritance—I
n the example above, a chicken Is a type of bird. This is a superclass–subclass
relationship. As a programmer, this relationship is important because it indicat
es that anything a Bird can do, the Chicken can do. In other words, all methods
and properties defined for a superclass will be available for each of its subtyp
es. • Composition—The chicken diagrammed above Is composed of exactly two wings
and several feathers. If the chicken is destroyed, these other objects are also
destroyed. If there is an exact cardinality in the relationship the number will
be listed on the diagram, a one-to-one relationship is described with a simple l
ine, while an indefinite multiplicity relationship (0 to infinity) is described
with the asterisk (*). •--- Creation—The arrow in the diagram above indicates th
at a Chicken object can be used to create an Egg object. This can be an importan
t relationship for a programmer, because some objects can only be created from o
ther objects. •* Multiplicity—An asterisk is used to indicate potential multipli
city in a relationship. The Chicken class above, for example, is composed of sev
eral Feather objects. The asterisk indicates that there could be anywhere from 0
to an infinite number of Feathers on a Chicken. Some relationships have a range
of possible values, in which case the range will be indicated like this: 0 .. 3
. •— Association—A plain line connecting two classes indicates a simple relation
ship. In this kind of relationship, each object could exist individually. In the
example above a Chicken is associated with a Nest, but if the Chicken was delet
ed, the Nest would still exist. Contrast this relationship with the composition
relationship, in which case the lifetime of an object is controlled by the objec
t to which it is related.
Introduction to Programming ArcObjects with VBA Understanding object model diagr
ams 7-4
ArcMap objects
Classes and their corresponding objects
MxDocument Application
Map
*
Layer
*
FeatureLayer
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
7-5
ArcMap/OMD Example Remember that Application is a preset global variable that po
ints to the currently running application (ArcMap or ArcCatalog). In the simplif
ied object model shown above, you can see that the ArcMap Application object is
composed of ( ) exactly one MxDocument object. This relationship is more than si
mple association; if the Application were closed, the MxDocument could not live
on independently. The MxDocument is composed of ( ) potentially several (*) Map
objects. A Map to an ArcObject programmer is called a Data Frame on the ArcMap u
ser interface. Again, in this composed of relationship, the Map could not exist
independently of an MxDocument. A Map, in turn, is composed of ( ) potentially s
everal (*) Layer objects. Layer is an abstract class that has several subtypes (
), such as RasterLayer, TinLayer, and CadLayer. FeatureLayers are Layers that a
re based on a shapefile, coverage, or geodatabase dataset, such as the States la
yer in the example above.
Introduction to Programming ArcObjects with VBA
Understanding object model diagrams
7-5
Creatable Class (CoClass)
Creatable: Use the New keyword
Dim pMap As IMap Set pMap = New Map
Instantiable: Obtain from other objects
Dim pMap As IMap Set pMap = pMxDocument.FocusMap
OMD symbol: Shaded 3D rectangle
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
7-6
CoClass CoClasses are the only type of class from which instances can be created
with the New keyword. Logically, it makes sense that many objects you work with
should be created only from other objects (Classes), while others should be cre
atable (CoClasses). In ArcMap, for example, you may want to create new Maps, Fea
tureLayers, FillSymbols, or GraphicElements. Although objects can be created new
from a coclass, an ArcObject programmer might still want to access existing ins
tances from other objects. If you needed to reference the selected FeatureLayer
in your user’s map, for example, you would not create a new FeatureLayer (even t
hough you could, it is a coclass), but instead would reference the existing Feat
ureLayer using the MxDocument class. In the object model diagrams, you will find
CoClasses represented as three-dimensional shaded boxes.
Introduction to Programming ArcObjects with VBA
Understanding object model diagrams
7-6
Instantiable Class (Class)
Noncreatable class
Cannot create with the New keyword
Obtain instances from other objects
Dim pNewRow As IRow Set pNewRow = pTable.CreateRow
OMD Symbol: 3D Rectangle with no shade
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming Arc
Objects with VBA
7-7
Class Some objects in the ArcObject libraries can only be created from another A
rcObject. Referred to as Instantiable Classes or sometimes just Classes, instanc
es of these classes are often created by the object that will contain them. A Ta
ble object, for example, can create new Rows, a FeatureClass can create new Feat
ures, and a Workspace can create new Datasets. When you instantiate one of these
objects using another object, the new object will immediately exist in its prop
er context. This makes more sense than creating a brand new Row, for example, an
d then having to place it in the appropriate Table. Attention Although instances
of instantiable classes must always be obtained from another object, you will n
ot always find the ‘creates a’ (--- ) relationship explicitly listed on the diag
ram for these classes. On the Geodatabase OMD, for example, there is no dashed a
rrow between the Workspace and Table classes. Upon scanning the methods on the W
orkspace class, however, you will find that a Workspace can indeed be used to cr
eate a new Table, FeatureDataset, or FeatureClass.
Introduction to Programming ArcObjects with VBA
Understanding object model diagrams
7-7
Abstract class
Not creatable or instantiable
Can never have instances of an abstract class
Define general interfaces for subclasses
Subclasses inherit interfaces
OMD symbol: 2D shaded rectangle
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming Arc
Objects with VBA
7-8
Abstract classes As the name implies, an instance of an abstract class cannot ex
ist (in your code) as a concrete object. Abstract classes are used only to organ
ize and group a set of more specific subclasses. Therefore, you will never find
an abstract class on the object model diagrams that does not have at least one (
usually several) subtypes ( ). In the example above, Layer is an abstract class
that is used to organize a set of subtypes, such as CoverageAnnotationLayer, Fea
tureLayer, and TinLayer. Because of the superclass-subclass relationship, a prog
rammer working with any subtype of Layer can use all the interfaces defined on L
ayer (ILayer or IGeoDataset). The concept of the abstract class exists in your d
aily lives as well. When you talk about a Car, for example, you are talking abou
t an object that has a certain set of characteristics (properties) and has certa
in things it can do (methods), but does not really exist as a concrete object. I
n other words, although you know a Car can accelerate and has an engine, you nev
er see anyone driving a Car; instead you see concrete examples of Car subtypes (
Volkswagen Bugs, Honda Civics, etc.).
Introduction to Programming ArcObjects with VBA
Understanding object model diagrams
7-8
Inheritance
Type of inheritance
QI needed
Interface inheritance
If interface does not inherit from IUnknown or IDispatch QI not needed
Dim pFC As IFeatureClass Set pFC = pSomeObj.FeatureClass No need to QI to IObje
ctClass MsgBox pFC.AliasName
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
7-9
There are two ways interfaces can be inherited to other objects: Type of Inherit
ance Type of Inheritance is what you will typically work with when using ArcObje
cts. Type of Inheritance is provided by the Type of relationship on the Object M
odel Diagrams. For instance, on the last slide Abstract Classes were discussed.
Any class below an abstract class will inherit all interfaces on the abstract cl
ass due to the Type of relationship provided by the Abstract class. With Type of
Inheritance, you still must perform a QueryInterface in order to obtain all the
functionality on an additional interface. Interface inheritance For each interf
ace on the Object Model Diagram, the first line before all methods and propertie
s will indicate which interface is being inherited. In the example above, it is
shown as IFeatureClass: IObjectClass. This means that IFeatureClass inherits fro
m the IObjectClass interface. The majority of ArcObject interfaces will inherit
from IUknown, which provides the backbone for how COM classes are created and th
e ability to QueryInterface. To find out more about IUknown, you may read about
it in any COM book. If an interface does not inherit from IUnknown or IDispatch,
that interface is automatically getting all methods and properties from the int
erface it is inheriting from. In the example above, IFeatureClass automatically
gets all methods and properties from IObjectClass (AliasName, ObjectClassID, and
RelationshipClasses). Although it does not directly appear on the interface, th
e code completion will show properties and methods for both IFeatureClass and IO
bjectClass. IObjectClass also inherits from IClass, which means IFeatureClass in
herits from both IObjectClass and IClass.
Introduction to Programming ArcObjects with VBA
Understanding object model diagrams
7-9
Property and method symbols
Property
Barbell symbol
Property Get Property Get (read) (read)
Property Set Property Set (write) (write)
Method
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
7-10
Symbols for properties, methods, and events Although the object model diagrams s
how all the interfaces that each class supports, they do not show the methods an
d properties for every interface (there simply is not enough room). They do, how
ever, show a complete listing of methods, properties, and events for some of the
more common interfaces on each class. • Property: Properties are illustrated on
the object model diagrams with a box symbol. For each property on the diagram,
a programmer may have the ability to assign (write) a value to the property, or
to get (read) the property’s current value. A box on the right means a programme
r can set the property, a box on the left means he or she can get the property.
Therefore, a programmer can use an object model diagram to determine whether som
e of the more common properties are read-only, write-only, or neither. • Method:
Methods are symbolized on the diagrams with a solid (black) arrow. In addition
to the name of the method, any required arguments from the method, return values
from the method, or both will be specified as part of the diagram listing.
Introduction to Programming ArcObjects with VBA
Understanding object model diagrams
7-10
Getting properties
Return a value
Name: String
Return an object reference
Document: IDocument StatusBar: IStatusBar
Dim strName As String strName = Application.Name Value MsgBox strName Dim pDoc
As IDocument Set pDoc = Application.Document Object MsgBox pDoc.Title Dim pBar
As IStatusBar Set pBar = Application.StatusBar Object
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming Arc
Objects with VBA
7-11
Getting property values In addition to indicating whether a property can be read
or written, the object model diagrams also list the type of value or object use
d for each property. Reading the property listing from left to right, you will f
irst find the barbell symbol for the property, followed by the name of the prope
rty, and finally (on the right of the colon), the value to expect when getting t
he property value (or the type of value to use when setting it). It is important
to know what type of value to expect from a property so you can declare your va
riables appropriately. If you do not declare your variable as the proper return
type, you may receive a type mismatch error. If an interface name is listed as t
he return value, the property returns a reference to the object through this int
erface. However, any other interface the object supports can be used when retrie
ving the property, if desired. In the example above, three variables are declare
d: one as a string, one as a pointer to the IDocument interface, and another to
the IStatusBar interface. These are the documented return types for the Name, Do
cument, and StatusBar properties.
Introduction to Programming ArcObjects with VBA
Understanding object model diagrams
7-11
Setting properties
Property Put: Most ArcObjects properties
Property holds a value or a copy of an object Do not use Set keyword
pLayer.Name = "Port Moresby" No Set keyword
Property Put by Reference: Some ArcObjects properties
Property holds a reference to an object Must use the Set keyword
Set pLayer.FeatureClass = pMoresbyData Must use Set!
If the referenced object changes, property is affected (dynamic)
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming Arc
Objects with VBA
7-12
There are two ways in which a value may be assigned to an object property, by va
lue or by reference. Most object properties are set by value, which means a copy
of the value is stored as the property value. Below is an example of setting a
property by value:
valueY = 43 someObjectVariable.PropertyX = valueY valueY = 100 MsgBox someObject
Variable.PropertyX
In the example above, even though the value of valueY changes later in the progr
am, someObjectVariable’s PropertyX value is unchanged. The value that appears in
the message box above would be 43. Some object properties, however, are set by
reference, which means the property is not assigned using a copy of a value, but
rather with a reference to some existing object. Below is an example of setting
a property by reference:
valueA = 43 Set anotherObjectVariable.PropertyB = valueA valueA = 100 MsgBox ano
therObjectVariable.PropertyB
When a property is assigned with a reference, there is a dynamic association bet
ween the object property and the object that was used to set it. In the example
above, the value 100 would be displayed in the message box because as the value
of valueA changes, so does the value of anotherObjectVariable’s PropertyB proper
ty. When to use set Notice that you must use the Set keyword when assigning a pr
operty by reference, and that you must not use Set when assigning a property by
value. You cannot choose when to use put by value or put by reference when assig
ning a value to an object property. The symbols described above will indicate wh
ich method you must use.
Introduction to Programming ArcObjects with VBA
Understanding object model diagrams
7-12
Finding interfaces
Lollypop symbols ( )
Inherited interfaces are available. Inherited interfaces are available. This int
erface is used by the class. This interface is used by the class. All methods an
d properties are listed. All methods and properties are listed.
These interfaces are available. These interfaces are available. Must look elsewh
ere for specific Must look elsewhere for specific methods and properties methods
and properties (e.g., Object Browser). (e.g., Object Browser).
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
7-13
Remember that the object model diagrams are not the only source of help for writ
ing your code. Object model diagrams are useful for showing all the interfaces s
upported by a given class, but do not, however, list the methods and properties
for every interface (there simply is not enough room). Generally, you will find
methods and properties listed for the most common interfaces on each class. On t
he Map class, for example, you will find a listing for IMap, which is the interf
ace you would be most likely to use. You will also be able to identify other int
erfaces supported by the Map class, such as IMapBookmarks, without a complete li
sting of its methods and properties. Once you know that the Map class supports t
he IMapBookmarks interface, however, you can use the object browser (or other he
lp tool) to find more specific information about that interface. Keep in mind th
at when you see the inheritance ( ) relationship, all interfaces defined on the
superclass will be available for the subclass. To learn more about the IUnknown
interface and its use with other programming languages, explore one of the follo
wing books or Web pages related to COM programming: David Chappell. Understandin
g OLE and ActiveX. Microsoft Press, 1996. ISBN 1-57231-216-5. Wayne S. Freeze. V
isual Basic Developer’s Guide to COM and COM+. Sybex, 2000. ISBN 0-7821-2558-1.
Introduction to Programming ArcObjects with VBA
Understanding object model diagrams
7-13
Wormholes
Conceptually, there is one object model Physically, there are several diagrams
Wormholes connect related classes between diagrams
Class Name
OMD Name
Layer Class on Layer Class on Carto Layer OMD Carto Layer OMD
Element Class on Element Class on Carto OMD Carto OMD
Introduction to Programming ArcObjects with VBA
Copyright © 2001–2004 ESRI. All rights reserved.
7-14
Remember that there is only one ArcObject object model. All of the ArcObject cla
sses are defined in multiple libraries, and all of these classes are somehow rel
ated to other ArcObject classes. To make your life (at least a little) simpler,
the object model diagrams have been organized into logical groups of classes. At
the moment, there are over 60 different object model diagrams, such as ArcMap,
Geodatabase, Raster, Display, and Geometry. When a class on one diagram is relat
ed to a class on another diagram, a Wormhole is used to indicate the related cla
ss and the diagram on which it appears. As a programmer, this is your bridge tha
t connects each of the object model diagrams. In the example above, the wormhole
on Layer indicates that the Layer class is related to the Map class, which can
be found on the Carto Object Model Diagram. The Element class is associated with
the Geometry class, found on the Geometry Object Model Diagram.
Introduction to Programming ArcObjects with VBA
Understanding object model diagrams
7-14
Exercise 7A overview
Interpret a fictitious object model diagram
Answer questions based on class relationships Complete some code
Start using printed ArcObject OMDs
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
7-15
Exercise 7A In this exercise, you will begin by working with a fictitious object
model diagram. You will interpret this (Country) diagram to answer questions ab
out relationships illustrated there. You will then move on to interpret the ArcO
bjects diagrams to answer similar questions and then to write some code in ArcMa
p using the diagrams.
Introduction to Programming ArcObjects with VBA
Understanding object model diagrams
7-15
Lesson overview
Lesson 7A
Reading an object model diagram
Types of classes Relationships between classes
Symbols for interfaces, properties, and methods Interpreting OMDs to write code
Lesson 7B
ArcObject object model diagrams
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
7-16
Object model diagrams The ArcGIS Developer Help includes several object model di
agrams that describe how the ArcObject libraries are put together. As a programm
er, these diagrams are invaluable tools that help you plan how to write your cod
e. Specifically, they indicate how to work with certain classes (can objects be
created brand new or must they be obtained from an existing object, for example)
, and how each class is related to others (a Map is composed of several Layers,
for example). This lesson will introduce you to the ArcObject object model diagr
ams. You will learn the symbology used to describe ArcObject classes and class r
elationships. Code examples based on the diagrams will illustrate the importance
of understanding these diagrams in order to work with the ArcObjects.
Introduction to Programming ArcObjects with VBA
Understanding object model diagrams
7-16
Finding object model diagrams
Large paper diagrams are included with this course Start > Programs > ArcGIS > D
eveloper Help > VB6 Help
Simple and detailed diagrams
PDF files
Course CD Software install folder
All OMDs
Find a specific OMD
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
7-17
Finding ArcObject object model diagrams You will find several (over 50) object m
odel diagrams (OMDs) in the ArcGIS Developer Kit. The diagrams are organized acc
ording to logical groups of objects, such as Map Layers, Output (printing and ex
porting), IMS, and Labeling and Annotation, to name a few. Diagrams are availabl
e in Adobe Acrobat (PDF) format in the ArcGIS installation directory C:\Program
Files\ArcGIS\DeveloperKit\Diagrams). Within this directory, you will see two sub
directories of Object Model Diagrams (Desktop and Engine). The Engine folder con
tains all OMDs that compose the ArcGIS Engine Runtime, which is needed for produ
cts of the ArcGIS Engine Developer Kit product. The Desktop folder contains all
OMDs specific to working with ArcGIS Desktop. You will be using OMDs from both o
f these directories. To download the (free) Adobe Acrobat viewer, visit the Adob
e Web site at:
http://www.adobe.com/products/acrobat/readstep.html
You will also find object model diagrams included with your training material. Y
our class database CD contains Adobe Acrobat versions of each diagram, in additi
on to the three postersized hard copy diagrams that you have been provided (ArcM
ap, Map Layer, and Geodatabase). Other useful information in the ArcGIS Develope
r Help The ArcGIS Developer Help also provides a vast resource to find out infor
mation about all the classes, interfaces, properties and methods that ArcObjects
is composed of. You will also find Developer Guides and Samples here as well.
Introduction to Programming ArcObjects with VBA
Understanding object model diagrams
7-17
Finding the right OMD: Step 1
Use Index/Search tabs to find any Class or Interface
Type in Class or Interface name
Name of OMD/library: Click on this link for Step 2
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
7-18
The Index tab The Index tab is an excellent resource for an ArcObjects Developer
. The Index tab provides an Alphabetical listing of virtually all the contents c
ontained within the ArcGIS Developer Help. This listing also includes all classe
s, interfaces, properties and methods. In the example above, the MxDocument CoCl
ass was found using the Index tab. The help panel provides a comprehensive overv
iew of what the class is used for, as well as all the interfaces MxDocument impl
ements. If you would like to find the Object Model Diagram a particular class is
contained on, the next few slides will step you through, using MxDocument as an
example. The next step is to click on the name of the Library, which in this ex
ample is esriArcMapUI. As a developer, you will find the help as being a great r
esource for finding more information about the classes you want to work with. Th
e help however, does not show the explicit relationships between classes as the
Object Model Diagrams do.
Introduction to Programming ArcObjects with VBA
Understanding object model diagrams
7-18
Finding the right OMD: Step 2
Library will show all interfaces available for all classes
Click Contents tab for Step 3
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
7-19
Libraries Remember, all ArcObjects classes (and their interfaces, properties, an
d methods) are stored in libraries. Many libraries are used to package all the A
rcObjects. Each library is listed in the ArcGIS Developer Help. The example abov
e, shows the ArcMapUI Library, which contains the MxDocument class as seen on th
e last slide. The help panel also shows all the other interfaces the ArcMapUI li
brary contains. You could click on an individual interface to find the members o
f that interface. This slide shows an overview and the contents of the ArcMapUI
Library. If you would like to find the Object Model Diagrams for this particular
library, click on the Contents tab.
Introduction to Programming ArcObjects with VBA
Understanding object model diagrams
7-19
Finding the right OMD: Step 3
Contents shows overviews of all libraries/OMDs
Library Reference contains overviews of all libraries and OMDs
Open OMD for Step 4
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
7-20
The Contents Tab The Contents Tab will list everything in the ArcGIS Developer H
elp in logical groupings. This slide portrays the Library Reference contents. Th
is gives a listing of all the libraries that store all the ArcObjects that compo
se ArcGIS Desktop. Expanding any library (esriArcMapUI on this slide) will give
you: an overview of the library; the contents of the library (as seen on the hel
p panel on this slide; and the Object Model Diagram(s) for that particular libra
ry. Clicking on the Library Object Model Diagram will allow you to open the Obje
ct Model Diagram(s) for that particular library in .pdf format.
Introduction to Programming ArcObjects with VBA
Understanding object model diagrams
7-20
Finding the right OMD: Step 4
Open the OMD in Adobe Acrobat Reader
MxDocument Class from Step 1 Name of OMD/Library
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
7-21
Using Adobe Acrobat Reader Once you have opened the OMD in Adobe, you will see t
he name on the diagram, as ArcMapUI Object Model is highlights on this slide. So
me libraries contain many ArcObjects and are composed of multiple Object Model D
iagrams. The MxDocument class, which the original search was for in Step 1, is h
ighlighted in red. Once you have found the appropriate Object Model Diagram, you
can easily find the relationships to other classes.
Introduction to Programming ArcObjects with VBA
Understanding object model diagrams
7-21
Where to begin? Getting into the OMD
Special preset variables
Application: IApplication interface of the Application object ThisDocument: IDoc
ument interface of the MxDocument object
Your entry point to ArcMap or ArcCatalog
ArcMap OMD
Application ThisDocument
ArcMapUI OMD
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
7-22
You have to start somewhere In Visual Basic for Applications, you will generally
have preset global variables that allow you to easily access the current applic
ation or document. You will find that it is fairly standard for applications tha
t use the VBA development environment to use a preset variable called Applicatio
n. As the name of this variable implies, it points to the current application in
which you are programming. When programming in ArcMap, for example, Application
will point to ArcMap. In ArcCatalog, it will point to ArcCatalog. In Microsoft
Word, it will point to … you guessed it, Word. In any of the above applications,
a programmer could also use a preset variable called ThisDocument that points t
o the document that is currently being customized. Although you have already pro
grammed with these preset variables, you probably did not realize that they poin
t to a specific interface on the objects they represent. The Application preset
variable points to the IApplication interface, while the ThisDocument variable p
oints to the IDocument interface. It will be common in your code to use QueryInt
erface (QI) on these variables to access other interfaces supported by the Appli
cation or MxDocument objects.
Introduction to Programming ArcObjects with VBA
Understanding object model diagrams
7-22
Example: MxDocument > Map > layer
Get the FocusMap (active data frame) from MxDocument
MxDocument may have several Maps ( * )
Get a layer from the the Map
Many types of layers (
Dim Set Dim Set Dim Set
MxDocument
)
*
Map
pMxDoc As IMxDocument pMxDoc = ThisDocument pMap As IMap pMap = pMxDoc.FocusMap
pLayer As ILayer pLayer = pMap.Layer(1)
*
Layer
Is pLayer a FeatureLayer? If TypeOf pLayer Is IFeatureLayer Then MsgBox "Yes!,
it’s a feature layer" End If
Copyright © 2001–2004 ESRI. All rights reserved.
FeatureLayer Others
Introduction to Programming ArcObjects with VBA
7-23
OMD code example: Maps and layers In the example above, the object model diagram
can be used as a guide for writing code. Your starting point for writing code i
n ArcMap is generally the ThisDocument preset variable. By consulting the ArcMap
UI object model diagram, you would find that the IMxDocument interface on MxDocu
ment (rather than the default IDocument interface to which ThisDocument points)
has properties for accessing Maps (data frames). Because of the composed of rela
tionship ( ) shown in the diagram, and the multiplicity (*), you know that an Mx
Document could potentially have several associated Maps. To insure that you get
the Map that your user is currently working in, you use the FocusMap property. L
ooking at the diagram again, you notice that a Map is composed of ( ) potentiall
y several (*) Layers. From the Map, you can retrieve a Layer at a given index po
sition (you are accessing the 2nd Layer in the code above). Finally, because Lay
er is an abstract class that has several subtypes ( ), you would want to test to
see what kind of Layer you have. The TypeOf statement can be used to see if a p
articular object supports a given interface.
Introduction to Programming ArcObjects with VBA
Understanding object model diagrams
7-23
Exercise 7B overview
Interpret the ArcObject object model diagrams
Write your first code accessing ArcObjects Write code to change the ArcMap capti
on Work with the MxDocument and its Maps
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
7-24
Exercise 7B In this exercise, you will write your first ArcObjects code by using
the Object Model Diagrams and ArcGIS Developer help to assist you in determinin
g which objects and classes you need to use. This exercise is intended to show t
he relationships between classes and symbology on the Object Model Diagrams. The
following exercises will provide more detail about the specific classes and obj
ects you use.
Introduction to Programming ArcObjects with VBA
Understanding object model diagrams
7-24
Introduction to Programming ArcObjects with VBA
Maps and layers
Lesson overview Loop review Object model overview Accessing maps Looping through
a collection of maps Managing flow in a loop Accessing layers Working with a ma
p’s layers Looping through layers Working with layer properties Adding a new lay
er to a map Setting a FeatureLayer’s data source Exercise 8 overview
8-6 8-7 8-8 8-9 8-10 8-11 8-12 8-13 8-14
contents
8-2 8-3 8-4 8-5
Maps and layers
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
Introduction to Programming ArcObjects with VBA
Maps and layers
8-1
Lesson overview
Looping Review Accessing maps and layers Looping through maps and layers
Collections Enumerations
Working with layer properties Creating new layers
Setting a layer’s data source
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
8-2
Maps and layers In this lesson, you will learn the basics of working with maps a
nd layers in an ArcMap document. Because an ArcMap document can contain several
maps (i.e., Data Frames), you may need to loop through the entire map collection
. A Map, in turn, is composed of several map layers. You will also learn methods
for looping through a set of map layers. Accessing a document’s Maps Focused ma
p Map collection Layers Accessing layers Creating a new layer Layer properties S
pecifying a data source for a layer Looping Collections: For Next loop Enumerati
ons: Do While/Do Until loops
Introduction to Programming ArcObjects with VBA
Maps and layers
8-2
Loop review
Loop a specified number of times
For Next
Loop based on condition
Do While Do Until
Beware of endless loops
Here is an Endless Loop Do While Not MsgBox("Add a Record?") = vbYes Code here
to add a record to a table MsgBox "Record Added" Loop
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
8-3
When it is known how many times a loop must iterate, For Next is most often used
. For Next loops use an index variable (usually an integer) to control the numbe
r of loop iterations. By default, a For Next index variable is incremented by a
value of 1; optionally, different increments can be used by specifying a step. D
o While and Do Until loops are used to loop based on a condition. These loops wi
ll execute as long as (or until) a condition is true. Do While/Do Until loops ar
e best for looping according to user input (e.g., ‘Do you want to continue?’) or
for looping through items in an enum or cursor (cursors will be discussed later
). To prematurely exit a loop, use Exit Do or Exit For inside an If Then stateme
nt. Endless loops If you have a logic error in your loop, you might get caught i
n an infinite loop. The most common cause of an endless loop is forgetting to up
date the condition on which your loop is iterating. If you get caught in an endl
ess loop, use <Control>+<Break> on the keyboard to get into Break mode (and out
of the endless loop).
Introduction to Programming ArcObjects with VBA
Maps and layers
8-3
Object model overview
MxDocument DataSet * Map
Carto Geodatabase
Table
* Layer
Carto Layer
FeatureLayer 0 .. 1 FeatureClass * FeatureDataset
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
8-4
In this lecture, the objects related to maps and layers will be discussed. Becau
se of how the object model diagrams are organized, the objects discussed here ca
n be found on three separate diagrams: Carto, Carto Layer, and Geodatabase. You
will see wormholes on each diagram that indicate the related class in the other
diagrams. It should be noted that although the name of the diagram is Geodatabas
e, it refers to all formats of data you might use in ArcMap (shapefile, coverage
, ArcSDE or personal geodatabase, and even tabular formats such as INFO and dBAS
E). As you already know, the ArcMap Application is composed of a single MxDocume
nt object. The MxDocument is composed of several (indicated by the asterisk, *)
Map objects, which are also composed of several Layers. Layer is an abstract cla
ss. A Map never literally contains Layer objects; it contains layers of various
types (FeatureLayer, RasterLayer, TINLayer, etc.). One of the types of Layer is
FeatureLayer, which is a layer based on vector data (shapefile, coverage, or geo
database format). A FeatureLayer has either 0 or 1 associated FeatureClass objec
t (indicated by the 0 .. 1 in the diagram). Notice that a FeatureLayer’s associa
ted FeatureClass is listed on the Geodatabase object model diagram. There is a w
ormhole between FeatureLayer on the Carto diagram and FeatureClass in the Geodat
abase diagram. A FeatureClass is the data being displayed by the FeatureLayer (a
shapefile, for example). In reality, a FeatureClass is nothing more than a Tabl
e that also stores coordinate geometry (shape). A Table, according to the diagra
m above, is a type of dataset.
Introduction to Programming ArcObjects with VBA
Maps and layers
8-4
Accessing maps
Access maps from MxDocument Get the active map
Dim Set Dim Set pMxDoc As IMxDocument pMxDoc = ThisDocument pMap As IMap pMap =
pMxDoc.FocusMap
Get all maps (IMaps)
A collection of Maps
Dim pAllMaps As IMaps Set pAllMaps = pMxDoc.Maps
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
8-5
Accessing maps in the document Remember that what are called Data Frames by some
one using the ArcMap interface are called Maps by an ArcObjects programmer. An A
rcMap document (MxDocument) is composed of (potentially) several Maps. Each map
in a document can have a different set of layers, a different extent, and even a
different spatial reference. Maps can be accessed from the document or MxDocume
nt object. All the properties used to access Maps are on the IMxDocument interfa
ce, so it is necessary to first QueryInterface to this interface (see the first
two lines in the example above). Depending on the purpose of your code, you migh
t want to get a particular map (the first one, for example), or the focused map
(i.e., the active data frame), or you might want to access and work with all map
s in the document. To get all maps, use the Maps property, which will return a c
ollection object (IMaps interface) that contains all the document’s maps. Once y
ou have accessed the map collection, you can retrieve a particular map according
to its index position (counting from top to bottom, starting at 0). The focused
map can be referenced by using the FocusMap property on the IMxDocument interfa
ce.
Introduction to Programming ArcObjects with VBA
Maps and layers
8-5
Looping through a collection of maps
Collections are ordered
Reference items by position (index) First item is at position 0
Syntax Example Syntax Example For <index = start> To <end> For <index = star
t> To <end> process each item … process each item … Next <index> Next <index
> Map Dim Dim Set collection example … intIndex As Integer pMaps As IMaps pMap
s = pMxDoc.Maps
0 0 1 1
2 2
For intIndex = 0 To pMaps.Count - 1 MsgBox pMaps.Item(intIndex).Name Next intInd
ex
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
8-6
For Next loops To loop through any kind of collection, you will use a For Next l
ooping structure. For Next loops are used whenever you know how many times the l
oop should execute. This type of loop requires the use of an index variable to c
ontrol loop iterations. This variable is generally an integer, although it does
not have to be. The syntax for a For Next loop is
For index = startNumber To endNumber Next index
Once the endNumber has been reached, the loop finishes execution. By default, th
e index variable is incremented by 1 after each iteration. Optionally, however,
you can specify a step value to change the increment value. The example below wi
ll increment by a value of 2 after each iteration of the loop.
For index = startNumber To endNumber Step 2
Looping on a map collection Because the maps collection has a Count property, yo
u can use this to dictate how many times a loop should execute in order to acces
s each map. Remember that the collection of maps is zero-based (the first item i
s at position 0); therefore, a loop on the collection should execute Count–1 tim
es or an error will occur.
Introduction to Programming ArcObjects with VBA
Maps and layers
8-6
Managing flow in a loop
Exit a loop prematurely when a condition is true
For Next loops: Exit For Do While and Do Until loops: Exit Do
Dim pCityMap As IMap Dim X As Integer For X = 0 To pMaps.Count - 1 If pMaps.Item
(X).Name = "Cities" Then Set pCityMap = pMaps.Item(X) Exit For End If Next X Msg
Box "All Done", vbInformation
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
8-7
Ending a loop Most loops terminate when a condition is no longer true, when a co
ndition becomes true, after a specified number of iterations, or when all of the
elements in a collection have been evaluated. Less common methods of ending a l
oop are to use either the Exit For statement within a For loop or an Exit Do sta
tement within a Do loop as shown in the code example above. Exit For and Exit Do
always occur inside an If Then statement; if a certain condition is true, the l
oop is exited prematurely. In the example, a loop is used to examine each map in
the maps collection. Once the desired map is found (the one named Cities), exec
ution of the loop is terminated prematurely by using the Exit For statement. Usi
ng Exit For and Exit Do can make your code more efficient in examples such as th
is because it avoids the execution of unnecessary code. Example Below is an exam
ple of a loop that could theoretically loop forever, as long as the user chooses
No in the message box. Notice that the entire If Then statement can be written
on a single line.
Do If MsgBox ("Stop?", vbYesNo) = vbYes Then Exit Do MsgBox "Aren’t you bored wi
th this yet?" Loop
Introduction to Programming ArcObjects with VBA
Maps and layers
8-7
Accessing layers
Access layers from Map or MxDocument Get the selected layer (IMxDocument)
Dim pLayer As ILayer Set pLayer = pMxDoc.SelectedLayer
Get a specific layer (IMap)
Dim pLayer As ILayer Set pMap = pMxDoc.FocusMap Set pLayer = pMap.Layer(3)
Get all layers (IMap)
An enumeration of layers
Dim pAllLayers As IEnumLayer Set pAllLayers = pMap.Layers
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
8-8
Accessing layers from a map A Map is basically a collection of layers, and once
you have referenced a particular map, you will find properties (on the IMap inte
rface) for referencing the layers it contains. As with accessing a map from the
document, it is possible to either access a particular layer or retrieve all lay
ers in a map. Unlike the Maps property, however, which returns a collection of m
aps, the Layers property (on IMap) returns an object known as an enumeration (or
enum). An individual layer can also be obtained directly from the MxDocument (I
MxDocument interface) by using the SelectedLayer property. Getting the SelectedL
ayer will return whichever layer is highlighted in the ArcMap Table of Contents
(similar to the idea of an active theme in ArcView GIS 3.x). Enumerations (Enums
) An enumeration, usually called an enum for short, is a package of objects cont
ained (managed) in a single object. It is very similar in concept to a collectio
n. It differs from a collection in several important aspects, however. An enum g
enerally has a very simple interface with the following two methods (and usually
nothing more). Next: retrieves the next item in the enum. Reset: moves the poin
ter back to the top of the enum. Notice that, unlike a collection, there is no w
ay to (easily) reference an object by its position (order) inside the enum. Ther
e is also no easy way to get the number of items in the enum (such as the Count
property found on collections).
Introduction to Programming ArcObjects with VBA
Maps and layers
8-8
Working with a map’s layers
IMap’s Layers property returns IEnumLayers
Like a collection with fewer methods and properties Next returns ILayer Reset mo
ves to top of Enum
Dim pLayer As ILayer Dim pLayers As IEnumLayer Set pLayers = pMap.Layers Set pLa
yer = pLayers.Next Set pLayer = pLayers.Next Set pLayer = pLayers.Next Set pLaye
r = pLayers.Next Nothing
Introduction to Programming ArcObjects with VBA
IEnumLayer Top
pLayers.Reset
Copyright © 2001–2004 ESRI. All rights reserved.
8-9
Working with an enumeration of layers An enum is like a collection in that it st
ores a group of items in a single object. It is much different in how you work w
ith it, however. When an enumeration is first initialized, a pointer (which is m
anaged by the enum) is pointing above the first item in the enum. As items are t
aken out of the enum, this pointer is updated to point to each successive positi
on in the enum. You will find that all enumeration objects have basically the sa
me methods for working with items stored within. Although there are several enum
eration interfaces, each named for the type of object they contain (e.g., IEnumL
ayer, IEnumGxObject, IEnumElement), they generally all have the same two methods
(and no properties). The Next method returns the next item in the enum, then mo
ves the pointer to the next item. Each time Next is called, this pointer is auto
matically moved down in the enum. The Reset method returns the pointer above the
first item in the enum. Plates analogy Working with any enum is like taking pla
tes off a stack. You can take plates off one at a time until you reach the botto
m or until you find the particular plate you want. You are not able, however, to
take a plate out of the middle (by counting down the stack) as you can with a c
ollection. To begin working your way down through the stack again, you need to R
eset in order to put the stack back into its original state.
Introduction to Programming ArcObjects with VBA
Maps and layers
8-9
Looping through layers
Do While or Do Until Loop based on a Condition (Boolean)
Syntax Example Syntax Example Do Until/While <a condition is true> Do Until/
While <a condition is true> Run this code Run this code Loop Loop Layer enum
example Dim pLayer As ILayer Dim pMapLayers As IEnumLayer Set pMapLayers = pMap
.Layers Set pLayer = pMapLayers.Next Do Until pLayer Is Nothing MsgBox pLayer.Na
me Set pLayer = pMapLayers.Next Loop
!
Nothing
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
8-10
Looping based on a condition Looping based on a condition is probably the most c
ommon and useful method of looping. There are two methods that allow for looping
based on a condition and two variations of each. Do While Loops execute while t
he condition in the logical expression evaluates to true. Do While Loops check t
he logical expression at the top of the loop and, if the initial condition is fa
lse, may never loop at all. Under special circumstances, the developer may want
to force at least one evaluation of the loop, in which case the expression can b
e placed at the bottom in a Do Loop While. Do Until Loops or Do Loop Until work
identically to the While loops, except execution terminates when a condition bec
omes true. Looping through map layers Conditional loops are used for looping thr
ough layers because there is no way to (easily) get a count from an enum object
(IEnumLayer), which is required for the For Next loops described earlier. It is
much more efficient to write a loop such as the one shown above. This loop pulls
layers out of the enum one at a time and stores them in a variable (pLayer). Th
e item pulled from the enum is evaluated, and when it becomes Nothing (i.e., the
bottom of the enum is reached), the loop terminates.
Introduction to Programming ArcObjects with VBA
Maps and layers
8-10
Working with layer properties
All layers inherit interfaces defined on the Layer class Properties on ILayer
Name, Visible, ShowTips, MaximumScale, MinimumScale, etc.
Properties on IGeoDataset
Extent, SpatialReference
This code will work for ANY type of layer Access the document’s selected layer
Dim pLayer As ILayer Set pLayer = pMxDoc.SelectedLayer Set basic layer propert
ies pLayer.Name = "Streets" pLayer.Visible = True pLayer.ShowTips = False
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
8-11
Basic Layer properties The layer properties that are available in the Layer Prop
erties dialog from the ArcMap interface are the same ones you will find availabl
e as a programmer. Because all Layers in ArcMap inherit from the generic Layer a
bstract class, they can all use the ILayer and IGeoDataset interfaces. These int
erfaces allow access to basic layer properties such as Name, MaximumScale, Minim
umScale, Visible, Extent, and SpatialReference. Feature Layer properties One of
the most common layer types you will work with is the feature layer. Feature lay
ers are layers based on vector data (such as shapefiles, coverages, and geodatab
ase data). Feature layers have properties such as FeatureRenderer, which control
s how the layer is displayed (symbols, colors, classification, etc.), FeatureCla
ss, which accesses or sets the dataset displayed by the layer, and DefinitionExp
ression, which can be used to restrict the features shown in the layer by using
attribute criteria.
Introduction to Programming ArcObjects with VBA
Maps and layers
8-11
Adding a new layer to a map
Layer is an abstract class: Not creatable
Creatable subclasses: TinLayer, FeatureLayer, RasterLayer, etc.
Make a New FeatureLayer Dim pFLayer As ILayer Set pFLayer = New FeatureLayer A
dd a layer to MxDocument or Map Dim pMxDoc As IMxDocument Dim pMap As IMap Set p
MxDoc = ThisDocument Set pMap = pMxDoc.FocusMap pMap.AddLayer pFLayer
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
8-12
Layer is an abstract class that has several creatable subtypes. As a programmer,
you can create several kinds of layers brand-new by using the New keyword. Reme
mber that a Layer is nothing more than a pointer to some dataset on disk, and th
e symbology (and other basic properties) used to display the data in the map. Th
e type of layer you create depends on the type of data you want to represent in
the map. You can create RasterLayers, for example, to display data that is in Gr
id (or some other image format), TinLayers to display TIN data, and FeatureLayer
s to display vector data (shapefile, geodatabase, or coverage). The example The
code above creates a new FeatureLayer (using the Visual Basic New keyword). The
IMxDocument interface on the current document (ThisDocument) is then used to acc
ess the document’s activated data frame (FocusMap). The AddLayer method is calle
d on the Map, and the new FeatureLayer is passed in as the only required argumen
t. After the code above executes, an empty layer would appear in the ArcMap Tabl
e of Contents (as shown above). Before adding a layer, obviously, a programmer w
ould generally set some of its basic properties, such as its name and the data o
n disk that it will display in the map. You will learn more about working with t
hese layer properties in a later lesson.
Introduction to Programming ArcObjects with VBA
Maps and layers
8-12
Setting a FeatureLayer’s data source
FeatureClass property (IFeatureLayer)
Specifies the data source to display Set by reference (must use the Set keyword)
More about accessing data in the next lesson
Make a new FeatureLayer Dim pFLayer As IFeatureLayer Set pFLayer = New FeatureL
ayer Get another layer’s FeatureClass Dim pFClass As IFeatureClass Set pFClass
= pSomeOtherLayer.FeatureClass Set the new layer’s FeatureClass property Set pF
Layer.FeatureClass = pFClass
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
8-13
Working with a FeatureLayer’s FeatureClass property Feature layers are based on
a type of dataset known as a FeatureClass. FeatureClasses are datasets that have
a single feature type (point, line, polygon), a common set of attributes, and a
common spatial reference. FeatureClasses are basically just a collection of fea
tures and their associated attributes. Examples of FeatureClasses are Shapefiles
, Coverages, and Geodatabase datasets. To access a FeatureLayer’s dataset, use t
he FeatureClass property on IFeatureLayer. This is a read–write property, so in
addition to simply getting a FeatureLayer’s data source, you can also set it. Fe
atureClass is a property put by reference, which means you must use the Set keyw
ord when setting this property (see the example above). The example The code abo
ve simply gets the FeatureClass from one FeatureLayer in the map, then assigns i
t as the data source for a new FeatureLayer by setting the new layer’s FeatureCl
ass property equal to the same FeatureClass object. This code has simply made a
copy of an existing layer in the map (probably with different symbology, however
). The code below is more succinct and would also work.
Dim pFLayer As IFeatureLayer Set pFLayer = New FeatureLayer Set pFLayer.FeatureC
lass = pSomeOtherLayer.FeatureClass
Introduction to Programming ArcObjects with VBA
Maps and layers
8-13
Exercise 8 overview
Loop
Maps in a document Layers in a map
Optional steps (choose one: 3, 4, or 5)
Fields in a layer table Determining object reference Add a layer to a map
Set basic properties Set the data source
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
8-14
In this exercise, you will write code to manage maps in the current document, la
yers in the maps, and fields in each attribute table. You will also write code t
hat adds a layer to the map.
Introduction to Programming ArcObjects with VBA
Maps and layers
8-14
Programming ArcInfo with Visual Basic for Applications ModuleTitle
Data access and creation
Lesson overview 9-2 Data creation objects 9-3 Opening an existing Workspace 9-5
Connecting to an ArcSDE database 9-7 Getting a FeatureDataset 9-8 Getting Featur
eClasses 9-9 Pseudocode: Adding a data layer 9-10 GxDialog 9-11 Example: GxDialo
g 9-12 Exercise 9A overview 9-13 Working with Name objects 9-14 Creating a new W
orkspace 9-15 Creating a new Table or FeatureClass 9-17 Field and Fields classes
9-18 IField and IFieldEdit 9-19 Creating a Fields collection 9-20 Creating a Ta
ble or FeatureClass 9-21
contents
Work with fields in a table 9-23 Adding rows and values to a table 9-24 Exercise
9B overview 9-26
Data access and creation
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
Introduction to Programming ArcObjects with VBA
Data creation
9-1
Lesson overview
Data creation objects
Workspace FeatureDataset FeatureClass
Workspace Workspace FeatureDataset FeatureDataset FeatureClasses FeatureClasses
Working with fields and field collections Creating Tables and FeatureClasses Add
ing rows Editing table values
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
9-2
Overview This lesson will discuss how to access existing data on disk as well as
how to create new data. You will learn how to create and define new fields for
a table or feature class, how to add records (rows or features), and how to add
new values. Specifically, the following objects related to working with data wil
l be examined: WorkspaceFactory Workspace FeatureDataset Table FeatureClass Fiel
ds/Field Name Row Feature
Introduction to Programming ArcObjects with VBA
Data creation
9-2
Data creation objects
WorkspaceFactory WorkspaceFactory Workspace
*
Dataset
Field
1 ..
*
Fields
ShapefileWorkspaceFactory
Row
Table
AccessWorkspaceFactory FeatureClass
ArcInfoWorkspaceFactory Others
Which ones can be created new? Which ones can be created new?
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming Arc
Objects with VBA
9-3
Object Model overview Notice that a lot of the objects used to access or create
data are Classes, which means they cannot be created with the New keyword. These
objects (such as Workspace, Table, and Row) must be created from another class.
The first step in working with data on disk is to reference a Workspace object.
A Workspace is simply a folder that contains data (shapefiles, coverages, geoda
tabase, tables, etc.). Once you have a Workspace, you can get to all the dataset
s contained within. Workspaces Although all Workspaces implement the same interf
aces, Workspace objects come in various forms, some of which are listed below (t
his is a good example of polymorphism). ArcInfo Workspace: A directory containin
g coverages and an INFO subdirectory Shapefile Workspace: A directory containing
ESRI shapefiles Access Workspace: A personal geodatabase containing tables and
feature datasets SDE™ Workspace: An ArcSDE™ instance that contains tables, featu
re datasets, and layers Raster Workspace: A Workspace containing grids and image
s TIN Workspace: A Workspace containing TINs You can only access datasets of the
type identified by your Workspace object. For example, if you have a directory,
C:\Data, that contains both shapefiles and coverages, you would need two Worksp
ace objects in your code to get at all these datasets (one Shapefile Workspace a
nd one ArcInfo Workspace).
Introduction to Programming ArcObjects with VBA
Data creation
9-3
Dataset According to the diagram above, a Workspace is associated with several (
*) datasets. A dataset is an abstract class that represents both geographic and
nongeographic data collections such as tables, feature datasets, grids, and imag
es. Datasets are accessed through the Workspace that contains them. If you look
at the detailed Geodatabase diagram, you will notice a lot of subclasses that in
herit from the abstract dataset class (such as Table, ObjectClass, FeatureClass,
GeoDataset, etc.).
Introduction to Programming ArcObjects with VBA
Data creation
9-4
Opening an existing Workspace
Use IWorkspaceFactory to return a Workspace object
Generic interface for all sub-types of WorkspaceFactory OpenFromFile: Access an
existing folder on disk Open: Connect to an existing database (e.g., ArcSDE)
Dim pWFactory As IWorkspaceFactory Dim pWFactory As IWorkspaceFactory Set pWFact
ory = New ArcInfoWorkspaceFactory Set pWFactory = New ArcInfoWorkspaceFactory Di
m pWorkspace As IWorkspace Dim pWorkspace As IWorkspace Set pWorkspace = pWFacto
ry.OpenFromFile("D:\Covers", 0) Set pWorkspace = pWFactory.OpenFromFile("D:\Cove
rs", 0)
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
9-5
The first step in accessing data on disk is to reference the Workspace that cont
ains the data. Because the Workspace class is a Class (instantiable, but not cre
atable), a programmer must access objects of this class from other objects. In t
he case of an existing Workspace, you can use the WorkspaceFactory object to ins
tantiate a Workspace. WorkspaceFactory As the name implies, a WorkspaceFactory c
an create Workspace objects. According to the type of data you want to access, u
se the corresponding WorkspaceFactory CoClass. For example, to access ArcInfo co
verages, you need to create your Workspace using an ArcInfoWorkspaceFactory; to
open personal geodatabase feature classes, you need to create a Workspace from a
n AccessWorkspaceFactory, and so on. Either of the methods below can be used to
open an existing Workspace. OpenFromFile: use for Workspaces that do not require
a connection such as folders or a personal geodatabase on your local machine. O
pen: use to open Workspaces that you need to connect to such as an ArcSDE databa
se. The Open method takes a PropertySet object as an argument, which contains al
l connection information. Both methods (OpenFromFile and Open) have a second arg
ument being a window handle (or OLE_HANDLE). A window handle is a long value, th
at the operating system assigns to each window on your computer. Therefore, if f
or example, you type in the wrong path to your directory, VBA will tie the dialo
g box indicating this error, with the ArcMap application. In VBA, you may specif
y 0, as this is a default number that tells VBA to get the ArcMap window handle.
Introduction to Programming ArcObjects with VBA
Data creation
9-5
PropertySet A PropertySet is a collection of name–value pairs. PropertySets supp
ort methods to find properties by name. Property Values are represented as Varia
nts. This allows a Property Value to hold either a common type, such as a string
or a number, or a COM object. PropertySets are used to represent the metadata a
vailable for any dataset. PropertySets can also be used to represent the set of
properties for an individual feature in the database. For example, a PropertySet
used to store connection information for an ArcSDE Workspace may contain userna
me, instance, and password properties. hWnd This argument is very important for
the user-interface programmer. OpenFromFile and Open might display a dialog if t
he file does not contain all of the necessary properties required for connecting
. In this situation, the dialog needs to know that parent window to maintain the
correct modality. Not using it could result in OpenFromFile creating a dialog t
hat is parented incorrectly. (For example, the parent of the dialog could end up
being some other application.) If you are calling Open from ArcMap, you can pas
s in the ArcMap application’s hWnd. Getting the ArcMap or ArcCatalog hWnd: Appli
cation.hWnd There are two cases where you can use 0 (zero): • You know that all
the required properties are contained in the connection file. • You are calling
it from a non-GUI application.
Introduction to Programming ArcObjects with VBA
Data creation
9-6
Connecting to an ArcSDE database
Use SDEWorkspaceFactory
Use IWorkspaceFactory to retrieve a workspace
Set connection properties with IPropertySet
Use SetProperties method to set Database Connection properties (Server, Instance
, etc)
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
9-7
Use the SDEWorkspaceFactory to retrieve a Workspace object, just as you would if
you want to connect to a folder containing shape. The last slide shows the Open
FromFile method to open an ArcInfoWorkspaceFactory. If using an ArcSDE Workspace
, use the Open method, which asks for a ConnectionProperties parameter. With the
ConnectionProperties parameter, you can pass in a PropertySet object which allo
ws you to set the database connection properties. Note that when using the examp
le below, the password is exposed in the code. You could get around this by havi
ng the user fill it in through a form that you create. The password could also b
e stored by creating custom components (.dlls). Creating custom components is di
scussed in the Extending ArcGIS Desktop Applications instructor-led course.
Public Function openSDEWorkspace(Server As String, Instance As String, User As S
tring, _ Pswd As String, Optional Dbse As String = "", Optional version As Strin
g = "SDE.DEFAULT") As IWorkspace Dim pPropSet As IPropertySet Dim pSdeFact As IW
orkspaceFactory Set pPropSet = New PropertySet With pPropSet .SetProperty "SERVE
R", Server .SetProperty "INSTANCE", Instance .SetProperty "DATABASE", Dbse .SetP
roperty "USER", User .SetProperty "PASSWORD", Pswd .SetProperty "VERSION", versi
on End With Set pSdeFact = New SdeWorkspaceFactory Set openSDEWorkspace = pSdeFa
ct.Open(pPropSet, 0) End Function
Introduction to Programming ArcObjects with VBA
Data creation
9-7
Getting a FeatureDataset
IFeatureWorkspace interface on Workspace
OpenFeatureDataset method
Dim pFWorkspace As IFeatureWorkspace Set pFWorkspace = pWorkspace QI for IFeatu
reWorkspace Dim pCover As IFeatureDataset Set pCover = pFWorkspace.OpenFeatureDa
taset("streets") Workspace Workspace
FeatureDataset FeatureDataset FeatureClasses FeatureClasses
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
9-8
FeatureDatasets A FeatureDataset is simply a collection of FeatureClasses. ArcIn
fo coverages, for example, are all FeatureDatasets. A single coverage may contai
n several feature types (such as Polygons, Lines, Label Points, and Tics), each
of which is a FeatureClass. A Geodatabase might also contain FeatureDatasets, wh
ich, like coverages, can organize a set of FeatureClasses. The concept of a Feat
ureDataset does not exist for Shapefiles, as Shapefiles are FeatureClasses in th
emselves and cannot contain more than one feature type. Getting a FeatureDataset
On the Workspace class, the IFeatureWorkspace interface has several methods tha
t are dedicated to accessing or creating all types of datasets. It is here that
you will find the OpenFeatureDataset method that can be used to open ArcInfo cov
erages or geodatabase feature datasets (depending on the type of Workspace you h
ave referenced). To open a feature dataset from a Workspace, you only need to pr
ovide the name of the dataset, as shown in the example above.
Introduction to Programming ArcObjects with VBA
Data creation
9-8
Getting FeatureClasses
Use IFeatureClassContainer to get existing FeatureClasses from a FeatureDataset
Dim Dim Dim Dim Set Set Set Set
pFCC As IFeatureClassContainer pFCC As IFeatureClassContainer pStreetArcs As IFe
atureClass pStreetArcs As IFeatureClass pFCC = pCover QI for IFeatureClassConta
iner pFCC = pCover QI for IFeatureClassContainer pStreetArcs = pFCC.ClassByName
("arc") pStreetArcs = pFCC.ClassByName("arc")
FeatureClasses FeatureClasses
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
9-9
FeatureClasses Remember that a FeatureClass is a set of features that have the s
ame feature type (all points, lines, or polygons), the same set of attributes, a
nd the same spatial reference (coordinate system, extent, etc.). FeatureClasses
can exist directly inside a Workspace, as in the case of a Shapefile in a folder
, or can reside within a FeatureDataset, as in the case of polygons inside a par
ticular ArcInfo coverage. In a geodatabase, FeatureClasses can exist either insi
de a FeatureDataset or directly inside the Workspace (both situations can exist
in the same geodatabase). Getting a FeatureClass Using the IFeatureWorkspace int
erface on the Workspace class, a programmer can access FeatureClasses that are s
tored directly inside the Workspace by using the OpenFeatureClass method (this i
s how you would access a Shapefile from a particular folder, for example). In th
e case of FeatureClasses that are stored in a FeatureDataset, a programmer can u
se the IFeatureClassContainer interface on the FeatureDataset object. As the nam
e implies, the IFeatureClassContainer interface is used to get at the contents o
f a FeatureDataset. FeatureClasses can be accessed from this interface with prop
erties such as ClassByName, ClassByID, or Class(index). All FeatureClasses can b
e accessed (and returned as an enum) by using the Classes property.
Introduction to Programming ArcObjects with VBA
Data creation
9-9
Pseudocode: Adding a data layer
Get the MxDocument using ThisDocument Get the MxDocument using ThisDocument Get
the active Map from the MxDocument Get the active Map from the MxDocument Make a
new FeatureLayer object Make a new FeatureLayer object Make a new ShapefileWork
spaceFactory object Make a new ShapefileWorkspaceFactory object Get a Workspace
from the ShapefileWorkspaceFactory Get a Workspace from the ShapefileWorkspaceFa
ctory Get the FeatureClass from the Workspace Get the FeatureClass from the Work
space Set the FeatureClass for the FeatureLayer Set the FeatureClass for the Fea
tureLayer Assign the Name and ShowTips properties for the FeatureLayer Assign th
e Name and ShowTips properties for the FeatureLayer Add the FeatureLayer to the
Map Add the FeatureLayer to the Map
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
9-10
Pseudocode is code that cannot be understood or executed by Visual Basic; instea
d, it is used to help a programmer begin to solve a coding problem. Oftentimes,
pseudocode can be a useful first step in designing an application. It should be
written so it can be easily understood yet should also conform to the general st
ructure of a Visual Basic program. After outlining a program in pseudocode, it s
hould be a fairly straightforward task to convert the pseudocode into actual Vis
ual Basic code. The pseudocode above adds a shapefile as a new layer in the acti
ve dataframe. Does this pseudocode help you better see the overall process? Woul
d you find this helpful in writing your code, or an unnecessary step?
Introduction to Programming ArcObjects with VBA
Data creation
9-10
GxDialog
ArcCatalog type dialog box for browsing directories
User-friendly identification of input/output files Can open modally for saving o
r opening a file
Properties that define appearance and behavior
StartingLocation Title ObjectFilter AllowMultiSelect FinalLocation
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
9-11
GxDialog provides the developer with an easy way to let the user specify input o
r output files. Like ArcCatalog, GxDialog lets you connect or disconnect folders
or view thumbnails of your spatial data. GxDialog will always open modally, mea
ning you cannot interact with any other application until the dialog is closed.
A GxDialog can be used to open or save a single file or to open several files. B
efore opening a GxDialog, you may want to set several of its properties. You can
use the StartingLocation property to indicate a pathname to show the dialog box
to begin browsing. Use the ObjectFilter property to specify types of items to s
how in the dialog box. Use the Title and the ButtonCaption to specify text for t
he dialog box title bar and the OK button. When a user is through browsing, you
can find the last directory he or she entered with the FinalLocation property of
the GxDialog object. To access objects that were selected (for input), an IEnum
GxObject object is provided as a parameter.
Introduction to Programming ArcObjects with VBA
Data creation
9-11
Example: GxDialog
Dim pGxDialog As IGxDialog Dim pGxObjEnum As IEnumGxObject Set pGxDialog = New G
xDialog
pGxDialog.AllowMultiSelect = True pGxDialog.StartingLocation = "C:\Esri\EsriData
\Mexico" pGxDialog.Title = "Select Files for Input" pGxDialog.ButtonCaption = "G
O!" pGxDialog.DoModalOpen 0, pGxObjEnum
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
9-12
The example above uses only a few lines of code to present the user with an intu
itive dialog box for specifying several input files. Notice that a required para
meter for the DoModalOpen method is an EnumGxObject. This variable will contain
all files (GxObjects) selected by the user. If AllowMultipleSelect is set to fal
se (the default), this enumeration object is still required to store the single
selected object. When asking the user to save a file, use DoModalSave. This meth
od has no parameters. If AllowMultiSelect was set to False, you could access the
one file that was selected with code such as this (also test to see if it is No
thing, because the user might have pressed Cancel)
Dim pGxObject As IGxObject Set pGxObject = pGxObjEnum.Next If pGxObject Is Nothi
ng Then Exit Sub
If you wanted to read through the selected files and delete certain types (e.g.,
shapefiles), you might use code such as the following to loop through the enume
ration.
Dim pGxObjEdit As IGxObjectEdit Set pGxObj = pGxObjEnum.Next Do Until pGxObj Is
Nothing If pGxObj.Category = "Shapefile" Then Set pGxObjEdit = pGxObj pGxObjEdit
.Delete End If Set pGxObj = pGxObjEnum.Next Loop
Introduction to Programming ArcObjects with VBA
Data creation
9-12
Exercise 9A overview
Add a layer to a map
Set a shapefile data source
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
9-13
Introduction to Programming ArcObjects with VBA
Data creation
9-13
Working with Name objects
A lightweight version of the object it represents
Use Open on IName to return the object
Several creatable subtypes
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
9-14
A Workspace by any other name … A Name object identifies and locates a geodataba
se object (such as a dataset or a Workspace) or a map object (such as a layer).
Although a Name object is simply a surrogate for the object it represents, it su
pports an Open method that a programmer can use to instantiate the actual object
represented. The Open method lets you instantiate the actual object from the Na
me object. The example below uses QueryInterface to get the IName interface on a
feature class name then instantiates the corresponding feature class using the
Open method.
Dim pName as IName Set pName = pFeatureClassName Set pFeatureClass = pName.Open
IUnknown Pointer If you look at the Open method (on IName) on the Geodatabase ob
ject model diagram, you will notice that its return value is listed as IUnknown
Pointer. This may seem confusing at first glance; how can a programmer tell what
kind of object is actually returned from the Open method? Because there are sev
eral classes that support the IName interface, including FeatureDatasetName, Wor
kspaceName, and TableName, there is no way the diagram can list specifically wha
t will be returned when the Open method is called. When Open is called on a Tabl
eName object, for example, a Table is returned. When it is called on a FeatureDa
tasetName, a FeatureDataset is returned, and so on. Because all COM objects inhe
rit the generic interface IUnknown, the diagram lists this as the return type. A
s a programmer, you would know what is actually being returned, of course, becau
se you would know what type of Name object you were opening.
Introduction to Programming ArcObjects with VBA
Data creation
9-14
Creating a new Workspace
Use IWorkspaceFactory to get a WorkspaceName
Create method
Use IName to get a Workspace
Open method
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
9-15
Using the Create method New Workspaces, as you may have guessed, are created fro
m a WorkspaceFactory. The IWorkspaceFactory interface, which is supported by the
creatable (coclass) subtypes of the WorkspaceFactory class, uses the Create met
hod not to produce new Workspaces, but to produce new WorkspaceName objects. Wor
kspaceName objects, as described on the previous slide, are simply lightweight v
ersions of a Workspace and not the Workspace itself. In order to instantiate the
actual Workspace object from the WorkspaceName, use the Open method on the INam
e interface, as shown below.
Use Create to return a WorkspaceName. Parameters are 1) the parent folder, 2)
the name, 3) a PropertySet, and 4) an hWnd Dim pWorkName As IWorkspaceName Set p
WorkName = pShapeFileWSFactory.Create ("C:\Data", "MyFiles", Nothing, 0) Dim pNa
me As IName Set pName = pWorkName interface QueryInterface to get the IName
Dim pShapeWSpace As IWorkspace Set pShapeWSpace = pName.Open object Open on an
y Name returns the
Introduction to Programming ArcObjects with VBA
Data creation
9-15
PropertySet A PropertySet is a collection of name–value pairs. PropertySets supp
ort methods to find properties by name. Property Values are represented as Varia
nts. This allows a Property Value to hold either a common type, such as a string
or a number or a COM object. PropertySets are used to represent the metadata av
ailable for any dataset. PropertySets can also be used to represent the set of p
roperties for an individual feature in the database. For example, a PropertySet
used to store connection information for an ArcSDE Workspace may contain usernam
e, instance, and password properties. If you do not require a PropertySet to ope
n or create a Workspace, you can use the Nothing keyword (as in the example abov
e) to ignore this parameter.
Introduction to Programming ArcObjects with VBA
Data creation
9-16
Creating a new Table or FeatureClass
Use IFeatureWorkspace interface on Workspace
CreateTable and CreateFeatureClass methods
Requires a Fields collection
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
9-17
Creating a new dataset Once you have referenced a Workspace object (new or exist
ing), you can create new datasets inside the Workspace by using one of the metho
ds on the IFeatureWorkspace interface listed below. CreateFeatureClass CreateFea
tureDataset CreateRelationshipClass CreateTable Remember, the type of data you c
reate is dictated by the type of Workspace object you created or opened. If, for
example, you use the CreateFeatureClass method on a ShapefileWorkspace, you hav
e created a Shapefile. If you called CreateTable on this same Workspace, you wou
ld create a dBASE table (the table format for Shapefiles). CreateTable and Creat
eFeatureClass The CreateTable and CreateFeatureClass methods on IFeatureWorkspac
e are very similar in their syntax. This is not surprising because a FeatureClas
s is simply a table that has coordinate geometry. Both methods require a string
to specify the name of the dataset, UIDs for specifying custom behavior DLLs, a
string for an ArcSDE configuration keyword, and a collection of fields. CreateFe
atureClass has additional parameters related to geometry such as FeatureType and
ShapeFieldName. Before calling the CreateTable or CreateFeatureClass methods, a
programmer would have to produce a collection of fields to satisfy the Fields p
arameter.
Introduction to Programming ArcObjects with VBA
Data creation
9-17
Field and Fields classes
Tables and FeatureClasses have an associated Fields
A Fields is a Collection
A Fields object has Field objects
One or several (1..*)
Creatable
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
9-18
Field and Fields Before creating a new FeatureClass or Table, you need to produc
e a collection of fields for the new dataset. Individual Field objects can be cr
eated with the New keyword (they are coclasses). After creating each Field that
you want in the dataset, you need to add them to a Fields object. Fields is an o
bject that manages a set of individual Field objects. Simply put, it is a collec
tion of Fields. Like the Field class, Fields is a coclass and can therefore also
be created New. The fields of an existing dataset can also be accessed. Tables
and FeatureClasses have a Fields property that returns the dataset’s associated
Fields object. From this Fields object, you can access individual Field objects
according to index position (as with any collection object). Caution Do not use
a dataset’s Fields collection to add a Field to an existing dataset. This method
is only appropriate when creating a new dataset. To add a Field to an existing
Table or FeatureClass, use the AddField method on the dataset itself.
Introduction to Programming ArcObjects with VBA
Data creation
9-18
IField and IFieldEdit
Get field properties with IField
Read-only
Set field properties with IFieldEdit
Write-only
Dim pNameField As IFieldEdit Set pNameField = New Field With pNameField .Name =
"StreetName" .Type = esriFieldTypeString .Length = 16 End With
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
9-19
What a difference an ‘s’ makes Both the Field and Fields classes support interfa
ces for reading properties and another for writing properties. These interfaces
are named IField (IFields) for read-only access and IFieldEdit (IFieldsEdit) for
write-only access. When declaring variables to work with field objects and fiel
d collections, take care to use the proper interface. A common mistake is to ina
dvertently add or forget an ‘s’ when dimensioning one of these variables, which
leaves the programmer working with a collection instead of a single field object
or vice versa. When creating new Field objects or a new Fields collection, you
need to use the editing interfaces. From the IFieldEdit interface, for example,
you can set properties for the new field such as its name, the type of data it w
ill contain, and it length. Likewise, you can only add new Field objects to a Fi
elds collection if you are using the IFieldsEdit interface. The OID field The OI
D field is an internal identification field and is basically a record number (ob
ject identifier). The values stored by the OID field are integers that uniquely
identify each record (starting from one and incrementing from top to bottom). Th
ese values are managed internally and do not need to be explicitly set by the us
er. When creating a table with code, make sure to create an OID field for your d
ataset (also make sure to define only one Field as type OID).
Introduction to Programming ArcObjects with VBA
Data creation
9-19
Creating a Fields collection
Use the IFieldsEdit interface
AddField method: Puts a field in the collection
Dim pFieldsEdit As IFieldsEdit Set pFieldsEdit = New Fields pFieldsEdit.AddField
pOIDField pFieldsEdit.AddField pNameField pFieldsEdit.AddField pSalesField
Field = Fields !
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
9-20
Fields collection Fields is a coclass and can be created New in your code. Once
a new Fields collection has been created, use the AddField method on the IFields
Edit interface to put each Field you have defined into the collection. Each Fiel
d that you add will be added to the Fields collection. Later on you will use the
Fields collection to add it to a Table or Feature Class. A Fields collection sh
ould contain one (and exactly one) OID field. This field will be managed by the
software and will basically store a record number. If you attempt to create a Ta
ble without an OID field, you will receive an error. IFieldsEdit methods AddFiel
d DeleteAllFields DeleteField (index) Adds a field to the collection. This is a
hidden method by default. Deletes all fields from the collection. Deletes a fiel
d at the position specified by the index (integer).
Introduction to Programming ArcObjects with VBA
Data creation
9-20
Creating a Table or FeatureClass
Use IFeatureWorkspace interface on Workspace
CreateTable and CreateFeatureClass methods
Dim pTable As ITable Set pTable = pFeatureWorkspace.CreateTable _ ("Store55", pF
ieldsEdit, Nothing, Nothing, "") Table Name Table Name CLSID and EXTCLSID CLSID
and EXTCLSID (Custom Behavior DLLs) (Custom Behavior DLLs) Fields Collection Fie
lds Collection CreateFeatureClass takes additional CreateFeatureClass takes addi
tional FeatureType and ShapeFieldName parameters FeatureType and ShapeFieldName
parameters
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming Arc
Objects with VBA
ArcSDE Configuration ArcSDE Configuration Keyword Keyword
9-21
Once you have created the Field objects required for your Table or FeatureClass
and placed them into a Fields collection, you can use the CreateTable or CreateF
eatureClass method on a Workspace object’s IFeatureWorkspace interface. The synt
ax for the CreateTable method is:
Set aTable = aWorkspace.CreateTable (aTableName, aFieldsCollection,_ aClassID, _
aClassExtensionID, aConfigKeyword)
aTable: aTableName:
A variable declared as an ITable object. The name of the table as it will appear
on disk (e.g., Streets.dbf). A string. A GUID that identifies a DLL used to def
ine custom behavior for the table. A UID object.
aFieldsCollection: The fields to appear in the table. A Fields object. aClassID:
aClassExtensionID: A GUID that identifies a ClassExtension DLL for the table. An
UID object. aConfigKeyword: Storage parameters for an ArcSDE server. A string.
Notice that the Nothing keyword can be used to ignore certain parameters that re
quire an object. The final parameter, the ArcSDE configuration keyword, requires
a string. In order to ignore this parameter, a programmer must provide an empty
string (“”) and not the Nothing keyword. In this example, a Fields collection m
ust be provided; a programmer could not ignore this parameter.
Introduction to Programming ArcObjects with VBA
Data creation
9-21
Additional parameters for creating a FeatureClass Because a FeatureClass stores
coordinate geometry, there are additional FeatureType and ShapeFieldName paramet
ers required for the CreateFeatureClass method. FeatureType: satisfied with a co
nstant (esriFeatureType) such as esriFTSimple, esriFTComplexEdge, and esriFTAnno
tation ShapeFieldName: a string that identifies the field in the Fields collecti
on that will store coordinate geometry
Introduction to Programming ArcObjects with VBA
Data creation
9-22
Work with fields in a table
IFields interface
FieldCount returns the total number of fields FindField (also on ITable) returns
a field’s index number Field returns a field given the index number
For intLoop = 1 To pFClass.Fields.FieldCount – 1 MsgBox pFClass.Fields.Field(int
Loop).Name Next intLoop intFieldNum = pTable.Fields.FindField("Area") If intFiel
dNum > -1 Then -1 means the field was not found Set pAreaField = pTable.Fields.
Field(intFieldNum) End If
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming Arc
Objects with VBA
9-23
Working with fields In addition to creating a collection of fields for creating
a new dataset, the Fields collection can be returned from any existing Table or
FeatureClass as well. Once a reference to the Fields collection is made, a progr
ammer can use the IFields interface to work with individual Field objects. Membe
rs on Ifields FieldCount: returns the total number of field objects in the colle
ction. The FieldCount may be important for building a looping routine to access
each field in the collection, for example. FindField: does not return a Field fr
om the collection. Instead, it returns the index position of the specified Field
object in the collection. Index position in the collection is the same as it ap
pears in the table itself, with 0 being the field on the far left of the table,
increasing from left to right. If the specified field is not located, the value
–1 is returned. Field: use this property to return a Field object from the Field
s collection. The Field property requires an index number in order to access a F
ield. Use the FindField method described above to first locate the Field’s posit
ion, then use the Field property to get the Field itself. You can also chain cod
e together to access a Field from the collection, as shown below.
pIncomeField = pTable.Fields.Field(pTable.FindField ("Income") )
Introduction to Programming ArcObjects with VBA
Data creation
9-23
Adding rows and values to a table
CreateRow on ITable returns a Row
CreateFeature on IFeatureClass returns a Feature
Value property
Get or set cell values Specify the field index
Dim pRow As IRow Set pRow = pTable.CreateRow pRow.Value(1) = "Jesse White" pRow.
Store
Row
Table
Feature
FeatureClass
Name
pRow.Value(pTable.FindField("Age")) = 35 Age
Store commits the new row Store commits the new row Feature has a Shape property
to store geometry Feature has a Shape property to store geometry
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
9-24
Adding Rows to a Table If you look at the simplified object model diagram above,
you will notice that Row is a Class, which means it must be instantiated from a
nother object (and not with the New keyword). Also shown by the diagram above is
the fact that a Table object can instantiate a Row (dashed arrow means creates
a). As a programmer working with Tables and Rows, this makes perfect sense. Crea
ting a Row with the New keyword would mean that the Row would exist outside the
context of a Table. By having the Table create the Row, you are assured that the
Row is created inside a Table and that it has all the fields that are defined i
n that Table. Calling the CreateRow method on ITable opens an empty record in th
e parent table. Obviously, it is important to store the Row that is returned by
the CreateRow method in a variable so it can be referenced later in your code. T
he IRow interface on the Row class has a Value property. This property is read–w
rite, which means you can both access values from an existing Row and provide ne
w values for a new (or existing) Row. To use the Value property, you need to spe
cify the index position of a Field you want to provide a value for. Once all val
ues have been written to a Row, make sure to use the Store method to commit the
new Row to the Table. If you do not use Store, your Row will not actually be add
ed to the Table.
Introduction to Programming ArcObjects with VBA
Data creation
9-24
Features in a FeatureClass Just as a Table object contains Rows, a FeatureClass
contains Features. Features are like Rows in that they are simply records in a d
ataset. They differ, however, in the fact that they store geometry. The methods
for assigning values (attributes) described above also apply to Features in a Fe
atureClass, with the exception of setting the geometry. You can directly access
geometry for a Feature by using the Shape property defined on the IFeature inter
face. As with Rows, make sure to use Store to commit the Feature to the FeatureC
lass. Below is an example of storing a new Feature.
Dim pFeature As Ifeature Set pFeature = pFeatureClass.CreateFeature Set pFeature
.Shape = pPolygon pFeature.Value(3) = "Hyrum" pFeature.Value(pFeature.FindField(
PropertyValue)) = 160000 pFeature.Value(pFeatureClass.FindField("Owner")) = "Chu
ck and Joslin Werstak" pFeature.Store
Introduction to Programming ArcObjects with VBA
Data creation
9-25
Exercise 9B overview
Make a new personal geodatabase (workspace) Create a new table
Add records Edit values
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
9-26
Exercise 9 overview In this exercise, you will write code to: Add a shapefile la
yer to a map. Create a new personal geodatabase on disk. Make a Fields collectio
n. Create a new table inside your geodatabase by using the Fields collection. Ad
d records (Rows) to the table and add new information.
Introduction to Programming ArcObjects with VBA
Data creation
9-26
Introduction to Programming ArcObjects with VBA
Geometry and geoprocessing
Lesson overview Geometry objects Feature geometry Points and multipoints Segment
s Polylines and polygons Envelopes Zooming in to a Feature Displaying features G
eometry spatial operator interfaces ITopologicalOperator IRelationalOperator IPr
oximityOperator Area and length Spatial reference Spatial reference OMD Exercise
10 overview
10-11 10-12 10-13 10-14 10-15 10-16 10-17 10-18
contents
10-2 10-3 10-4 10-5 10-6 10-7 10-8 10-9 10-10
Geometry and geoprocessing
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
Introduction to Programming ArcObjects with VBA
Working with geometry
10-1
Lesson overview
Geometry 101 Operators: Working with feature geometry Drawing geometry Geoproces
sing
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
10-2
Overview Types of ArcMap geometry objects Creating new geometry with code Measur
ing proximity Examining spatial relationships Displaying features
Introduction to Programming ArcObjects with VBA
Working with geometry
10-2
Geometry objects
Geometry *
Geometry collection
Curve
Envelope
Point
*
MultiPoint
Polycurve
Segment *
Path
*
Polyline
Polygon
Line
CircularArc
BezierCurve
Ring
*
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
10-3
Geometry object model diagram The last slide showed how certain types of geometr
y can be built by aggregating other types of geometry. For example, segments can
be produced from points and paths can be produced from segments. This is illust
rated in the object model diagram by the fact that the IGeometryCollection inter
face is supported by the Polycurve class (inherited by Polygon and Polyline). A
GeometryCollection object is a set of geometries of the same type. It may be a c
ollection of paths that describe a line, a collection of segments that describe
a path, or even a collection of points that describe a polygon. Notice that the
Path class has an ISegmentCollection and an IPointCollection interface (inherite
d by Ring); therefore, there is no hierarchy for building geometry. You do not h
ave to aggregate points to segments, segments to paths, and paths to rings in or
der to make a Polygon feature. All geometry has an envelope. An envelope is the
minimum bounding rectangle that surrounds a piece of geometry. As the name impli
es, it is a rectangular geometry with properties such as LowerLeft, UpperRight,
Width, and Height. True to the object model, even though points do not have area
, they do have an (empty) envelope. Being a type of geometry, even envelopes hav
e an Envelope property. Does an envelope’s envelope have an envelope?
Introduction to Programming ArcObjects with VBA
Working with geometry
10-3
Feature geometry
Points Multipoints Polylines Polygons
1 Line
1 Poly
Segments have start and end with curve in between Aggregate to paths/rings Aggre
gate to lines/polygons Edit at any level
Bezier curve Line Segments
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming Arc
Objects with VBA
2 Paths
3 Rings (closed paths)
Circular arc
10-4
ArcMap geometry When storing geometry in a geodatabase, you have the potential t
o create multipart features. This means a single feature (one record in the Feat
ure Class table) can store the coordinates for several spatially distinct geomet
ries. Aggregation of geometry The point is at the root of all geometry. A point
is a single pair of x- and y-coordinates that can be used to build other kinds o
f geometry such as lines or polygons. Although the above geodatabase geometry il
lustration is accurate (points can aggregate to form segments, segments to form
paths, etc.), notice that any geometry can be produced directly from a collectio
n of points.
Introduction to Programming ArcObjects with VBA
Working with geometry
10-4
Points and multipoints
Points are zero dimensional
Defined with x- and y-coordinates May have Z and M properties
Multipoints are collections of points
Dim pPoint As IPoint Point Set pPoint = New Point pPoint.X = 300 pPoint.Y = 450
Multipoint with six points
Dim pMultiPts As IPointCollection Set pMultiPts = New MultiPoint pMultiPts.AddPo
int pPoint
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
10-5
Points are the most basic type of geometry. They are zero-dimensional and compos
ed of a single pair of x- and y-coordinates. Using the IGeometryCollection or IP
ointCollection interface, geometry of any type may be built with a collection of
points. A Multipoint feature is a single feature that stores the coordinates fo
r several points. Several locations for a single fast food chain, for example, c
ould be represented with a Multipoint feature.
Introduction to Programming ArcObjects with VBA
Working with geometry
10-5
Segments
Consist of two points (From and To) and a function defining the curve between th
em
From To To From
Subclasses: Line, BezierCurve, CircularArc Segments used to create other geometr
y
Paths, polylines, rings, and polygons
Dim pLine As ILine Set pLine = New Line pSegment.FromPoint = pPointA pSegment.To
Point = pPointB
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
10-6
Segments, lines, and curves The Segment class is an abstract class, meaning the
programmer cannot create a Segment object with the New keyword. Instead, specifi
c types of segments may be created including Lines, CircularArcs, EllipticArcs,
and BezierCurves. Segment is a subclass of another abstract class called Curve.
All of the above-mentioned classes inherit some of their most basic properties a
nd methods from the Curve class. For example, FromPoint and ToPoint define the s
tart and end for any type of curve. ISegmentCollection More complex geometry, su
ch as paths, rings, polylines, and polygons, may be built by first aggregating s
egments. The Path and Ring classes directly support the ISegmentCollection inter
face, while Polyline and Polygon support the more generic IGeometryCollection in
terface. ISegmentCollection has methods such as AddSegment, RemoveSegment, AddSe
gmentCollection, and SegmentCount. ICircularArc ICircularArc has more than 30 me
thods. Examine the ArcGIS Developer Help for more information.
Dim pArc AS ICircularArc Set pArc = New CircularArc pArc.ConstructThreePoints pP
oint1, pPoint2, pPoint3
Introduction to Programming ArcObjects with VBA
Working with geometry
10-6
Polylines and polygons
Polylines
Collections of connected or unconnected paths
Polygons
Composed of one or several rings
1 Polyline with four segments
1 Polygon with seven rings
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
10-7
Example: Building a ring from a Segment collection, making a polygon from a ring
Dim pSegColl As ISegmentCollection Dim pSegColl As ISegmentCollection Set pSegCo
ll = New Ring pSegmentA and pSegmentB are Lines built earlier pSegColl.AddSegme
nt pSegmentA pSegColl.AddSegment pSegmentB Dim pRing As IRing Set pRing = pSegCo
ll pRing.Close Dim pPolygon As IGeometryCollection Set pPolygon = New Polygon pP
olygon.AddGeometry pRing QueryInterface
Introduction to Programming ArcObjects with VBA
Working with geometry
10-7
Envelopes
Define a feature’s spatial extent
Minimum bounding rectangle
All geometry has an envelope
Get or set with IGeometry :: Envelope
Dim pEnvelope As IEnvelope Set pEnvelope = pLine.Envelope
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
10-8
Envelope Envelopes are a rectangular geometry. Every geometry has an envelope, w
hich can be described as the feature’s minimum bounding rectangle, or extent. Th
e Envelope property is defined in the IGeometry interface and can be used to ret
rieve (but not set) any geometry’s envelope. The Envelope class is a CoClass. Th
is means a programmer may create an envelope object using the New keyword. Examp
le: Setting the extent of the active view to a feature’s envelope
ActiveView’s Extent property is set with an Envelope Get the Envelope from a f
eature’s shape, use it to set map’s extent pMxDoc.ActiveView.Extent = pFeature.S
hape.Envelope
Introduction to Programming ArcObjects with VBA
Working with geometry
10-8
Zooming in to a Feature
Get the extent using a shape’s Envelope property
On the IGeometry interface Set the ActiveView Extent property with an Envelope
pMxDoc.ActiveView.Extent = pFeature.Shape.Envelope pMxDoc.ActiveView.Extent = pF
eature.Shape.Envelope pMxDoc.ActiveView.Refresh pMxDoc.ActiveView.Refresh
Feature
Geometry
Envelope 1 Polygon Feature
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
10-9
Getting geometry A Feature’s Shape property returns feature geometry. The Envelo
pe property returns the minimum bounding rectangle for a shape (Envelope is a pr
operty defined on IGeometry and is therefore supported on all types of geometry)
. You can use the Envelope (rectangle) to set the ArcMap view extent, thereby zo
oming in on the bounding rectangle of the feature. Example: Zooming into each Fe
ature in a FeatureCursor
Public Sub ZoomToRoads () Dim pQFilter As IQueryFilter Set pQFilter = New QueryF
ilter pQFilter.WhereClause = "LENGTH > 100000" Dim pFCursor As IFeatureCursor Se
t pFCursor = pFClass.Search(pQFilter, False) All roads longer than 100000 mete
rs are placed in the FeatureCursor Dim pFeature As IFeature Dim Counter As Integ
er Set pFeature = pFCursor.NextFeature Get the first feature Do Until pFeature
Is Nothing Counter = Counter + 1 pMxDoc.ActiveView.Extent = pFeature.Shape.Enve
lope Get the shape and zoom in pMxDoc.ActiveView.Refresh Refresh after each
zoom Set pFeature = pFCursor.NextFeature Keep pulling out features Loop MsgBox
"There are " & Counter & " roads longer than 100 km" End Sub
Introduction to Programming ArcObjects with VBA Working with geometry 10-9
Displaying features
Several Draw methods on IScreenDisplay interface
StartDrawing: Prepare display for drawing DrawPoint, DrawMultipoint, DrawPolylin
e, DrawPolygon FinishDrawing: Flush caches to screen
Quick draw of geometry and symbol
Dim pDisplay As IScreenDisplay Set pDisplay = pMxApplication.Display pDisplay.St
artDrawing pDisplay.HDC, esriNoScreenCache pDisplay.SetSymbol pSym pDisplay.Draw
Polygon pPolygon pDisplay.FinishDrawing
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
10-10
To draw geometry, use the IScreenDisplay interface of the MxApplication’s Displa
y object. Use one of the geometry drawing methods between StartDrawing and Finis
hDrawing statements. You will learn more about display and saving graphics later
. For now, the Start and Finish drawing methods draw geometry to the display are
a, but the geometry is not saved. This means when you refresh the display, the g
eometry and its symbol will not be there. Use this quick draw when you do not wa
nt to save the graphics. ScreenCache options • esriNoScreenCache • esriAllScreen
Caches • esriScreenRecording
Introduction to Programming ArcObjects with VBA
Working with geometry 10-10
Geometry spatial operator interfaces
Interfaces supported by subtypes of Geometry
ITopologicalOperator IProximityOperator IRelationalOperator
Use to …
Perform familiar spatial operations such as buffer, cut, and clip Measure distan
ces between shapes Examine spatial relationships
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
10-11
Several interfaces are provided by ArcMap for working with feature geometry. The
se interfaces allow you to do things such as: Measure distances between features
. Evaluate spatial relationships. Produce new geometry based on spatial relation
ships of existing features. Query features based on spatial criteria.
Introduction to Programming ArcObjects with VBA
Working with geometry 10-11
ITopologicalOperator
Provides methods for working with geometry Supported by Point, Multipoint, Polyl
ine, and Polygon
Intersect Buffer Union
Cut Dim pTopoOp As ITopologicalOperator Dim pBuffPoly As IPolygon Set pTopoOp =
pFeature.Shape
Clip
Set pBuffPoly = pTopoOp.Buffer (intBufferDistance)
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming Arc
Objects with VBA
10-12
ITopologicalOperator interface Coming from an ArcInfo background, you may think
of operations such as Buffer, Clip, and Intersect as functions you would call in
your Visual Basic code. Perhaps the features on which you are operating would b
e the arguments passed to the function, much like command line ArcInfo. This is
not the case. Instead, the programmer working with ArcInfo geometry objects asks
the geometry object to perform operations on itself. The ITopologicalOperator i
nterface is supported by the Point, Multipoint, Polyline, and Polygon geometry c
lasses. When you are working with one of these objects, you can QueryInterface t
he ITopologicalOperator interface and then call the appropriate method. Be aware
that these operators are working on individual geometries, not entire datasets.
Also realize that most methods return geometry and require additional geometry
as parameters. (Buffer, for example, returns a Polygon object.) Some of the most
common topological operations are listed above. Check your object model diagram
for a full list of properties and methods supported by ITopologicalOperator.
Introduction to Programming ArcObjects with VBA
Working with geometry 10-12
IRelationalOperator
Methods for examining spatial relationships (return Boolean)
Equals: Are input geometries structurally equivalent? Touches: Do input geometry
boundaries intersect? Contains: Is one geometry contained by the other? Disjoin
t: Are input geometries spatially distinct? Several others
Dim pRelationOp As IRelationalOperator Dim booTouches As Boolean Set pRelationOp
= pPoly booTouches = pRelationOp.Touches (pAnotherPoly)
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
10-13
IRelationalOperator interface IRelationalOperator is supported by the Envelope c
lass as well as the classes that support the ITopologicalOperator interface (i.e
., Point, Multipoint, Polyline, and Polygon classes). Working with the IRelation
alOperator interface lets the programmer ask questions about a geometry’s spatia
l relationship to other geometry. Some of the relationships the programmer can c
heck for are listed above; check your object model diagram for all supported met
hods. All methods on this interface require another piece of geometry as an argu
ment. The resulting answer will always be a Boolean object (true or false). Beca
use the IRelationalOperator interface is supported by the Envelope class, the pr
ogrammer can check the spatial relationships between the envelopes (extents) of
two features.
Introduction to Programming ArcObjects with VBA
Working with geometry 10-13
IProximityOperator
Methods for examining proximity relationships between features
ReturnDistance: Returns the minimum distance between features (double) ReturnNea
restPoint: Finds and returns the nearest point on the specified feature (point)
Dim pProxOp As IProximityOperator Dim dblDistance As Double Set pProxOp = pLine
dblDistance = pProxOp.ReturnDistance (pSomeOtherLine)
?
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
10-14
IProximityOperator interface Unlike the ITopologicalOperator and IRelationalOper
ator interfaces, IProximityOperator is supported by all ArcInfo geometry classes
. This interface only has a handful of methods, and each one asks proximity ques
tions of geometry. Using IProximityOperator, the programmer can measure distance
between geometries or locate the nearest point on one geometry relative to anot
her.
Introduction to Programming ArcObjects with VBA
Working with geometry 10-14
Area and length
Each feature is a type of Geometry QueryInterface to Curve (Line features) or Po
lygon
Dim pArea As IArea Set pArea = pPoly ‘QI Msgbox pArea.Area
Polygon
IPolygon IArea
IPolygon: IPolycurve ExteriorRingCount: Long InteriorRingCount(exteriorRing: IRo
ng): Long Close FindExteriorRing(interiorRing: IRing): IRing QueryExteriorRings(
ExteriorRings: IRing) QueryInteriorRings(exteriorRings: IRing, interiorRings: IR
ing) SimplifyPreserveFromTo
Curve
ICurve
ICurve: IGeometry FromPoint: IPoint IsClosed: Boolean Length: Double ToPont: IPo
int
Dim pCurve As ICurve Set pCurve = pLine ‘QI Msgbox pCurve.Length
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
10-15
Area and length can be obtained easily from the Geometry OMD. The Curve class is
an Abstract class that allows you to work with all types of Segments (Lines) an
d polygons. You can work with the ICurve interface by performing a queryinterfac
e to an existing piece of geometry. You then will have access to the length. IAr
ea is an interface that allows you to work with the area of polygons. Like ICurv
e, you must first queryinterface to an existing polygon to use the area property
. Another useful property found on IArea is the centroid, which returns a pointe
r to IPoint, the center of gravity of the polygon. Both the area and length retu
rn units are the units that the data is stored in. In order to obtain different
units, you must either multiply it by a constant or apply a different projection
to the piece of geometry.
Introduction to Programming ArcObjects with VBA
Working with geometry 10-15
Spatial reference
All geometry inherits from IGeometry Use the SpatialReference property to obtain
projection information Use the Spatial Reference OMD for further parameters
Dim pPoint As IPoint Set pPoint = mypoint MsgBox pPoint.SpatialReference.Name
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
10-16
Every piece of geometry has a SpatialReference property, which returns a pointer
to ISpatialReference. ISpatialReference can be found on the Geometry Spatial Re
ference OMD. With the SpatialReference property, you can obtain many of the para
meters associated with the projection assigned to the geometry, or simply the na
me of the projection. Notice that the SpatialReference property is put by refere
nce (hollow box). Thus, if the projection changes for a feature class, it will a
utomatically be changed for all of the associated features.
Introduction to Programming ArcObjects with VBA
Working with geometry 10-16
Spatial reference OMD
All Geometry has a Spatial reference Use ISpatialReferenceFactory to create Proj
ected Coordinate Systems to apply to geometry or feature class
Make your own or choose from one of ESRI predefined projections
ISpatialReference
SpatialReference
Unknown
Geographic CoordinateSystem
Projected CoordinateSystem
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
10-17
Spatial reference continued Geographic data will often times be projected into a
different coordinate system to accommodate the needs of different organizations
. The classes on the Geometry Spatial Reference OMD allow you to reproject your
data programmatically. The previous slide demonstrates how all geometry will hav
e a Spatial Reference Property. The Spatial Reference property will return eithe
r a Geographic Coordinate System, a Projected Coordinate System, or Unknown (a p
rojection was not assigned). If you want to reproject your data, you can use the
ISpatialReferenceFactory to create a projected coordinate system that you want
your data to be reprojected to. The ISpatialReferenceFactory Interface is simila
r to the IWorkspaceFactory Interface used in the last lecture. It is an abstract
class that contains only methods that will return a projection, or a parameter
associated with a projection. Often times you will choose from one of ESRI’s pre
defined projection types to project your data to. If you would like to assign a
projection to an entire feature class, use the IGeoDataset interface on the Feat
ureClass Class to obtain the SpatialReference property.
Introduction to Programming ArcObjects with VBA
Working with geometry 10-17
Exercise 10 overview
Create point features from coordinates Store point features Assign feature attri
butes Create a polygon from a Point collection Challenge: Calculate the area fro
m the polygon you created
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
10-18
Exercise 10: Use coordinate input to draw features In this exercise, you will dr
aw point and polygon geometry and store it as a feature in a Feature Class table
.
Introduction to Programming ArcObjects with VBA
Working with geometry 10-18
Introduction to Programming ArcObjects with VBA ModuleTitle
Working with subsets and selections
Lesson overview 11-2 Object Model overview 11-3 SelectionSet 11-4 Cursors and Fe
atureCursors 11-6 Creating a QueryFilter 11-7 Returning a Search cursor 11-8 Spa
tialFilter 11-10 Three types of cursors 11-12 Accessing records in a cursor 11-1
4 Example: Summarizing a cursor’s attributes 11-15 Review: Features and geometry
11-16 Displaying a subset of features 11-18 Exercise 11 overview 11-19
contents
Working with subsets and selections
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
Introduction to Programming ArcObjects with VBA
Working with subsets and selections
11-1
Lesson overview
Getting the current selection from a table or layer
SelectionSet
Getting a subset of records
Cursor FeatureCursor QueryFilters and SpatialFilters
Three types of cursors: Search, Update, and Insert Looping through cursor record
s Displaying a subset of layer features
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
11-2
Overview There are a variety of ways to work with selections and subsets of reco
rds with ArcObjects. In this lesson, you will learn: How to get an existing sele
ction using the SelectionSet class … from a feature layer … from a table window
How to produce a subset of records using the Cursor and FeatureCursor class … us
ing attribute criteria, spatial criteria, or both … for analysis … for updating
a dataset How to process the records in a Cursor using a Do While loop How to di
splay a subset of features in a feature layer
Introduction to Programming ArcObjects with VBA
Working with subsets and selections
11-2
Object Model overview
SelectionSet Row Cursor Table
QueryFilter
SpatialFilter Feature FeatureCursor FeatureClass = ‘in conjunction with’ = ‘in c
onjunction with’
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
11-3
Object model diagram You will find the objects discussed in this lesson on the G
eodatabase object model diagram. Notice that, with one exception, all of the cla
sses shown above are Classes and must be instantiated from another class. The on
ly CoClasses shown above are QueryFilter and its subtype SpatialFilter. These ar
e the only ones that can be created with the New keyword. The diamond symbol sho
wn above may be new to you. This symbol indicates that an object is created (das
hed arrow) by two classes working together. Therefore, according to the diagram
above, a Table working in conjunction with a QueryFilter can create a Cursor or
a SelectionSet object. Likewise, a FeatureCursor (which is a type of Cursor) is
also created from a FeatureClass (a type of Table) and a QueryFilter. Remember t
hat the dashed arrow symbol indicates a creates a relationship. A Row object can
be created from a Table or from a Cursor object. A Feature (which is a type of
Row) can be created either from a FeatureClass (type of Table) or FeatureCursor
(type of Cursor).
Introduction to Programming ArcObjects with VBA
Working with subsets and selections
11-3
SelectionSet
Get the currently selected records (Rows or Features)
IFeatureSelection :: SelectionSet (FeatureLayer) ITableWindow :: SelectionSet (T
ableWindow)
Public Sub GetLayerSelection() Dim pMxDoc As IMxDocument Dim pFSel As IFeatureSe
lection Dim pSelSet As ISelectionSet Set pMxDoc = ThisDocument Set pFSel = pMxDo
c.SelectedLayer QueryInterface Set pSelSet = pFSel.SelectionSet MsgBox pSelSet.
Count & " selected features" End Sub
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming Arc
Objects with VBA
11-4
SelectionSet class Use the SelectionSet class to get the current selection from
a Table or FeatureClass object. Although you can get a SelectionSet object from
a Table or FeatureClass object using the Select method, it is perhaps more commo
n for an ArcObjects programmer to get the selection directly from the FeatureLay
er or TableWindow in which the user is working. The example above shows the easi
est way to get the selection from a FeatureLayer in a map. The FeatureLayer clas
s supports the IFeatureSelection interface, which allows you to get at selected
features by using the SelectionSet property. By dimensioning a variable as the I
FeatureSelection interface, you can QueryInterface from a FeatureLayer (the exam
ple simply assumes that the selected layer is a FeatureLayer), then retrieve the
SelectionSet. As a final step above, the example reports the number of selected
features in a message box. If you wanted to access each individual feature in t
he SelectionSet, you would need to write more code to place the features into a
FeatureCursor, which is described on the following slide.
Introduction to Programming ArcObjects with VBA
Working with subsets and selections
11-4
Getting the SelectionSet from a Table A TableWindow object allows you to retriev
e selected rows. Use the SelectionSet property on ITableWindow to get a Selectio
nSet object as shown below.
Public Sub GetTableSelection() Dim pMxDoc As IMxDocument Set pMxDoc = ThisDocume
nt Use the ITableCollection interface on the Map to get at all tables in the cu
rrent data frame Dim pTableCollection As ITableCollection Set pTableCollection =
pMxDoc.FocusMap If pTableCollection.TableCount < 1 Then MsgBox "There are no ta
bles in the active data frame", vbExclamation Exit Sub End If Get the first tab
le from the collection Dim pTable As ITable Set pTable = pTableCollection.Table(
0) Dim pTabWin As ITableWindow Dim pOldWin As ITableWindow Set pTabWin = New Tab
leWindow Check to see if the table window is already open Set pOldWin = pTabWin
.FindViaTable(pTable, False) If Not pOldWin Is Nothing Then Set pTabWin = pOldWi
n Else Set pTabWin.Table = pTable Set pTabWin.Application = Application Allow o
ne selected row pTabWin.TableSelectionAction = esriSelectCurrentRow pTabWin.Show
True End If Get the SelectionSet Dim pSelSet As ISelectionSet Set pSelSet = pT
abWin.SelectionSet Use the SelectionSet property on ITableWin to get the selec
ted records Show the count of selected records in a message box MsgBox "The tab
le has " & pSelSet.Count & " selected records" End Sub
Introduction to Programming ArcObjects with VBA
Working with subsets and selections
11-5
Cursors and FeatureCursors
Manages a subset of records as a single object Not visible to the user (e.g., se
lection)
A Fields property for accessing attributes A Fields property for accessing attri
butes •• Same fields and order as the parent table Same fields and order as the
parent table Methods for working with records Methods for working with records (
rows or features) (rows or features)
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
11-6
Cursor objects (and their subtype, FeatureCursor) give you the ability to manage
a set of records (rows or features) in a single object. The subset of records i
n a Cursor can be defined using spatial criteria, attribute criteria, or both. O
nce a Cursor is produced, you will have a convenient mechanism for looping throu
gh the set of records. Cursor objects have a Fields property that allows you to
access all the same attribute fields that are in the parent Table or FeatureClas
s from which the Cursor was derived. These fields are in the same order in the C
ursor as they are in the parent Table, and once you access the Fields collection
, you can indicate a particular field by using its index position. Cursor object
s have several methods for working with their content rows or features. Dependin
g on the type of Cursor you work with (the three types of Cursors will be covere
d later), you will have methods for inserting, deleting, updating, or simply acc
essing records. Keep in mind that a Cursor is not the same as a selection. When
you produce a Cursor as a programmer, you are not displaying these records as a
selection to the user; you are simply pulling out a subset of records to work wi
th in your application. If you want to display these records as a visible select
ion in the user’s table or map, you need to work with the SelectionSet class.
Introduction to Programming ArcObjects with VBA
Working with subsets and selections
11-6
Creating a QueryFilter
Create a QueryFilter with the New keyword Set the WhereClause property (string)
Dim pQFilter As IQueryFilter Dim pQFilter As IQueryFilter Set pQFilter = New Que
ryFilter Set pQFilter = New QueryFilter pQFilter.WhereClause = "LENGTH > 100000"
pQFilter.WhereClause = "LENGTH > 100000" QueryFilter QueryFilter
WhereClause WhereClause
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
11-7
QueryFilter, and its subclass SpatialFilter, are CoCreatable. In other words, th
ey can be created with the New keyword. Before producing a Cursor or FeatureCurs
or from a dataset (Table or FeatureClass), you need to have a QueryFilter or Spa
tialFilter to define your selection criteria. A QueryFilter object has a WhereCl
ause property, which is simply an expression that defines an attribute query. A
SpatialFilter also defines the criteria for producing a Cursor but instead uses
geometry and spatial relationships for making a subset of records. SpatialFilter
s are discussed in more detail on a later slide. SQL syntax The SQL syntax of yo
ur QueryFilter’s WhereClause expression should use the format of the data you ar
e querying. For example, INFO, SQL, BASE, Oracle, and Access databases use sligh
tly different query syntax. The expression that appears between the quotes gets
passed on to the database being queried. SQL for Access (personal geodatabase) H
ere is an example of an expression that will select all U.S. states that contain
the letter p from an Access personal geodatabase FeatureClass (or Table):
pQFilter.WhereClause = "STATE_NAME like ‘*p*’"
SQL for Shapefiles The same query above on a Shapefile (or BASE Table) would be
case sensitive and look like the following: pQFilter.WhereClause = "STATE_NAME l
ike ’%p%‘ or STATE_NAME like ’%P%‘ " SQL for Coverages The same query above on a
n ArcInfo coverage (or INFO Table) would look like the following:
pQFilter.WhereClause = "STATE_NAME like ’%p% "
Introduction to Programming ArcObjects with VBA
Working with subsets and selections
11-7
Returning a Search cursor
Apply to a Table or FeatureClass
Search method Returns a Cursor or FeatureCursor
Dim pFCursor As IFeatureCursor Dim pFCursor As IFeatureCursor Set pFCursor = pFC
lass.Search(pQFilter, True) Set pFCursor = pFClass.Search(pQFilter, True) What
do you think this code does? What do you think this code does? Set pFCursor = p
FClass.Search(Nothing, True) Set pFCursor = pFClass.Search(Nothing, True)
QueryFilter FeatureClass
Search
FeatureCursor
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
11-8
Using a QueryFilter to return a Search cursor After creating a QueryFilter (or a
SpatialFilter, discussed on the following slide) to define the criteria to prod
uce a Cursor, you can use the Search method on ITable (Table) or on IFeatureClas
s (FeatureClass) to produce a Cursor or FeatureCursor, respectively. Notice that
the Search method has two arguments: the first is the QueryFilter, and the seco
nd is a Boolean that describes how memory should be managed by the Cursor (descr
ibed in more detail below). There are three kinds of Cursors that may be produce
d from a Table or FeatureClass. Each type of Cursor is used for a different purp
ose and is defined by the method used to create it. The example above creates a
Search Cursor by using the Search method on IFeatureClass. Search Cursors are us
ed to return a subset of records for some type of read-only purpose such as calc
ulating a statistic or getting a count of records. The two other types of Cursor
s that may be created are Update and Insert and will be discussed shortly. Nothi
ng Remember that the Visual Basic keyword Nothing can sometimes be used to satis
fy an object parameter. In the case of the Search method, you can use Nothing in
place of a QueryFilter object to return all records from a Table or FeatureClas
s and place them in the returned Cursor object. Specifying Nothing is essentiall
y defining no search criteria whatsoever and will have the same effect as using
an expression such as Name = ‘*’.
Introduction to Programming ArcObjects with VBA
Working with subsets and selections
11-8
Recycling The second parameter for the Search method is a Boolean value that spe
cifies whether memory will be recycled for records retrieved from the Cursor. Re
cycling memory means that each record pulled from the Cursor will occupy the sam
e location in memory and results in better performance. If memory is not recycle
d, each record pulled from the Cursor will occupy its own location in memory. Fo
r Cursor used for editing or data loading (Update or Insert Cursors), memory sho
uld not be recycled. Cursors used for read-only operations such as display or si
mple analysis should use memory recycling. A value of True indicates that memory
will be recycled. A value of False means individual memory locations will be al
located.
Introduction to Programming ArcObjects with VBA
Working with subsets and selections
11-9
SpatialFilter
Type of QueryFilter Select features based on a spatial relationship
Dim pSFilter As ISpatialFilter Dim pSFilter As ISpatialFilter Set pSFilter = New
SpatialFilter Set pSFilter = New SpatialFilter Set pSFilter.Geometry = pBufferP
olygon Set pSFilter.Geometry = pBufferPolygon pSFilter.SpatialRel = esriSpatialR
elContains pSFilter.SpatialRel = esriSpatialRelContains Set pFCursor = pCityFCla
ss.Search (pSFilter, True) Set pFCursor = pCityFClass.Search (pSFilter, True) Ge
ometry Property Geometry Property •• Point Point •• Line Line •• Polygon Polygon
SpatialRel Property SpatialRel Property •• Inside Inside •• Contains Contains •
• Intersects Intersects •• Etc … Etc …
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming Arc
Objects with VBA
11-10
The SpatialFilter class is a subclass of QueryFilter. Like QueryFilter, SpatialF
ilter is a coclass and can therefore be created with the New keyword. As the nam
e implies, a SpatialFilter is used to produce a subset of records based on spati
al criteria. Because a SpatialFilter uses spatial relationships (geometry), it i
s only appropriate to use it with a FeatureClass in order to create a FeatureCur
sor. Instead of using a WhereClause property as the QueryFilter does, a SpatialF
ilter uses a Geometry property and a SpatialRel property to define the search cr
iteria. Geometry: After creating a new SpatialFilter, set this property with som
e geometry that will be the basis of the spatial relationship. This property can
be set with any type of geometry (i.e., any class that supports the IGeometry i
nterface). SpatialRel: Use one of the predefined esriSpatialRelEnum constants to
define the type of spatial relationship to be used in the search criteria. Thes
e constants are listed below.
esriSpatialRelContains esriSpatialRelCrosses esriSpatialRelEnvelopeIntersects es
riSpatialRelIndexIntersects esriSpatialRelIntersects esriSpatialRelOverlaps esri
SpatialRelTouches esriSpatialRelUndefined esriSpatialRelWithin
Introduction to Programming ArcObjects with VBA
Working with subsets and selections 11-10
The example The code in the example above will locate all features that are with
in (esriSpatialRelWithin) the specified piece of geometry (pBufferPolygon). Thes
e features will be returned and stored as a subset of records in a FeatureCursor
object (pFCursor). The FeatureCursor created is a Search cursor (created with t
he Search method), so it could not be used for inserting or updating features in
the Cursor. Because the second parameter of the Search method is set to True, e
ach feature in the Cursor will occupy the same location in memory (memory will b
e recycled).
Introduction to Programming ArcObjects with VBA
Working with subsets and selections 11-11
Three types of cursors
Determined by the method used to return the cursor Search cursor
Search method
Dim myCursor As IFeatureCursor Dim myCursor As IFeatureCursor Set myCursor = pFC
lass.Search(pQFilter, True) Set myCursor = pFClass.Search(pQFilter, True)
Use for read-only analysis of a record subset
Update cursor
Update method
Dim myCursor As IFeatureCursor Dim myCursor As IFeatureCursor Set myCursor = pFC
lass.Update(pQFilter, False) Set myCursor = pFClass.Update(pQFilter, False)
Use to update or delete records in the database
Insert cursor
Insert method
Dim myCursor As IFeatureCursor Dim myCursor As IFeatureCursor Set myCursor = pFC
lass.Insert(True) Set myCursor = pFClass.Insert(True)
Use to insert new records into the database
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
11-12
Types of cursors There are three types of cursor objects that can be obtained fr
om a Table or FeatureClass. The type of cursor returned depends solely on the me
thod that was used to create it. As a programmer using one of these cursors, you
need to be mindful of the type of cursor you create and make sure that it is su
ited to your purpose. Each cursor type will have the same available interfaces (
e.g., ICursor, IFeatureCursor), with the same methods and properties available.
Calling some of these methods with the wrong type of cursor, however, will retur
n an error. Search cursor Search cursors have already been described. These curs
ors are created by calling the Search method on a Table or FeatureClass and are
used to carry out operations that do not require write access to the records. Se
arch cursors are generally used for tasks such as calculating a statistic for a
subset of records (e.g., find the average value for commercially zoned lots), ob
taining a count (e.g., the number of records with a value greater than 1,000), o
r for display (e.g., drawing temporary buffers around all vacant lots). Search c
ursors are created with a QueryFilter, giving you the ability to store a subset
of records in the cursor (or all records by using the Nothing keyword). If you c
reate a cursor as a Search cursor, you will not be able to call methods such as
InsertRow, DeleteRow, or UpdateRow (they will be available, but will not work).
The only method you will use on a Search cursor is NextRow (NextFeature) to acce
ss each record in the cursor.
Introduction to Programming ArcObjects with VBA
Working with subsets and selections 11-12
Update cursor Update cursors are created by calling the Update method on a Table
or FeatureClass. An Update cursor is used to update or delete records in the da
tabase from which the cursor was created (Table or FeatureClass). Like Search cu
rsors, Update cursors are created with a QueryFilter object, giving you the abil
ity to store a subset of records in the returned cursor (or all records by using
the Nothing keyword). If you create a cursor as an Update cursor, you should no
t try to call the InsertRow (InsertFeature) method. This method only works on an
Insert cursor. Insert cursor Insert cursors are created by (you guessed it) usi
ng the Insert method on a Table or a FeatureClass. Use an Insert cursor to inser
t new records into the database from which the cursor was created (Rows in a Tab
le or Features in a FeatureClass). Unlike Search and Update cursors, the Insert
method does not take a QueryFilter as a parameter. Insert cursors do not support
the NextRow (NextFeature) method or the Insert and UpdateRow methods.
Introduction to Programming ArcObjects with VBA
Working with subsets and selections 11-13
Accessing records in a cursor
When initialized, Cursors point above the first record NextRow/NextFeature to re
turn records (Row/Feature)
Dim myCursor As ICursor Set myCursor = pTable.Search(pQFilter, False) myCursor i
nitializes here myCursor initializes here Set myRow = myCursor.NextRow Set myRow
= myCursor.NextRow Set myRow = myCursor.NextRow Set myRow = myCursor.NextRow No
thing is returned when all records have been accessed Nothing is returned when a
ll records have been accessed
Cursor Cursor
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
11-14
When a cursor is first instantiated (using the Search or Update methods), a poin
ter is established above the first record. To pull a record out of the cursor, u
se the NextRow method (or NextFeature for a FeatureCursor). This method will mov
e the pointer down to the first record in the cursor and then return the item it
finds there (Row or Feature). Each time this method is called, the pointer move
s down one record in the cursor and returns the Row or Feature it finds. When th
e pointer is at the last record in the cursor and the NextRow method is called,
the Visual Basic Nothing object is returned. It will be important, therefore, to
immediately check each object retrieved from a cursor to make sure it is not No
thing before working with it in your code. As a programmer, there is no need to
explicitly manage the location of the cursor’s pointer; this is handled by the c
ursor object itself. There is also no way to jump to a certain record (e.g., usi
ng an index position) or to go backwards in the cursor. If you want to move back
to the top of the cursor, you cannot use a Reset method (as with an enum). To r
eturn the pointer to its original position (above the first record) the cursor m
ust be re-instantiated (e.g., using the Search method).
Introduction to Programming ArcObjects with VBA
Working with subsets and selections 11-14
Example: Summarizing a cursor’s attributes
Use a Do Until loop Loop until no more features (Nothing) Use IFeatureClass::Fea
tureCount to count features
Dim pFeature As IFeature Dim intLength As Long Set pFeature = pFCursor.NextFeatu
re Do Until pFeature Is Nothing intLength = intLength + pFeature.Value(9) Set pF
eature = pFCursor.NextFeature Loop MsgBox pFClass.FeatureCount(pQFilter) & _ " r
oads longer than 100 km." & _ " The total length is " & intLength
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
11-15
Example: Accessing records in a cursor To access all records inside a cursor, yo
u need to use a Do While or a Do Until loop. Remember that these loops are based
on a condition, rather than on a fixed number of iterations. Before entering th
e loop, the first feature is pulled out of the FeatureCursor (pFCursor.NextFeatu
re) and stored in a variable (pFeature). The loop will then check to see if pFea
ture is Nothing, and until it is, the loop will continue to execute. If, at this
point, your FeatureCursor had no records (i.e., nothing met the search criteria
), the first object retrieved from the cursor would be Nothing, and therefore th
e body of the loop would never be executed. A variable intLength is declared in
the code above to summarize the attribute values for the length field. The field
index is specified by the value property (pFeature.Value(9)). For each record t
hat the cursor finds, intLength is incremented to keep track of all the attribut
es that meet the criteria of the Feature Cursor. After the length is incremented
, it is very important to pull another feature from the cursor by again calling
the NextFeature method. This moves the pointer and returns the next object in th
e cursor, which is again tested to see if it is Nothing. Without this line of co
de, you would have an infinite loop. The IFeatureClass interface has a FeatureCo
unt property that requires a QueryFilter. This will return the total number of f
eatures that meet the criteria set by the QueryFilter.
Introduction to Programming ArcObjects with VBA
Working with subsets and selections 11-15
Review: Features and geometry
Every feature has geometry (shape) All geometry has an envelope
A bounding rectangle Use an Envelope to set the ArcMap extent
Zoom to Qatar … Zoom to Qatar … pQFilter.WhereClause = "Name = ‘Qatar’" pQFilt
er.WhereClause = "Name = ‘Qatar’" Set pFCursor = pFClass.Search (pQFilter, True)
Set pFCursor = pFClass.Search (pQFilter, True) Set pFeature = pFCursor.NextFeat
ure Set pFeature = pFCursor.NextFeature If Not pFeature Is Nothing Then If Not p
Feature Is Nothing Then Dim pEnv As IEnvelope Dim pEnv As IEnvelope Set pEnv = p
Feature.Shape.Envelope Set pEnv = pFeature.Shape.Envelope pMxDoc.ActiveView.Exte
nt = pEnv pMxDoc.ActiveView.Extent = pEnv End If End If
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
11-16
Getting geometry A Feature’s Shape property returns feature geometry. The Envelo
pe property returns the minimum bounding rectangle for a shape (Envelope is a pr
operty defined on IGeometry, and is therefore supported on all types of geometry
). You can use the Envelope (rectangle) to set the ArcMap software’s view extent
, thereby zooming in on the bounding rectangle of the feature.
Introduction to Programming ArcObjects with VBA
Working with subsets and selections 11-16
Example: Zooming into each Feature in a FeatureCursor
Public Sub ZoomToRoads () Dim pQFilter As IQueryFilter Set pQFilter = New QueryF
ilter pQFilter.WhereClause = "LENGTH > 100000" Dim pFCursor As IFeatureCursor Se
t pFCursor = pFClass.Search(pQFilter, False) longer than 100000 meters are plac
ed in the FeatureCursor Dim pFeature As IFeature Dim Counter As Integer Set pFea
ture = pFCursor.NextFeature Do Until pFeature Is Nothing Counter = Counter + 1 p
MxDoc.ActiveView.Extent = pFeature.Shape.Envelope zoom in pMxDoc.ActiveView.Ref
resh Set pFeature = pFCursor.NextFeature Loop MsgBox "There are " & Counter & "
roads longer than 100 km“ End Sub Get the shape and Get the first featur
e All roads
Refresh after each zoom Keep pulling out features
Introduction to Programming ArcObjects with VBA
Working with subsets and selections 11-17
Displaying a subset of features
Use IFeatureLayerDefinition :: DefinitionExpression
Creates temporary subset of features for analysis and display
Public Sub MakeLayerDefinition() Dim pMxDoc As IMxDocument Dim pFDefine As IFeat
ureLayerDefinition Set pMxDoc = ThisDocument Set pFDefine = pMxDoc.SelectedLayer
QueryInterface pFDefine.DefinitionExpression = "Pop > 3000000" pMxDoc.ActiveVi
ew.Refresh Refresh the display End Sub
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
11-18
Displaying a subset of features in a feature layer There may be times when you n
eed to define an attribute expression, not to produce a subset of records in a c
ursor but to restrict the features being displayed in a feature layer in the map
. The easiest way to accomplish this is by using the DefinitionExpression proper
ty on the IFeatureLayerDefinition interface. IFeatureLayerDefinition is an inter
face supported by the FeatureLayer class. By using an attribute expression for a
QueryFilter’s WhereClause, you can define a subset of features to be displayed
in the map (and in the attribute table for the layer). To clear a subset definit
ion and return to viewing the entire set of features, set the definition express
ion equal to an empty string (“”).
The example In the example above, a variable is declared as IFeatureLayerDefinit
ion (pFDefine). This variable is set to the selected layer in the current docume
nt by using the SelectedLayer property of IMxDocument. If there was no selected
layer in the document, or if it were not a feature layer (a TIN, Raster, or CAD
layer, for example), this code would return a type mismatch error. The Definitio
nExpression property on IFeatureLayerDefinition is set to display only those fea
tures that have a value greater than 3,000,000 for the Pop attribute (population
). Finally, the ArcMap active view is refreshed in order to see the result of th
e definition expression.
Introduction to Programming ArcObjects with VBA
Working with subsets and selections 11-18
Exercise 11 overview
Display a subset of layer features
IFeatureLayerDefinition :: DefinitionExpression
Calculate statistics for a subset of features
IQueryFilter :: WhereClause FeatureCursors
Produce a cursor based on attribute and spatial criteria
SpatialFilter SelectionSet
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
11-19
In this exercise, you will work with some of the ArcObjects related to making se
lections and producing subsets of data based on attribute criteria, spatial crit
eria, or both. You will learn how to make a query definition for a feature layer
to easily display a subset of features. Finally, you will produce spatial and a
ttribute queries to report information about a subset of features. Here are some
tasks that you will write code for: • Restrict the display of the world city an
d world country layer according to a population threshold. • Calculate some simp
le statistics for a subset of world countries. • Select cities based on a spatia
l relationship (the country they fall in) and an attribute criterion (population
greater than 3 million). As a challenge step, you will work with an Update curs
or to correct a spelling error in the world countries database.
Introduction to Programming ArcObjects with VBA
Working with subsets and selections 11-19
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
11-20
Introduction to Programming ArcObjects with VBA
Working with subsets and selections 11-20
Introduction to Programming ArcObjects with VBA
Symbolizing elements and layers
Lesson overview 12-2 Subclasses of Symbol 12-3 Using color 12-4 ColorRamps 12-5
Creating simple graphic elements 12-6 Example: Make a new element, set its symbo
l 12-7 Defining an element’s position 12-8 Adding an element to the map (or layo
ut) 12-9 FeatureRenderers 12-11 SimpleRenderer 12-12 UniqueValueRenderer 12-13 C
lassBreaksRenderer 12-14 ScaleDependentRenderer 12-15 Storing layers on disk 12-
16 GxLayer object 12-17 Example: Saving a layer from ArcMap 12-18 Exercise 12 ov
erview 12-19
contents
Symbolizing elements and layers
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
Lesson overview
Overview of symbology objects
Symbol objects Color objects Color ramps
Adding simple graphics to the map Changing layer display with FeatureRenderers M
anaging layer symbology with layer files (*.lyr)
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
12-2
Overview This lesson will introduce you to some of the ArcObjects required to co
ntrol how elements (“graphics”) and layers are displayed on the map. • Symbol—Th
ere are several creatable subtypes of Symbol, including text symbols, line symbo
ls, and fill symbols, for example. • Color—The (abstract) Color class has five c
reatable subtypes, allowing the programmer to define colors in a variety of ways
. • ColorRamp—ArcGIS has four creatable color ramps that a programmer can use to
build a collection of colors. • FeatureRenderer—FeatureRenderers control how da
ta in a feature layer are categorized and symbolized. This section will discuss
some of the more common types of renderers. You will learn how to programmatical
ly create, modify, and add graphic elements to the map or page layout. You will
also learn how to manage layer symbology by saving and retrieving layer files fr
om disk.
Subclasses of Symbol
ISymbol
Symbol *
MarkerSymbol
LineSymbol
FillSymbol
SimpleMarkerSymbol
SimpleLineSymbol
SimpleFillSymbol
CharacterMarkerSymbol
PictureLineSymbol
LineFillSymbol
PictureMarkerSymbol
HashLineSymbol
MarkerFillSymbol
* Several additional types of symbols are listed on the Display OMD, including T
extSymbols
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming Arc
Objects with VBA
12-3
Symbol You will find the Symbol abstract class and all of its subtypes listed on
the Display object model diagram. Any item on the Map or PageLayout must have a
symbol in order to be displayed. ArcMap uses MarkerSymbols, LineSymbols, or Fil
lSymbols to display geometry, and TextSymbols to display text elements. There ar
e also 3DChartSymbols for drawing charts (graphs). The ISymbol interface (suppor
ted by each subtype of Symbol) has methods for drawing a symbol directly to a de
vice context (DC). A device context is basically a window display, such as the A
rcMap display, an ArcCatalog preview pane, or a (standalone Visual Basic) user f
orm. Each symbol subclass has methods and properties a programmer can use to def
ine the symbol, such as Style, Line Width, Font, Size, Angle, and Color. Choose
the appropriate subclass of symbol according to how you would like to define it:
a PictureMarkerSymbol to define a marker from a bitmap or GIF image, a Characte
rMaker to define a marker from a specific font and character, for example. Examp
le: Creating a simple (dashed) line symbol
Dim pSLineSymbol As ISimpleLineSymbol Set pSLineSymbol = New SimpleLineSymbol pS
LineSymbol.Style = esriSLSDash esriSimpleLineStyle
Example: Creating a simple (diagonal-hatched) fill symbol
Dim pSFillSymbol As ISimpleFillSymbol Set pSFillSymbol = New SimpleFillSymbol pS
FillSymbol.Style = esriSFSForwardDiagonal esriSimpleFillStyle
Using color
Five creatable subclasses
RgbColor CmykColor HsvColor HlsColor GrayColor
CmykColor HsvColor RgbColor HlsColor
IColor
Color
Properties for defining color
Red, Green, Blue values (0–255) Grayscale (0=white – 255=black) Cyan, Magenta, Y
ellow, Black
GrayColor
Use a color object to assign a symbol’s color property
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming Arc
Objects with VBA
12-4
Add some color to your code Because the five subclasses of color are coclasses,
they can each be created with the New keyword. As a programmer, you can choose C
olor objects and interfaces according to how you would like to define a particul
ar color. To specify individual values for red, green, and blue for example, you
would use the IRgbColor interface on the RgbColor class. Below are brief descri
ptions of how color is defined for each of the five color interfaces. • IRgbColo
r: Red, green, and blue (0–255) • ICmykColor: Cyan, magenta, yellow, and black (
0–255) • IHsvColor: Hue (0–360), saturation, and value (0–100) • IHlsColor: Hue,
lightness, and saturation (0–100) • IGrayColor: Level 0 (white) to 255 (black)
Visual Basic functions for defining color Visual Basic has some built in ways to
specify color values. One of the most powerful is the RGB function. The RGB fun
ction takes three integer arguments that indicate the amount of red, green, and
blue respectively. Here’s an example of using the RGB function to make a cyan co
lor:
Dim myColor As IRGBColor Set myColor = New RGBColor myColor.RGB = RGB(0,255,255)
*Red,Green,Blue: 0-255
Visual Basic also contains color constants that can be used to define a handful
of basic colors. These constants are: vbBlack, vbBlue, vbCyan, vbGreen, vbMagent
a, vbRed, vbWhite, and vbYellow
ColorRamps
Four subclasses
AlgorithmicColorRamp RandomColorRamp PresetColorRamp MultiPartColorRamp
MultiPartColorRamp RandomColorRamp AlgorithmicColorRamp PresetColorRamp
IColorRamp
ColorRamp
Color ramps can also be referenced from the StyleGallery
Accessing items in the StyleGallery will be covered in Lesson 13
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
12-5
The four subclasses of ColorRamp are coclasses. Therefore, the programmer can cr
eate them with the New keyword. After instantiating a ColorRamp object, the numb
er of colors are specified by setting the Size property; the ramp is then create
d by calling the CreateRamp method. Once the ramp is produced, an enumeration of
the colors can be retrieved from the Ramp object by using the Colors property.
Choose the ramp appropriate for how you need the colors defined. Example: Create
a new random color ramp
Public Function GetRandomRamp (NumColors As Integer) As IEnumColors Dim pRandomC
olorRamp As IColorRamp Set pRandomColorRamp = New RandomColorRamp pRandomColorRa
mp.Size = NumColors Dim blnOK As Boolean pRandomColorRamp.CreateRamp blnOK If No
t blnOK Then Exit Function Set GetRandomRamp = pRandomColorRamp End Function *
Make it so! * Exit if there was an error *Pass back the ramp *Passed into th
e function
Creating simple graphic elements
Several creatable classes Graphic elements
Line, polygon, marker Text and pictures
FrameElement GraphicElement
IElement
Element
Geometry
FrameElements
On the PageLayout Map frames North arrows, legends, scale bars Table frames
TextElement
LineElement
BmpPictureElement
MarkerElement
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
12-6
Elements There are two broad types of element: GraphicElement and FrameElement.
GraphicElements are “dumb” elements that once added to the display, will not cha
nge unless the user does so explicitly. Graphic elements are things like simple
shapes (markers, lines, polygons), text strings, or images (such as a company lo
go). FrameElements, on the other hand, are elements that contain objects, such a
s tables, maps, or map surrounds. Map surrounds are map-related elements added t
o the PageLayout that will dynamically change to reflect changes in an associate
d map. A scalebar, for example, after being added to the layout, will change to
reflect the current map scale as the user zooms in and out on the display. In th
is section, you will learn the basics of working with graphic elements. In a lat
er section, you will learn more about adding frame elements to the page layout.
Example: Make a new element, set its symbol
Dim pMarkerElem As IMarkerElement Set pMarkerElem = New MarkerElement Make a ne
w element
Dim pMarkerSym As ISimpleMarkerSymbol Set pMarkerSym = New SimpleMarkerSymbol M
ake a new symbol pMarkerSym.Style = esriSMSCircle Specify the symbol style Dim
pColor As IRgbColor Set pColor = New RgbColor pColor.RGB = RGB(255,0,0) pMarkerS
ym.Color = pColor pMarkerElem.Symbol = pMarkerSym Make a new color Make it red
(RGB is a VB function) Assign color to the symbol Assign the symbol to the
element
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
12-7
The color’s connected to the … sym-bol. The symbol’s connected to the … mar-ker.
Follow the same general process illustrated in the example above for any graphi
c element you want to create. 1. Create a new graphic element (LineElement, Mark
erElement, PolygonElement, 2. Create a new symbol appropriate for the element (L
ineSymbol, TextSymbol, FillSymbol, etc.). 3. Create a new color object (RgbColor
, CmykColor, GrayColor, HlsColor, or HsvColor). 4. Define the color’s value. 5.
Assign the color to the symbol. 6. Define the symbol’s style. 7. Assign the symb
ol to the graphic element. At this point, the graphic element is completely defi
ned, but does not yet appear on the display.
Defining an element’s position
IElement :: Geometry
Supported by all subclasses of Element Defines a position on the map (or layout
page) Specify with a point, line, or envelope
Dim Dim Set Set pElem pElem pElem pElem As IElement As IElement = pMarkerElem Q
I = pMarkerElem QI
Dim pPoint As IPoint Dim pPoint As IPoint Set pPoint = New Point Set pPoint = Ne
w Point pPoint.PutCoords -63.91, -8.77 pPoint.PutCoords -63.91, -8.77 pElem.Geom
etry = pPoint pElem.Geometry = pPoint
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
12-8
Tell that element where to go All elements support a Geometry property (defined
on the IElement interface). Before adding any element to the display (GraphicsCo
ntainer), you must first define where the element is to appear on the page or ma
p. An element’s Geometry property can be specified with either a point, a line,
or an envelope, depending on which is most appropriate. Marker elements, of cour
se, should be defined using a point. Text elements, on the other hand, can be po
sitioned with a point (the center of the text), a line (perhaps a curve that the
text should follow), or an envelope (bounding box). Geometry can be defined eit
her in page units (for elements added to the page layout) or in map units (for e
lements added to the data frame).
Adding an element to the map (or layout)
Use IGraphicsContainer :: AddElement
Specify the element and the order Zero is the first (top) element, increases fro
m top to bottom
Dim pMxDoc As IMxDocument Dim pMxDoc As IMxDocument Set pMxDoc = ThisDocument Se
t pMxDoc = ThisDocument pMxDoc.ActiveView.GraphicsContainer.AddElement pElem, 0
pMxDoc.ActiveView.GraphicsContainer.AddElement pElem, 0 --OR— --OR— Dim pGCont
ainer As IGraphicsContainer Dim pGContainer As IGraphicsContainer Set pGContaine
r = pMxDoc.FocusMap Set pGContainer = pMxDoc.FocusMap pGContainer.AddElement pEl
em, 0 pGContainer.AddElement pElem, 0 pMxDoc.ActiveView.Refresh pMxDoc.ActiveVie
w.Refresh
Refresh the display to show the new element
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming Arc
Objects with VBA
12-9
Adding an element to the graphics container Both the Map and PageLayout classes
support the IGraphicsContainer interface. As the name implies, this is an interf
ace that allows a programmer to manage graphic elements that appear either in th
e data frame or in the page layout. The AddElement method is used to place new e
lements on the display. To add an element to the layout, use IGraphicsContainer
on the PageLayout object and make sure your element’s position (Geometry propert
y) has been defined in page units. An element added to the data frame should use
IGraphicsContainer on the Map object, and have its geometry defined in map unit
s. To control which elements are drawn on top of others, a programmer can change
the order of elements using methods such as SendToBack, BringToFront, or PutEle
mentOrder. When retrieving elements, the GraphicsContainer behaves like an enum.
To retrieve elements from the container, a programmer cannot use the element’s
position, but must instead use the Next method to pull out elements sequentially
, and the Reset method to move the pointer back to the top.
Example: Count all the graphic elements on the layout
Public Sub CountLayoutElements () Dim pMxDoc As IMxDocument Dim pGContainer As I
GraphicsContainer Dim pElement As IElement Dim intGraphicCount As Integer Set pM
xDoc = ThisDocument Set pGContainer = pMxDoc.PageLayout pGContainer.Reset *Make
sure the pointer is on the first item *pull out the first element Set pElement
= pGContainer.Next
Do Until pElement Is Nothing *Loop thru all elements If TypeOf pElement Is IGra
phicElement Then intGraphicCount = intGraphicCount + 1 End If Set pElement = pGC
ontainer.Next Loop MsgBox "There are " & intGraphicCount & " graphics on the pag
e" Exit Sub *pull out the next element *increment the count
FeatureRenderers
Renderers define how a layer is displayed
IFeatureRenderer
FeatureRenderer
FeatureLayer
SimpleRenderer
UniqueValueRenderer
ClassBreaksRenderer
ChartRenderer
ScaleDependentRenderer
DotDensityRenderer
There are additional Renderers for displaying RasterLayers and TinLayers
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
12-11
All feature layers have an associated FeatureRenderer that can be set or returne
d through the Renderer property, which is defined on the IGeoFeatureLayer interf
ace. The Renderer property is a property put by reference, so you must use the S
et keyword when assigning an object to this property. There are several subtypes
of FeatureRenderers, each of which is a coclass, and can therefore be created w
ith the New keyword. In this lesson, you will be introduced to the common render
ers listed below. • SimpleRenderer ArcMap software’s default feature renderer. A
SimpleRenderer symbolizes every feature in the layer with the same symbology (i
.e., style and color). • UniqueValueRenderer Displays a layer by assigning a dif
ferent symbol to each unique value found in a given attribute field. A land cove
r map, for example, could be displayed with a UniqueValueRenderer to show a hand
ful of unique land cover types that may exist for several thousand polygons. • C
lassBreaksRenderer Uses a classification based on one of the layer’s numeric att
ributes to display statistically (or manually) defined groups of features. The c
lass boundaries may be set explicitly or by using one of the ArcMap Classify obj
ects (NaturalBreaks, DefinedInterval, Quantile, EqualInterval, or StandardDeviat
ion). • ScaleDependentRenderer A renderer that actually contains a collection of
renderers. Its purpose is to let you specify different renderers for particular
scale ranges. You might use more detailed symbols as your user zooms in and mor
e general symbology when he or she zooms out, for example.
SimpleRenderer
Default renderer displays features with a single symbol
USA
Properties
Symbol: Color and Style Label: A string to appear in the legend
Refresh after modifying a layer’s renderer
Set a feature layer’s renderer Set a feature layer’s renderer Set pFLayer.Rend
erer = pRender Set pFLayer.Renderer = pRender Refresh the display Refresh the
display pMxDoc.ActiveView.Refresh pMxDoc.ActiveView.Refresh Refresh the Table o
f Contents (TOC) Refresh the Table of Contents (TOC) pMxDoc.UpdateContents pMxD
oc.UpdateContents
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming Arc
Objects with VBA
12-12
Example: Create and modify a SimpleRenderer
Private Sub ApplySimpleRenderer(SomeLayer As IGeoFeatureLayer) Dim pSRenderer As
ISimpleRenderer Set pSRenderer = New SimpleRenderer Dim pFillSymbol As ISimpleF
illSymbol Set pFillSymbol = New SimpleFillSymbol pFillSymbol.Style = esriSFSForw
ardDiagonal Dim pColor As IRgbColor Set pColor = New RgbColor pColor.RGB = vbBlu
e pFillSymbol.Color = pColor Property put by reference, must use "Set" … Set pS
Renderer.Symbol = pFillSymbol pSRenderer.Label = "USA" Set the layer’s renderer
, also property put by reference Set SomeLayer.Renderer = pSRenderer Dim pMxDoc
As IMxDocument Set pMxDoc = ThisDocument pMxDoc.UpdateContents pMxDoc.ActiveView
.Refresh End Sub Update legend Redraw display
UniqueValueRenderer
Displays features with a symbol for each unique value
Properties
Field(s): The field(s) in the feature class for which unique values are rendered
Value(s): Unique categories of features (e.g., “Pacific”) ValueCount: The numbe
r of unique values displayed by the renderer (e.g., the U.S. has nine regions)
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
12-13
Example: Create a UniqueValueRenderer to uniquely symbolize each state
Private Sub ApplyUniqueRenderer(SomeLayer As IGeoFeatureLayer) Dim pUVRenderer A
s IUniqueValueRenderer Set pUVRenderer = New UniqueValueRenderer Dim pColorEnum
As IEnumColors Set pColorEnum = MakeRandomRamp(50) Example on pg 12-5 pUVRender
er.FieldCount = 1 pUVRenderer.Field(0) = "STATE_NAME" Dim pFClass As IFeatureCla
ss Set pFClass = SomeLayer.FeatureClass Dim pFCursor As IFeatureCursor Set pFCur
sor = pFClass.Search(Nothing, False) Dim pFeature As IFeature, pSym As ISimpleFi
llSymbol Set pFeature = pFCursor.NextFeature Do Until pFeature Is Nothing Set pS
ym = New SimpleFillSymbol pSym.Color = pColorEnum.Next pUVRenderer.AddValue _ pF
eature.Value(pFClass.FindField("STATE_NAME")), "States", pSym Set pFeature = pFC
ursor.NextFeature Loop Set SomeLayer.Renderer = pUVRenderer Property put by ref
erence m_pMxDoc.UpdateContents m_pMxDoc.ActiveView.Refresh End Sub
ClassBreaksRenderer
A symbol for each grouping of numeric values
Properties
Breaks: Cut-off points between classes Field: Attribute on which classes are der
ived BreakCount: Number of class breaks
Classification methods
Use the appropriate Classify objects on the Display OMD
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming Arc
Objects with VBA
12-14
Those are the Breaks A ClassBreaksRenderer is used to display classes of a layer
’s features based on a numeric attribute. When creating a ClassBreaksRenderer, y
ou need to specify the number of classes to use, the field on which the classifi
cation is based and whether classes should be sorted lowest to highest (ascendin
g) or highest to lowest (descending). The breaks (cut-off points) that define ea
ch class also need to be explicitly defined by the programmer, along with the sy
mbol that will be used to symbolize each class. The numeric values that represen
t the break points for each class can be defined arbitrarily (hard-coded) or may
be derived from a statistical method. Assigning classes and symbols to the rend
erer is usually performed in a looping routine such as the pseudocode shown belo
w.
For i=0 to the-number-of-classes -1 Make a new symbol Set symbol properties (e.g
., color) Assign class break i Assign the symbol for class i Next i
ScaleDependentRenderer
A renderer that contains renderers Update the rendering of a layer according to
scale
More detail at large scales, less detail at small scales
1:75,000,000
1:7,000,000
Properties
Breaks: Cut-off points (scale ranges) Renderers: Renderers in the ScaleDependent
Renderer RendererCount: Number of renderers contained
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
12-15
A ScaleDependentRenderer is simply a collection of several renderers used to dis
play a single layer. Particular renderers in the ScaleDependentRenderer are appl
ied to the feature layer (i.e., turned on and off) according to the scale at whi
ch the data is displayed. This may be useful for dynamically displaying a layer
in more detail when viewed at a larger scale while showing a general view when v
iewed at a smaller scale. When creating a ScaleDependentRenderer, the order in w
hich you add renderers should match the order in which you define the associated
scale breaks. In other words, the first renderer added will correspond to the f
irst break that is defined. The code below adds two renderers and sets their sca
le breaks. Because the renderer represented by pZoomedInRend was added first, it
will be associated with the first break (break 0). This renderer will be used t
o display the layer at scales greater than 1:10000000. When the layer is display
ed at scales between 1:10000001 and 1:90000000, it will be displayed using the r
enderer represented by pZoomedOutRend. Note: If zoomed out beyond the last thres
hold (scales smaller than 1:90000000 in the example below) the layer will not be
renderered.
pScaleDepRend.AddRenderer pZoomedInRend pScaleDepRend.AddRenderer pZoomedOutRend
pScaleDepRend.Break(0) = 10000000 Set scale threshold for 2nd renderer (pZoom
edOutRend) pScaleDepRend.Break(1) = 90000000 Set pFLayer.Renderer = pScaleDepRen
d Assign the layer’s renderer Add the 1st renderer Add the 2nd renderer
Set scale threshold for 1st renderer (pZoomedInRend)
Storing layers on disk
Layers may be saved as layer (*.lyr) files Layer files store information about t
he layer
Path to the data Symbology Label preferences Definition query Etc.
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
12-16
Layer files In ArcGIS, a layer object can live in one of two places: saved as pa
rt of an ArcMap document (*.mxd, *.mxt) or saved individually in a layer file (*
.lyr). In either case, the layer will define the path to a data source (e.g., sh
apefile) and options for data display (classification, symbology, labels, etc.).
By storing layers in layer files, display properties only need to be set once.
Layers that are used frequently can be easily reused between documents without h
aving to redefine display options inside ArcMap. Layer files are especially well
suited for base layers that are used in several maps and may also require a con
sistent (standard) symbology.
GxLayer object
Use to access layer (*.lyr) files
A subtype of GxFile
IGxFile::Path
Defines the path to a file
GxCatalog
GxFile
IGxFile
IGxFile : IUnknown
*
Path: String
GxLayer
IGxLayer
IGxLayer : IUnknown Layer: ILayer
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
12-17
Example: adding a layer to ArcMap using GxLayer
Private Sub GetLayerFromFile () Create a new GxLayer Dim pGxLayer As IGxLayer S
et pGxLayer = New GxLayer QueryInterface to IGxFile, specify the path Dim pGxFi
le As IGxFile Set pGxFile = pGxLayer pGxFile.Path = "C:\Data\Waynesboro.lyr" Ge
t the layer from the file Dim pLayer As ILayer Set pLayer = pGxLayer.Layer Add
the layer to the active data frame Dim pMxDoc As IMxDocument Set pMxDoc = ThisDo
cument pMxDoc.FocusMap.AddLayer pLayer End Sub
Example: Saving a layer from ArcMap
Public Sub SaveFirstLayer () Dim pMxDoc As IMxDocument Set pMxDoc = ThisDocument
Create a new GxLayer object Dim pGxLayer As IGxLayer Set pGxLayer = New GxLaye
r Coclass: can create new QueryInterface for the IGxFile interface Dim pGxFile
As IGxFile Set pGxFile = pGxLayer Define the file’s pathname pGxFile.Path = "C
:\Data\Shelbyville.lyr" Assign the first layer in the focus map to the layer fi
le Set pGxLayer.Layer = pMxDoc.FocusMap.Layer(0) Save the file pGxFile.Save Do
ne! End Sub
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
12-18
Programmatically saving layer files The GxLayer class is a coclass, so instances
can be created using the New keyword. The only member available on the IGxLayer
interface is the Layer property. IGxLayer:: Layer is used to define or retrieve
the layer object stored in the file. GxLayer is a subclass of GxFile, and there
fore supports the IGxFile interface. When saving a new layer file, you must Quer
yInterface to IGxFile in order to define the output file name (using the Path pr
operty). The Save method must be called to commit the layer file to disk. Exampl
e: Saving all layers in the active data frame
Public Sub SaveAllLayers () Dim pMxDoc As IMxDocument Set pMxDoc = ThisDocument
Dim pEnumLayer As IEnumLayer, pLayer As ILayer Set pEnumLayer = pMxDoc.FocusMap.
Layers Set pLayer = pEnumLayer.Next Do Until pLayer Is Nothing Dim pGxLayer As I
GxLayer Dim pGxFile As IGxFile Set pGxLayer = New GxLayer Set pGxFile = pGxLayer
Set pGxLayer.Layer = pLayer pGxFile.Save Set pLayer = pEnumLayer.Next Loop End
Sub **QueryInterface pGxFile.Path = "C:\Data\Layers\" & pLayer.Name & ".lyr"
Exercise 12 overview
Create a new fill symbol and color Render layers in the map Save a layer in the
document to a layer file (*.lyr) Add layer files to ArcMap Experiment with scale
dependent rendering
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
12-19
Exercise 12: Work with the display, symbols, and renderers In this exercise, you
will: • Create a new fill symbol and color for rendering a layer. • Create a ne
w UIButtonControl for saving the selected layer to a layer file. • Create a cont
rol for adding layer files to the focus map. • Experiment with ScaleDependentRen
derers.
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
12-20
Introduction to Programming ArcObjects with VBA
Working with layout elements
Lesson overview 13-2 Object Model overview 13-3 Review: Elements 13-4 FrameEleme
nts 13-5 Example: Reference MapFrames on the layout 13-6 Review: Subclasses of S
ymbol 13-7 Review: Color classes 13-8 The StyleGallery 13-9 Getting style items
from the gallery 13-10 Example: Referencing an individual style item 13-11 Getti
ng the item 13-12 Basic steps: Adding a map surround 13-13 StyleSelector 13-14 P
rinting a layout 13-15 Exporting a layout 13-16
contents
Working with layout elements (Optional)
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
Introduction to Programming ArcObjects with VBA
Working with layout elements
13-1
Lesson overview
Adding frame elements to the PageLayout Using the graphics container Symbology r
eview
Symbols Colors Elements
Accessing items from the StyleGallery Printing and exporting a layout
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
13-2
Working with Layout Elements This lesson will discuss many of the objects relate
d to adding graphics to an ArcMap page layout or map. Graphics, whether they are
things such as scalebars, north arrows, markers, lines, or text, are genericall
y referred to as elements. Each of these elements may be added to a page layout,
or possibly a map. When working with elements, you may also find it necessary t
o use related objects such as symbols, colors, and geometry (to define the eleme
nts position on the page or map), all of which will be covered in this lesson.
Lesson overview • Object model overview • Working with layout frame elements • F
inding existing elements, creating new ones • Review: Symbols, Colors, Elements
• Referencing elements in the ArcMap style gallery • Outputting a layout to a pr
inter or file
Introduction to Programming ArcObjects with VBA
Working with layout elements
13-2
Object Model overview
ArcMap OMD ArcMap OMD
Geometry Element PageLayout M xDocument
*
*
GraphicElement FrameElement M ap
TextElement
M apFrame
*
MapSurround
LineElement
M apSurroundFrame ScaleBar
M arkerElement
TableFrame Legend
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
13-3
From the simple object model diagram above, you can tell that a PageLayout is co
mposed of (potentially) several Element objects. Element is an abstract class th
at has several sub-types. On the IElement interface (implemented by every subcla
ss of Element) there is a Geometry property. An element added to a layout or map
uses this property to specify its location. An element’s geometry can be define
d in map units or page units, whichever is appropriate. Graphic and Frame elemen
ts The two direct sub-types of Element are themselves abstract classes and repre
sent the two fundamental types of elements: • GraphicElements—text, shape, and p
icture elements • FrameElements—MapFrames (i.e., data frames), TableFrames, OLEF
rames, and MapSurroundFrames (e.g., north arrows, legends, and scalebars) Apart
from a handful of abstract classes, all elements are creatable (coclasses). As a
programmer, you can create new text, graphic, or map elements to add to your la
yout. Most graphic elements will have a Symbol property that allows you to contr
ol the color and style of the graphics you create. Frame elements are used as co
ntainers in the layout. MapFrames contain a collection of layers (in other words
, a data frame), while a MapSurroundFrame element is used to contain objects tha
t are related to a particular Map, such as a scalebar, north arrow, or legend. I
t is important to make a distinction between a MapSurroundFrame, and the object
it contains, a MapSurround. MapSurrounds, such as a Legend, are related directly
to a Map (data frame), and must be contained within a MapSurroundFrame in order
to be represented on the layout. Other types of FrameElements include TableFram
e, for containing a Table object, and an OLEFrame, for containing another applic
ation (such as a Microsoft Word document).
Introduction to Programming ArcObjects with VBA
Working with layout elements
13-3
Review: Elements
Several creatable classes Graphic elements
Line, polygon, marker Text and pictures
FrameElement GraphicElement
IElement
Element
Geometry
FrameElements
On the PageLayout Map frames Table frames
TextElement
LineElement
BmpPictureElement
M arkerElement
North arrows, legends, scale bars
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
13-4
Example: Count the types of elements on the layout
Public Sub CountElements () Dim pMxDoc As IMxDocument Dim pGC As IGraphicsContai
ner Set pMxDoc = ThisDocument Set pGC = pMxDoc.PageLayout pGC.Reset Dim intMapFr
ames As Integer, intMSFrames As Integer Dim intTextElements As Integer, intOther
Elements As Integer Dim pElement As IElement Set pElement = pGC.Next Do Until pE
lement Is Nothing If TypeOf pElement Is IMapFrame Then intMapFrames = intMapFram
es + 1 ElseIf TypeOf pElement Is IMapSurroundFrame Then intMSFrames = intMSFrame
s + 1 ElseIf TypeOf pElement Is ITextElement Then intTextElements = intTextEleme
nts + 1 Else intOtherElements = intOtherElements + 1 End If Set pElement = pGC.N
ext Loop MsgBox "The layout has " & intMapFrames & " map frames, " & _ intMSFram
es & " map surround frames, " & _ intTextElements & " text elements, and " & _ i
ntOtherElements & " miscellaneous element types." End Sub
Introduction to Programming ArcObjects with VBA Working with layout elements 13-
4
FrameElements
Added to the PageLayout MapSurroundFrame elements
Container for MapSurrounds (e.g., Scalebars) Contents are dynamically updated
IElement
MapSurroundFrame MapSurroundFrame
Element
*
PageLayout
MapSurround MapSurround
GraphicElement
FrameElement
M ap
*
TextElement M apFrame M apSurround
M apSurroundFrame
ScaleBar
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
13-5
MapSurrounds and MapSurroundFrames The terms MapSurround and MapSurroundFrame ca
n be a little confusing. To distinguish these objects, remember that a MapSurrou
ndFrame is a type of Element, and can be added to a PageLayout. A MapSurround ob
ject, on the other hand, is always contained within a MapSurroundFrame and has a
dynamic relationship with a Map (data frame).
Introduction to Programming ArcObjects with VBA
Working with layout elements
13-5
Example: Reference MapFrames on the layout
Dim pMxDoc As IMxDocument Set pMxDoc = ThisDocument Dim pGC As IGraphicsContaine
r Set pGC = pMxDoc.PageLayout pGC.Reset Like an enum, Reset moves above the 1st
item Dim pElem As IElement Set pElem = pGC.Next Also like an enum, Next gets a
n element Do Until pElem Is Nothing If (TypeOf pElem Is IMapFrame) Then Many el
ement types Dim pMapEnvelope As IEnvelope Dim intW As Integer, intH As Integer S
et pMapEnvelope = pElem.Geometry.Envelope intW = pMapEnvelope.Width intH = pMapE
nvelope.Height MsgBox "Map Frame = " & intW & " by " & intH End If Set pElem = p
GC.Next Retrieve another element Loop
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming Arc
Objects with VBA
13-6
Retrieving an element from the GraphicsContainer Elements in a GraphicsContainer
are organized like objects contained by an enum. Elements cannot be referenced
directly by their index position inside the GraphicsContainer, but must be locat
ed within a looping routine. If searching for a particular type of element (text
, picture, etc.), use the TypeOf statement to identify the element(s) you want t
o work with. The example above uses a Do While loop to iterate through each elem
ent in the GraphicsContainer. Inside the loop, a test is made to determine if th
e current element is a map frame (supports the IMapFrame interface). If it is, t
he element’s dimensions are stored, and then reported in a message box inside th
e loop. An ArcMap document always has at least one map frame, but could potentia
lly have many more. The code above will report the dimensions of all map frames
in the layout. Finding an element by name Elements added to the GraphicsContaine
r can be given a name by using the Name property on IElementProperties. By assig
ning a name to an element, it can be easily referenced later by using code such
as that shown below:
Dim pElementProps As IElementProperties Set pElementProps = pGContainer.Next Do
Until pElementProps Is Nothing *Loop thru all elements If pElementProps.Name =
"DougherNorth" Then *Look for this one … Dim pLegendFrame As IMapSurroundFrame
Set pLegendFrame = pElementProps *QueryInterface (QI) Exit Do *Exit the loop o
nce it s found End If Set pElementProps = pGContainer.Next Loop
Introduction to Programming ArcObjects with VBA
Working with layout elements
13-6
Review: Subclasses of Symbol
ISymbol
Symbol *
MarkerSymbol
LineSymbol
FillSymbol
SimpleM arkerSymbol
SimpleLineSymbol
SimpleFillSymbol
CharacterM arkerSymbol
PictureLineSymbol
LineFillSymbol
PictureM arkerSymbol
Has hLineSymbol
M arkerFillSymbol
* Several additional types of symbols are listed on the Display OMD, including T
extSymbols
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming Arc
Objects with VBA
13-7
Symbol You will find the Symbol abstract class and all of its subtypes listed on
the Display object model diagram. Any item on the Map or PageLayout must have a
symbol in order to be displayed. ArcMap uses MarkerSymbols, LineSymbols, or Fil
lSymbols to display geometry, and TextSymbols to display text elements. There ar
e also 3DChartSymbols for drawing charts (graphs). The ISymbol interface (suppor
ted by each subtype of Symbol) has methods for drawing a symbol directly to a de
vice context (DC). A device context represents an acceptable output device, such
as a printer or a window display (the ArcMap map display, for example). Each sy
mbol subclass has methods and properties a programmer can use to define the symb
ol, such as Style, Line Width, Font, Size, Angle, and Color. Choose the appropri
ate subclass of symbol according to how you would like to define it: a PictureMa
rkerSymbol to define a marker from a bitmap or GIF image, a CharacterMaker to de
fine a marker from a specific font and character, for example. Example: Creating
a bold Arial text symbol
*Make a new Font … Dim pArialFont As New stdole.StdFont pArialFont.Name = "Aria
l" pArialFont.Bold = True *Make a new TextSymbol, set its properties (including
the font) … Set pTextSym = New TextSymbol pTextSym.Angle = 45 pTextSym.Font = p
ArialFont pTextSym.Size = 28 *Assign the TextSymbol to a TextElement … pTextEle
m.Symbol = pTextSym
Introduction to Programming ArcObjects with VBA
Working with layout elements
13-7
Review: Color classes
Five creatable subclasses
RgbColor CmykColor HsvColor HlsColor GrayColor
CmykColor Hs vColor RgbColor Hls Color
IColor
Color
GrayColor
ColorSelector object
Allow the user to choose a color Same dialog available from the user interface
Use a color object to assign a symbol’s color property
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
13-8
Add some color to your code Because the five subclasses of color are coclasses,
they can each be created with the New keyword. As a programmer, you can choose C
olor objects and interfaces according to how you would like to define a particul
ar color. To specify individual values for red, green, and blue for example, you
would use the IRgbColor interface on the RgbColor class. Let the user decide …
Instead of “hard-coding” the value of colors in your program, you may want to le
t the user choose a color interactively. ArcObjects gives you access to the same
color selection dialog you find from the ArcGIS user interface. The code below
will display the color selection dialog (shown above), then return the color sel
ected.
Public Function GetUserColor() As IColor Dim pColorDlg As IColorSelector Set pCo
lorDlg = New ColorSelector dialog Dim bMadeChoice As Boolean bMadeChoice = pColo
rDlg.DoModal(Application.hWnd) *Show the dialog If Not bMadeChoice Then Exit Fu
nction *If user hit "Cancel", exit Set GetUserColor = pColorDlg.Color *Return
the selected color End Function *Make a new color selection
Introduction to Programming ArcObjects with VBA
Working with layout elements
13-8
The StyleGallery
MxDocument is composed of a single StyleGallery
Can also be created new (e.g., for stand-alone applications) Contains style clas
ses and style items
M xDocument StyleGallery
* StyleGalleryClas s
Get the style gallery Get the style gallery Set pMxDoc = ThisDocument Set pMxD
oc = ThisDocument Dim pGallery As IStyleGallery Dim pGallery As IStyleGallery Se
t pGallery = pMxDoc.StyleGallery Set pGallery = pMxDoc.StyleGallery —OR -- make
a new style gallery —OR -- make a new style gallery Set pGallery = New StyleGa
llery Set pGallery = New StyleGallery
StyleGalleryItem
EnumStyleGalleryItem
ColorStyleGalleryClas s
FillSymbolStyleGalleryClas s
NorthArrowStyleGalleryClas s
TextSymbolStyleGalleryClas s
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
13-9
Why reinvent the wheel? ArcMap comes with an extensive set of symbols and map el
ements that you can access through the StyleGallery. The StyleGallery object con
tains StyleGalleryClasses, such as north arrows, marker symbols, color ramps, co
lors, and scale bars (to name but a few). Within each StyleGalleryClass, you can
reference individual StyleGalleryItems. StyleGalleryItems are objects that repr
esent particular north arrows, marker symbols, colors, or anything else you migh
t find in the StyleGallery (the “Open Pasture” fill pattern, for example). By re
ferencing items that are already defined in the StyleGallery, a programmer does
not need to explicitly build each element “from the ground up”. Each MxDocument
is composed of a single StyleGallery object. The StyleGallery can be accessed by
using the StyleGallery property on IMxDocument. From the StyleGallery, a progra
mmer can access enums of all StyleGalleryItems contained by a particular StyleGa
lleryClass (an enum of all color ramps, for example). Instances of the StyleGall
ery class can also be created new. This can be useful when building stand-alone
applications (in Visual Basic, for example) that need to reference items stored
in an ArcGIS style.
Introduction to Programming ArcObjects with VBA
Working with layout elements
13-9
Getting style items from the gallery
IStyleGallery :: Items
Specify the style class (type) Returns an enum of style items
Get the North Get the North Dim pEnumNorth Dim pEnumNorth Set pEnumNorth Set p
EnumNorth ("North ("North Arrows in the ESRI.style style set Arrows in the ESRI.
style style set As IEnumStyleGalleryItem As IEnumStyleGalleryItem = pGallery.Ite
ms _ = pGallery.Items _ Arrows", "ESRI.style", "Default") Arrows", "ESRI.style",
"Default")
StyleSet Name Style Class Name Style Category Name
Get ALL north arrows (from all loaded styles) … Get ALL north arrows (from all
loaded styles) … Set pEnumNorth = pGallery.Items ("North Arrows", "", "" ) Set
pEnumNorth = pGallery.Items ("North Arrows", "", "" )
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming Arc
Objects with VBA
13-10
Accessing StyleGalleryItems When accessing a particular StyleGalleryItem, the fi
rst step (after getting the StyleGallery object) is to retrieve an enum of all i
tems of a particular StyleGalleryClass. Use the Items property (read-only) on IS
tyleGallery to return the enum, passing in three required arguments: the name of
the StyleClass you want (Marker Symbols, Legend Items, Colors, etc.), the name
of the style set (ESRI.style, Hazmat.style, Business.style, etc.), and the style
category name (Default, Fire Incident, ESRI Human Use, etc.). Once you have an
enum from a StyleGalleryClass, you can use a looping routine to locate a particu
lar item. You may find it useful to browse the ArcGIS styles before referencing
them with code to get a better idea of the objects you will use. To access the s
tyles from ArcMap, click the Tools menu, then Styles, and then Style Manager. In
the dialog that appears, you can access the various style sets (*.style) and al
l the style classes and style items they contain.
Introduction to Programming ArcObjects with VBA
Working with layout elements 13-10
Example: Referencing an individual style item
Get the 8th North Arrow gallery listing … Dim pNorthItem As IStyleGalleryItem D
im intIndex As Integer For intIndex = 0 To 7 Set pNorthItem = pEnumNorth.Next Ne
xt intIndex —OR– get the arrow named "ESRI North 3" … Dim pNorthItem As IStyleG
alleryItem Set pNorthItem = pEnumNorth.Next Do Until pNorthItem Is Nothing If pN
orthItem.Name = "ESRI North 3" Then Exit Do End If Set pNorthItem = pEnumNorth.N
ext Loop
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
13-11
Find your Style To locate a particular StyleItem from an enum, use one of the fa
miliar Visual Basic looping routines. To find an item according to its position
(the 23rd color ramp, for example), an ArcObject programmer can use a For Next l
oop to call the Next method x number of times. To find an item by name, use a Do
Until or Do While loop, as in the second example above.
Example: Saving an item to the style gallery
Public Sub SaveMarkerSym(aNewSymbol As IMarkerSymbol) *Make a new StyleGalleryI
tem, set its properties ... Dim pSGItem As IStyleGalleryItem Set pSGItem = New S
tyleGalleryItem pSGItem.Item = aNewSymbol *assign the marker symbol pSGItem.Nam
e = "Chanda Marker" *give it a name pSGItem.Category = "Custom" *assign it to
a category Dim pMxDoc As IMxDocument Set pMxDoc = ThisDocument Dim pSGalleryStor
age As IStyleGalleryStorage Set pSGalleryStorage = pMxDoc.StyleGallery *get the
style gallery *Indicate the target style file for the new marker ... pSGallery
Storage.TargetFile = "ESRI.style" Dim pSGallery As IStyleGallery Set pSGallery =
pSGalleryStorage QueryInterface pSGallery.AddItem pSGItem *add item to the ga
llery (ESRI.style) End Sub
Introduction to Programming ArcObjects with VBA
Working with layout elements 13-11
Getting the item
A StyleGalleryItem is not the item itself Use the Item property to return the it
em
Color, North Arrow, Fill Symbol, Color Ramp, etc.
Get the item (North Arrow) Get the item (North Arrow) Dim pArrow As INorthArro
w This is a MapSurround Dim pArrow As INorthArrow This is a MapSurround Set pA
rrow = pNorthItem.Item Set pArrow = pNorthItem.Item Item Item
StyleGalleryItem StyleGalleryItem
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
13-12
The map is not the terrain, the StyleGalleryItem is not the Item When you refere
nce a StyleGalleryItem from the StyleGallery, what you have is not the actual it
em (north arrow, color, symbol, etc.) but a listing for the item. Conceptually,
it is like the difference between a listing for a text file in Windows Explorer
versus the actual file opened in a text editor. A StyleGalleryItem represents an
item in the StyleGallery, and to access the underlying item, a programmer must
use the Item property on the IStyleGalleryItem interface. I am not anonymous, so
why am IUnknown? The Style object model diagram indicates that the Item propert
y on IStyleGalleryItem returns a pointer to the IUnknown interface. Why? You mig
ht expect it to return, for example, ISymbol, IMapSurround, or IColor. At first
glance this might seem confusing, but when considering the nature of StyleGaller
yItems, it becomes clearer. Because the style gallery contains a variety of obje
cts, including colors, color ramps, north arrows, text symbols, and even referen
ce systems, ArcMap cannot anticipate what exactly will be returned from a partic
ular StyleGalleryItem. The one thing that each of these objects will have in com
mon, however, is the IUnknown interface, which is implemented by all COM classes
.
Introduction to Programming ArcObjects with VBA
Working with layout elements 13-12
Basic steps: Adding a map surround
A MapSurround is contained by a MapSurroundFrame
1. 2. 3. 4. 5.
Create a MapSurround (or get it from the StyleGallery) Associate the MapSurround
with a Map Create a MapSurroundFrame Add the MapSurround to the MapSurroundFram
e Add the MapSurroundFrame to the layout (IGraphicsContainer)
MapSurround MapSurround
Code on previous slide created pArrow —1 Code on previous slide created pArrow
—1Set pArrow.Map = pMxDoc.FocusMap —2Set pArrow.Map = pMxDoc.FocusMap —2 Put t
he surround (North Arrow) in a Put the surround (North Arrow) in a Dim pMSFrame
As IMapSurroundFrame Dim pMSFrame As IMapSurroundFrame Set pMSFrame = New MapSu
rroundFrame Set pMSFrame = New MapSurroundFrame Set pMSFrame.MapSurround = pArro
w Set pMSFrame.MapSurround = pArrow pGContainer.AddElement pMSFrame, 0 pGContain
er.AddElement pMSFrame, 0
Copyright © 2001–2004 ESRI. All rights reserved.
frame frame —3 —3 —4 —4 —5 —5-
MapSurroundFrame MapSurroundFrame
Introduction to Programming ArcObjects with VBA
13-13
You are surrounded MapSurrounds are things such as north arrows, scale bars, and
legends. MapSurrounds are not simple graphics that you add to a layout, but are
directly and dynamically tied to a map (data frame). When a user zooms in or ou
t on a map, for example, the scale bar that is associated with that map must dyn
amically alter itself to represent the new scale. Use the Map property on IMapSu
rround (which is a property put by reference) to tie a MapSurround to the approp
riate Map. I was framed MapSurrounds are not added directly to a page layout, in
stead they are added to a special type of frame element, called a MapSurroundFra
me. As the name indicates, a MapSurroundFrame is simply a container for MapSurro
unds. Once a MapSurround has been added to a MapSurroundFrame element, it can be
placed on the page (added to the PageLayout’s GraphicsContainer). Use the Geome
try property on IElement to define the MapSurroundFrame’s position on the page.
Introduction to Programming ArcObjects with VBA
Working with layout elements 13-13
StyleSelector
Let the user choose a style item for the PageLayout
GetStyle method returns the chosen item
IStyleSelector
StyleSelector
Let the user Let the user Dim pNorthSel Dim pNorthSel Set pNorthSel Set pNorth
Sel
choose a north arrow choose a north arrow As IStyleSelector As IStyleSelector =
New NorthArrowSelector = New NorthArrowSelector
BackgroundSelector
Dim bMadeChoice As Boolean Dim bMadeChoice As Boolean bMadeChoice = pNorthSel.Do
Modal _ bMadeChoice = pNorthSel.DoModal _ (Application.hWnd) (Application.hWnd)
Was a choice made? Was a choice made? If Not bMadeChoice Then Exit Sub If Not
bMadeChoice Then Exit Sub Get the user’s selection Get the user’s selection Di
m pNArrow As INorthArrow Dim pNArrow As INorthArrow Set pNArrow = pNorthSel.GetS
tyle(0) Set pNArrow = pNorthSel.GetStyle(0)
LegendItemSelector
NorthArrowSelector
ScalebarSelector
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
13-14
Freedom of choice Rather than explicitly hard-coding the north arrow, scalebar,
or label styles displayed on the layout, you may want to have your users select
these styles for themselves. A variety of selector dialogs can be created and di
splayed for the user to make selections. The complete list of StyleSelector sub-
classes is listed below. • BackgroundSelector: background symbol for map frame (
fill) • BorderSelector: map frame border symbol (line) • LabelStyleSelector: tex
t symbol (for layout text elements, etc.) • LegendItemSelector: legend item form
at • MapGridSelector: gradicule, grid, or index for map frame • NorthArrowSelect
or: north arrows • ScalebarSelector: scalebars • ScaleTextSelector: text symbol
for representative scale • ShadowSelector: shadow symbol for map frame (fill) Af
ter displaying a style selector dialog, use the GetStyle method (on IStyleSelect
or) to reference the selected style. This method returns a pointer to IUnknown b
ecause this interface is the “lowest common denominator” for all the items liste
d above.
Introduction to Programming ArcObjects with VBA
Working with layout elements 13-14
Printing a layout
Variety of subclasses
PsPrinter (postscript) ArcPressPrinter
EmfPrinter Ps Printer
IPrinter
Printer
EmfPrinter (enhanced meta-file)
Paper class
Manages printer page settings
ArcPres s Printer
Send to a printer or to a file
Application Paper
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
13-15
Example: Printing the layout to a postscript file
Private Sub PrintToPSFile(aLayout As IPageLayout, FileName As String) Dim pMxApp
As IMxApplication, pPrinter As IPrinter Set pMxApp = Application Set pPrinter =
New PsPrinter Set pPrinter.Paper = pMxApp.Paper pPrinter.PrintToFile = FileName
Dim pPrintEnv As IEnvelope Set pPrintEnv = New Envelope aLayout.Page.GetDeviceB
ounds pPrinter, 0, 0, pPrinter.Resolution, pPrintEnv Dim rectOut As tagRECT rect
Out.Left = pPrintEnv.xMin rectOut.Top = pPrintEnv.yMin rectOut.Right = pPrintEnv
.xMax rectOut.bottom = pPrintEnv.yMax Dim pPageBounds As IEnvelope Set pPageBoun
ds = New Envelope aLayout.Page.GetPageBounds pPrinter, 0, 0, pPageBounds Dim hDc
As OLE_HANDLE hDc = pPrinter.StartPrinting(pPrintEnv, 0) Dim pActiveView As IAc
tiveView Set pActiveView = aLayout pActiveView.Output hDc, pPrinter.Resolution,
rectOut, pPageBounds, Nothing pPrinter.FinishPrinting MsgBox "Layout sent to " &
FileName, vbInformation, "Printing complete!" End Sub
Introduction to Programming ArcObjects with VBA Working with layout elements 13-
15
Exporting a layout
Variety of export formats
Adobe Acrobat (*.pdf) JPEG ArcPress
IArcPressExporter IExporter
Exporter
JpegExporter
PdfExporter
TiffExporter
ArcPres s Exporter
Ps Exporter
ArcPres s ExporterJPEG
ArcPres s Exporter TIFF
IExporter::StartExporting
Export the FocusMap or the PageLayout
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
13-16
Example: Exporting the layout as a jpeg
Private Sub Export(aLayout As IActiveView, aPath As String, DPI As Integer) Dim
rectOut As tagRECT rectOut = aLayout.exportFrame Dim pExporter As IExporter Set
pExporter = New JpegExporter Dim pEnv As IEnvelope Set pEnv = New Envelope pEnv.
PutCoords rectOut.Left, rectOut.Top, rectOut.Right, rectOut.bottom pExporter.Exp
ortFileName = aPath pExporter.PixelBounds = pEnv pExporter.Resolution = DPI Rec
alc the export frame to handle the increased number of pixels Set pEnv = pExport
er.PixelBounds Dim xMin As Double, yMin As Double, xMax As Double, yMax As Doubl
e pEnv.QueryCoords xMin, yMin, xMax, yMax rectOut.Left = xMin rectOut.Top = yMin
rectOut.Right = xMax rectOut.bottom = yMax Dim hDc As Long hDc = pExporter.Star
tExporting aLayout.Output hDc, DPI, rectOut, Nothing, Nothing pExporter.FinishEx
porting MsgBox "Export complete!", vbInformation End Sub
Introduction to Programming ArcObjects with VBA Working with layout elements 13-
16
Exercise 13 overview
Write code that adds an element to the layout Create a simple text element Refer
ence StyleGallery items Add a North Arrow to the layout Export the layout
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
13-17
Exercise 13: Work with layout elements In this exercise, you will write a sub pr
ocedure that adds an input element at a specified location on the page. You will
also use a function (that has been written for you) to retrieve an item from th
e StyleGallery. You will call these functions to 1) reference a north arrow from
the StyleGallery, then 2) add the north arrow and a new text element to the lay
out page. As a challenge step, you will work with some of the style and color se
lector dialogs.
Introduction to Programming ArcObjects with VBA
Working with layout elements 13-17
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
13-18
Introduction to Programming ArcObjects with VBA
Working with layout elements 13-18
Introduction to Programming ArcObjects with VBA
Using tools
Lesson overview Tool events Getting the user X and Y Display transformation Conv
ert display coordinates to map units Example: Rubberbanding IGraphicsContainer M
anaging Graphics Refreshing the display Partially refresh the display Exercise 1
4 overview: Choose one
14-6 14-7 14-8 14-9 14-10 14-11 14-12
contents
14-2 14-3 14-4 14-5
Using tools
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
Introduction to Programming ArcObjects with VBA
Using tools
14-1
Lesson overview
Tool events IDisplayTransformation Example tools: Display feedback and rubberban
ding IGraphicsContainer Refreshing the display Exercise: Choose a tool to create
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
14-2
Overview This lesson will discuss the use of UIToolControls in ArcMap. Tool cont
rols differ from buttons in that they allow for user interaction with the displa
y and therefore have many more events that can be coded, such as MouseUp, MouseD
own, MouseMove, and so on. Mouse clicks from a tool are returned in display coor
dinates (pixels). Because ArcMap tools are generally designed to get user input
on a map display, you will learn how to convert geometry returned from the mouse
into map units. Some common examples of the use of tools in ArcMap will be illu
strated in this lesson including panning and zooming, drawing, and providing a u
ser with display feedback.
Introduction to Programming ArcObjects with VBA
Using tools
14-2
Tool events
Tools have several event procedures Events for user interaction
Mouse events: MouseUp, MouseMove, MouseDown, DblClick Keyboard events: KeyUp, Ke
yDown
Events for controlling tool behavior
Enabled CursorID ToolTip Message
Close Visual Basic Editor window
Copyright © 2001–2004 ESRI. All rights reserved.
Built-In Cursors Built-In Cursors
Introduction to Programming ArcObjects with VBA
14-3
Because tools are designed to deal with a variety of sources of user input, they
have many more event procedures that can be coded. As a programmer, you have a
lot of control over obtaining user input. From the mouse, you can provide code f
or when the mouse moves, when the mouse button is pressed, when it is released,
and when it is double-clicked. You can see if the right or left mouse button is
clicked, whether or not the Shift key is held when it is clicked, as well as the
location of the mouse cursor. From the keyboard, you can provide code that exec
utes when a key is pressed and when it is released. You can also write logic bas
ed on which key is pressed. In addition to the events related to mouse and keybo
ard input, tools also provide some of the same button events that control appear
ance, such as Enabled, ToolTip, and Message. The CursorID event can be used to p
rovide a different mouse cursor when your tool is active. Use one of the built-i
n CursorIDs shown above, or use your own cursor using one of the methods illustr
ated below. Tools are in design mode while the Visual Basic Editor window is ope
n. Make sure the window is closed (not minimized) to ensure that all tool events
are fired properly.
Use an image on a UserForm in the project … Private Function UIToolControl1_Cur
sorID() As Variant Set UIToolControl1_CursorID = UserForm1.Image1.Picture End Fu
nction Load a file from disk (*.ico or *.cur) Private Function UIToolControl1_C
ursorID() As Variant Set UIToolControl1_CursorID = LoadPicture("c:\cursors\magni
fy.cur") End Function
Introduction to Programming ArcObjects with VBA
Using tools
14-3
Getting the user X and Y
Coordinates are passed into a Tool’s mouse events
MouseUp, MouseDown, MouseMove
Returns display units (pixels)
Private Sub UIToolControl1_MouseDown(ByVal button As Long, _ Private Sub UIToolC
ontrol1_MouseDown(ByVal button As Long, _ ByVal shift As Long, ByVal x As Long,
ByVal y As Long) ByVal shift As Long, ByVal x As Long, ByVal y As Long) MsgBox "
X = " & x MsgBox "X = " & x MsgBox "Y = " & y MsgBox "Y = " & y End Sub End Sub
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
14-4
Returning the current mouse position When a user interacts with your tool, the l
ocation of their mouse cursor is passed into several of the tool’s event procedu
res, such as MouseDown, MouseUp, and MouseMove. These coordinates are called x a
nd y in the parameter list (see the example above), and indicate the location of
the cursor in display units, called pixels (short for picture elements). Displa
y coordinates are radically different from the map coordinates used to measure g
eographic data. The size of a pixel will vary with the resolution of your monito
r, and the value of y increases as you move down from the origin (0,0), which is
in the upper-left of the display.
Introduction to Programming ArcObjects with VBA
Using tools
14-4
Display transformation
Transform coordinates between map and display units
ToMapPoint: Convert a display point (pixels) to a map point FromMapPoint: Conver
t a map point to a display point TransformCoords: Return map coordinates from a
set of display coordinates or vice versa
Using mouse input
Mouse clicks are captured in pixels GIS works in map coordinates
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
14-5
Because you will most often need the location of mouse interaction in map units
as opposed to display units, there are methods on the ArcMap display for creatin
g geometry in map coordinates from pixel locations. Use the DisplayTransformatio
n property on the IDisplay interface to access these methods. When converting co
ordinates from the display, the output map point will be in the current spatial
reference defined for your map.
Introduction to Programming ArcObjects with VBA
Using tools
14-5
Convert display coordinates to map units
Use IDisplayTransformation::ToMapPoint Returns a point in map units
Dim pMxApp As IMxApplication Set pMxApp = Application Dim pPnt As IPoint Set pPn
t = pMxApp.Display.DisplayTransformation.ToMapPoint(x, y) MsgBox "Longitude = "
& pPnt.x MsgBox "Latitude = " & pPnt.y
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
14-6
DisplayTransformation The DisplayTransformation object, which can be accessed fr
om the AppDisplay object, allows the conversion between display and map coordina
tes. The example above is typical for tool mouse event procedures that require m
ap coordinates. After using QueryInterface to access the IMxApplication interfac
e on the ArcMap Application object, code is chained together to first access the
AppDisplay (IMxApplication :: Display), then the DisplayTransformation (IDispla
y :: DisplayTransformation). The ToMapPoint method is called on the IDisplayTran
sformation interface, and the required x and y pixel coordinate arguments are pa
ssed in. A Point object is returned as a result of calling the method (IPoint).
Introduction to Programming ArcObjects with VBA
Using tools
14-6
Example: Rubberbanding
Declare module-level variable in General Declaration
Private m_pRubberBand As IRubberBand
Initialize in tool’s Select event
Set m_pRubberBand = New RubberLine or RubberPolygon or RubberEnvelope
Implement in tool’s MouseDown event Store returned geometry in an Object variabl
e
Set pLine = m_pRubberBand.TrackNew (pDisplay, pSymbol) or TrackExisting
IDisplayFeedback shows user interaction with geometry (Moving, resizing)
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming Arc
Objects with VBA
14-7
Working with tools Tool controls can implement several event procedures. To shar
e variables between these procedures, use module-level variables. Most often, mo
dule-level variables are initialized when the tool is initially selected, the Se
lect event procedure. While the Visual Basic Editor is open, tool controls are i
n design time mode. To properly capture your events and resolve run time errors,
completely close the Visual Basic Editor window and reselect your tool (fire th
e Select event to re-initialize module-level variables). IRubberBand properties
and methods The IRubberBand interface is implemented by several sub-classes of t
he abstract RubberBand class, such as: RubberEnvelope, RubberLine, RubberPoint,
and RubberPolygon. This common interface has the following methods for working w
ith a RubberBand object: • TrackExisting: Call to move or reshape an existing sh
ape • TrackNew: Call to rubberband a new shape When tracking a RubberBand object
, the geometry corresponding to the particular RubberBand coclass is returned (a
Line from a RubberLine, a Polygon from a RubberPolygon, etc.). Display Feedback
The DisplayFeedback objects are used to give users an interactive representatio
n of changes they are making on the display (before changes are actually made).
There are objects that can be used in this manner depending on the geometry and
functionality. All objects will implement IDisplayFeedback. See the ArcGIS Devel
oper Help for more information on Display Feedback.
Introduction to Programming ArcObjects with VBA
Using tools
14-7
IGraphicsContainer
Supported by Map and PageLayout
Also returned by IActiveView :: GraphicsContainer
Manage elements
AddElement, AddElements, DeleteElement, DeleteAllElements
IGraphicsContainer
MxDo c ume nt
Pag e Layo ut
Change display order
BringToFront, BringForward SendToBack, SendBackward PutElementOrder
Copyright © 2001–2004 ESRI. All rights reserved.
IGraphicsContainer
Map
*
Introduction to Programming ArcObjects with VBA
14-8
IGraphicsContainer interface The IGraphicsContainer interface has methods for wo
rking with elements in ArcMap. This is where you will find familiar graphic mana
gement methods such as SendToBack, BringToFront, AddElement, DeleteElement, and
so on. Remember that elements can be simple graphic elements such as text, shape
s, or pictures, and can also be frame elements that contain legends, scalebars,
or entire maps. IGraphicsContainer is supported by both the PageLayout and the M
ap class, which means you can work with map or layout elements by simply QI-ing
to IGraphicsContainer on either object. The code below shows an example of addin
g an element to the map.
DIM pGContainer As IGraphicsContainer Set pGContainer = pMxDoc.FocusMap pGContai
ner.AddElement pCompanyLogo
The GraphicsContainer can also be accessed as a property on the IActiveView inte
rface, which is also supported by both the Map and the PageLayout class. Use thi
s property to work with elements in whichever view your user has active. The cod
e below shows an example of adding an element to the Map or the PageLayout, depe
nding on which is currently being viewed.
pMxDoc.ActiveView.GraphicsContainer.AddElement pNewText
Introduction to Programming ArcObjects with VBA
Using tools
14-8
Managing graphics
Remove all elements from the Map –or- Layout Remove all elements from the Map
–or- Layout Set pMxDoc = ThisDocument Set pMxDoc = ThisDocument pMxDoc.ActiveVie
w.GraphicsContainer.DeleteAllElements pMxDoc.ActiveView.GraphicsContainer.Delete
AllElements pMxDoc.ActiveView.Refresh pMxDoc.ActiveView.Refresh Add an element
to the Layout Add an element to the Layout Set pMxDoc = ThisDocument Set pMxDoc
= ThisDocument Dim pGC As IGraphicsContainer Dim pGC As IGraphicsContainer Set
pGC = pMxDoc.PageLayout Set pGC = pMxDoc.PageLayout pGC.AddElement pElemArea, 0
pGC.AddElement pElemArea, 0 pMxDoc.ActiveView.Refresh pMxDoc.ActiveView.Refresh
Send selected graphics to the back on Layout Send selected graphics to the bac
k on Layout Dim pGCSelect As IGraphicsContainerSelect Dim pGCSelect As IGraphics
ContainerSelect Set pGCSelect = pGC ‘QI Set pGCSelect = pGC ‘QI pGC.SendToBack p
GCSelect.SelectedElements pGC.SendToBack pGCSelect.SelectedElements pMxDoc.Activ
eView.Refresh pMxDoc.ActiveView.Refresh
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming Arc
Objects with VBA
14-9
Adding graphics to a map The IGraphicsContainer interface adds elements (i.e., g
raphics) to a PageLayout. The Map class also supports the IGraphicsContainer int
erface. Many of the same graphic elements that you add to a layout (text, marker
s, polygons, etc.) can also be added directly to a Map. Adding an element to a M
ap is the same as adding one to a layout, except the geometry defining the eleme
nt’s position should be in map units rather than page units (e.g., inches).
Introduction to Programming ArcObjects with VBA
Using tools
14-9
Refreshing the display
IActiveView::Refresh
Redraws entire display (not the Table of Contents)
IScreenDisplay::Invalidate
Redraws a specified rectangle (envelope)
IMxDocument::UpdateContents
Notifies the document that its contents have changed Refreshes the Table of Cont
ents
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
14-10
Refreshing methods After modifying the ArcMap display, it may be necessary to re
fresh (redraw) the contents of the display or the document. In ArcObjects, you w
ill find a variety of ways to refresh; choose the method that is most appropriat
e for the situation. • IActiveView :: Refresh—call to redraw the entire display
area while in data (Map) or layout (PageLayout) view • IScreenDisplay :: Invalid
ate—call to redraw all layers and elements within a specified area (defined by p
assing in an Envelope object) • IMxDocument :: UpdateContents—call to redraw the
legends in the ArcMap Table of Contents
Introduction to Programming ArcObjects with VBA
Using tools 14-10
Partially refresh the display
You may need to refresh only a portion of the display
Area covered by a new graphic element More efficient than refreshing entire disp
lay
IActiveView::PartialRefresh
Use in Layout or Data view Specify what needs to be refreshed (e.g., graphics) S
pecify where to refresh (an envelope)
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
14-11
PartialRefresh PartialRefresh is a method on the IActiveView interface and can t
herefore be called on a Map or a PageLayout object. PartialRefresh is very simil
ar to IScreenDisplay::Invalidate in that it can be used to redraw only a specifi
ed area (envelope) of the display. PartialRefresh gives you more control, howeve
r, as it allows you to also specify what you want refreshed (geography, graphics
, selection, etc.). Using PartialRefresh is more efficient than redrawing everyt
hing on the entire display, especially for maps that contain a lot of data and g
raphics.
Introduction to Programming ArcObjects with VBA
Using tools 14-11
Exercise 14 overview: Choose one
14A – Create a tool to draw simple graphics
Transform a display point to a map point Add a new point graphic to the display
Change symbol color with a keystroke
14B – Make a Parcel Proximity tool to make a selection
Transform a display point to a map point Buffer the point (ITopologicalOperator)
Make a selection using spatial criteria (SpatialFilter) Display the selected pa
rcels
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
14-12
Exercise 14: Create a tool to draw point graphics In this exercise, you will hav
e a choice of creating one of two tools that allow the user to interact with the
map display. 14A—This exercise has you create a tool for interactively adding p
oint graphics to the display. You will allow the user to change the color of poi
nt symbols by pressing a key on the keyboard while the tool is active. You will
write code for the following UIToolControl event procedures: • Select • MouseUp
• MouseDown • MouseMove • KeyUp • KeyDown 14B—This exercise will have you create
a tool for making an interactive selection. You will buffer the user’s mouse cl
ick by a specified distance, then use the buffer polygon to select surrounding f
eatures (parcels). Although this exercise does not expose you to as many tool ev
ent procedures, it does get your hands on some new interfaces and objects, such
as: • ITopologicalOperator • SpatialReference • ISelectionEnvironment • ILinearU
nit
Introduction to Programming ArcObjects with VBA
Using tools 14-12
Introduction to Programming ArcObjects with VBA
Data management
Lesson overview Name objects Object Model overview: Name classes Creating a Data
setName Data manipulation objects Converting feature classes Exercise 15A overvi
ew Editing with a cursor Editing cursors Example: Updating misspelled attributes
Adding a field Creating a domain Adding a domain to a database Assigning a doma
in to a field Exercise 15B overview
15-4 15-5 15-6 15-7 15-8 15-9 15-10 15-12 15-13 15-14 15-15 15-16 15-17
contents
15-2 15-3
Data management
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
Introduction to Programming ArcObjects with VBA
Data management
15-1
Lesson overview
Using Name objects Converting data formats Editing with cursors
Update Insert
Adding fields to an existing dataset Creating and applying domains
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
15-2
Overview There are a variety of ways to manipulate existing data using ArcObject
s. In this lesson, you will learn … • How to use Name objects WorkspaceNames Dat
asetNames • How to convert feature classes and tables FeatureDataConverter Objec
tLoader • How to edit using a cursor Update Insert • How to add fields and domai
ns
Introduction to Programming ArcObjects with VBA
Data management
15-2
Name objects
Names are placeholders for the objects they represent
A lightweight version Limited number of methods and properties available Use INa
me::Open to instantiate the object represented
Use to represent new or existing datasets, workspaces, relationship classes, etc
. Used …
For quickly browsing workspace contents As input arguments for data conversion
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
15-3
Name dropping An ArcObject Name object is a lightweight representation of an obj
ect. By working with Name objects, you have access to some of the basic properti
es of the represented object, without having to carry the overhead of having the
entire object in memory. If you eventually need the actual object represented b
y a Name object, you can use the Name to obtain it. As an analogy, your business
card is like a Name object that represents you; someone who has your business c
ard can obtain basic information about you, such as your e-mail address and phon
e number. If that person needs you, he or she can e-mail or call you to obtain t
he actual object represented by your card (you). If your application needs to se
arch the contents of an entire workspace to find a particular dataset, for examp
le, it is much more efficient to search the dataset Names. Once the desired data
set Name is located, the dataset itself can be hydrated from the Name. Obviously
, for superficial tasks, it is more efficient to work with a Name in your code a
s opposed to the full object. You can use Name objects for things such as Tables
, FeatureClasses, and Workspaces.
Introduction to Programming ArcObjects with VBA
Data management
15-3
Object Model overview: Name classes
Name Not all Name subtypes Not all Name subtypes are shown here are shown here
WorkspaceName
DatasetName
FeatureDatasetName RelationshipClassName
TinName
TableName
RasterDatasetName
FeatureClassName
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
15-4
Name is an abstract class that has several creatable subtypes. There are Name ob
jects used to represent workspaces, IMS services, or any of the various types of
datasets. Names can be created to represent workspaces or datasets that you are
creating, or may be instantiated from other objects to represent existing objec
ts. A Workspace, for example, can be used to access an enum of DatasetNames for
all the data that it contains. An important aspect of working with Name objects
is the fact that they can be used to obtain the actual object represented. To ac
cess the object from any subtype of Name, use the Open method, which is defined
on the IName interface. Example: Searching for a particular DatasetName, then op
ening its dataset
Public Sub OpenCities() Dim pWSFactory As IWorkspaceFactory Dim pWS As IWorkspac
e Dim pEnumDSNames As IEnumDatasetName Dim pDSName As IDatasetName Dim pCities A
s IFeatureClass Set pWSFactory = New ShapefileWorkspaceFactory Set pWS = pWSFact
ory.OpenFromFile("C:\Student\IPAO\Data\Africa", Application.hWnd) Set pEnumDSNam
es = pWS.DatasetNames(esriDTFeatureClass) Set pDSName = pEnumDSNames.Next Do Unt
il pDSName Is Nothing If pDSName.Name = "AfricanCities" Then Dim pName As IName
Set pName = pDSName --- QueryInterface Set pCities = pName.Open Exit Do End If
Set pDSName = pEnumDSNames.Next Loop End Sub Introduction to Programming ArcObj
ects with VBA Data management 15-4
Creating a DatasetName
Many creatable CoClasses Specify the workspace
Use a WorkspaceName object
Specify the filename
New or existing
Create a new FeatureClassName Create a new FeatureClassName Dim pFCName As IDa
taSetName Dim pFCName As IDataSetName Set pFCName = New FeatureClassName Set pFC
Name = New FeatureClassName Identify its workspace Identify its workspace Set
pFCName.WorkspaceName = pWSName Set pFCName.WorkspaceName = pWSName Identify it
s filename Identify its filename pFCName.Name = "States.shp" pFCName.Name = "St
ates.shp"
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming Arc
Objects with VBA
15-5
Working with DatasetNames A common use of Name objects is to specify that a new
dataset be created on disk. The required input and output dataset arguments for
data conversion, for example, are satisfied using DatasetName objects rather tha
n full Dataset objects. Because each of the subtypes of DatasetName are coclasse
s, they can be created using the New keyword. Once created, properties of the Na
me can be set in order to represent a dataset on disk. Example If writing code t
o create a new table called PoisonFrogs.dbf in the (new) folder C:\Madagascar\Da
ta, you would write code such as the following:
Dim pShapeWSFactory As IWorkspaceFactory Dim pWorkName As IWorkspaceName Dim p
TableName As IDatasetName a Name to represent the workspace a Name to represen
t the table
** The code below returns a WorkspaceName, not a Workspace Set pShapeWSFactory
= New ShapefileWorkspaceFactory Set pWorkName = pShapeWSFactory.Create ("C:\Mada
gascar", "Data",_ Nothing, Application.hWnd) ** co-create a new TableName, set
its properties Set pTableName = New TableName Set pTableName.WorkspaceName = pWo
rkName pTableName.Name = "PoisonFrogs.dbf"
Introduction to Programming ArcObjects with VBA
Data management
15-5
Data manipulation objects
FeatureDataConverter, ExportOperation
Convert between coverage, shapefile, and geodatabase
ObjectLoader
Appends data to an existing feature class or table
Related objects
FieldChecker: Identifies problems with field names EnumInvalidObject: An enum of
features that were invalid during conversion or loading
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
15-6
Convert, export, load FeatureDataConverter is a coclass that can convert feature
classes, feature datasets, or tables to new output datasets. Use a FeatureDataC
onverter object to convert individual feature classes and tables, or even entire
feature datasets (e.g., ArcInfo coverages). The FeatureDataConverter object let
s you convert data between geodatabases, shapefiles, and coverages. Most types o
f feature data are currently supported (except for annotation). FeatureDataConve
rter is suitable for loading large amounts of data. When importing to a geodatab
ase, you can specify an interval for committing data; you can also specify an Ar
cSDE configuration keyword to control specific storage parameters for an ArcSDE
geodatabase. ExportOperation is a coclass that can be used to export a feature c
lass or a table. The ExportOperation coclass offers similar functionality to the
feature data converter but in a simplified form. It corresponds to the export d
ata function available in ArcMap by right-clicking on a layer in the Table of Co
ntents. ObjectLoader is used to append records from one table (or feature class)
to another. The IObjectLoader interface contains a single method, LoadObjects.
Validating fields and records A FieldChecker object can be used to validate a fi
elds collection. This can be especially useful when converting data between form
ats, as some datasets might contain field names that are illegal in other format
s. A FieldChecker will produce a new fields collection with standard fixes for i
nvalid fields it encounters (by adding an underscore to the field name, for exam
ple, UID_). The FieldChecker will provide standard names for geometry and OID fi
elds when converting to geodatabase format (Shape and OBJECTID). When loading or
converting features using the ObjectLoader or FeatureDataConverter, an enum of
invalid objects is returned (IEnumInvalidObject). Using this enum, a programmer
can easily see which objects (rows or features) could not be loaded or converted
.
Introduction to Programming ArcObjects with VBA
Data management
15-6
Converting feature classes
IFeatureDataConverter::ConvertFeatureClass
Converts an input feature class to a new output
Required arguments
Input and output FeatureClassNames Output FeatureDatasetName A QueryFilter
Create a new FeatureDataConverter object Several Others … Create a new Feature
DataConverter object Dim Dim Set Set pFDConvert pFDConvert pFDConvert pFDConvert
As IFeatureDataConverter As IFeatureDataConverter = New FeatureDataConverter =
New FeatureDataConverter
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
15-7
Using the FeatureDataConverter The FeatureDataConverter object allows a programm
er to export feature classes, tables, or feature datasets to a new output (of th
e same or different format). FeatureDataConverter is a coclass, so it can be cre
ated with the new keyword. Using the IFeatureDataConverter interface, you can ca
ll one of three methods to convert data: ConvertFeatureClass, ConvertFeatureData
set, or ConvertTable. Use the IFeatureProgress interface to track the progress o
f a conversion. Below is a description of the required arguments for IFeatureDat
aConverter :: ConvertFeatureClass. • InputDatasetName: IFeatureClassName—a Name
object that specifies the feature class to be converted. • InputQueryFilter: IQu
eryFilter—a QueryFilter object used to define a subset of features to be convert
ed. • outputFDatasetName: IFeatureDatasetName—a Name object that defines the (ne
w or existing) feature dataset into which the converted feature class will be wr
itten. • outputFClassName: IFeatureClassName—a Name object that defines the new
output feature class. • OutputGeometryDef: IGeometryDef—a GeometryDef object tha
t defines the spatial reference for the output feature class. If Nothing is used
for this argument, the spatial reference of the output feature dataset or the i
nput feature class will be used. • OutputFields: IFields—a fields collection for
the output feature class. If simply exporting a feature class to the same forma
t, the fields collection from the input feature class can be used. If exporting
between formats, it is a good idea to use a FieldChecker object to make sure the
fields are valid for the output format. • configKey: String—a string that speci
fies an ArcSDE configuration keyword. • FlushInterval: Long—an integer that spec
ifies the interval for committing features to the new feature class (when export
ing to geodatabase). • parentHWnd: Long—an integer specifying the application’s
window handle (you will usually use Application.hWnd to satisfy this argument).
IFeatureDataConverter :: ConvertFeatureClass returns IEnumInvalidObject, which i
s an enum of all features that could not be converted.
Introduction to Programming ArcObjects with VBA Data management 15-7
Exercise 15A overview
Convert an ArcInfo coverage to a Personal Geodatabase
IFeatureDataConversion :: ConvertFeatureClass
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
15-8
Introduction to Programming ArcObjects with VBA
Data management
15-8
Editing with a cursor
Update and Insert Cursors Faster than using ITable::CreateRow, ITable::Store
Much more efficient for large datasets
Use to add, delete, or modify rows or features
ICursor::InsertRow (IFeatureCursor::InsertFeature) ICursor::DeleteRow (IFeatureC
ursor::DeleteFeature) ICursor::UpdateRow (IFeatureCursor::UpdateFeature)
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
15-9
Using a cursor to edit records You have already learned to create records (rows
or features) using methods such as CreateRow and CreateFeature. You have learned
to change field values by setting properties such as Value and Shape, and to co
mmit your edits by calling the Store method. Although the above steps work fine
for editing a table or feature class, you may find it much more efficient to use
a cursor or feature cursor, particularly when editing a large number of records
; you can expect a cursor to perform the edits as much as 2,000 times faster.
Introduction to Programming ArcObjects with VBA
Data management
15-9
Editing cursors
Determined by the method used to return the cursor Update cursor
Update method
Dim pCursor As IFeatureCursor Dim pCursor As IFeatureCursor Set pCursor = pFClas
s.Update(pQFilter, False) Set pCursor = pFClass.Update(pQFilter, False)
Use to update or delete records in the database
Insert cursor
Insert method
Dim pCursor As IFeatureCursor Dim pCursor As IFeatureCursor Set pCursor = pFClas
s.Insert(True) Set pCursor = pFClass.Insert(True)
Use to insert new records into the database
Search cursor
Search method
Dim pCursor As IFeatureCursor Dim pCursor As IFeatureCursor Set pCursor = pFClas
s.Search(pQFilter, True) Set pCursor = pFClass.Search(pQFilter, True)
Use for read-only analysis of a record subset
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
15-10
Types of cursors There are three types of cursor objects that can be obtained fr
om a Table or FeatureClass. The type of cursor returned depends solely on the me
thod that was used to create it. As a programmer using one of these cursors, you
need to be mindful of the type of cursor you create and make sure that it is su
ited to your purpose. Each cursor type will have the same available interfaces (
e.g., ICursor, IFeatureCursor) with the same methods and properties available. C
alling some of these methods with the wrong type of cursor, however, will return
an error. Update cursor Update cursors are created by calling the Update method
on a Table or FeatureClass. An Update cursor is used to update or delete record
s in the database from which the cursor was created (Table or FeatureClass). Lik
e Search cursors, Update cursors are created with a QueryFilter object, giving y
ou the ability to store a subset of records in the returned cursor (or all recor
ds by using the Nothing keyword). If you create a cursor as an Update cursor, yo
u should not try to call the InsertRow (InsertFeature) method. This method only
works on an Insert cursor. Insert cursor Insert cursors are created by (you gues
sed it) using the Insert method on a Table or a FeatureClass. Use an Insert curs
or to insert new records into the database from which the cursor was created (Ro
ws in a Table or Features in a FeatureClass). Unlike Search and Update cursors,
the Insert method does not take a QueryFilter as a parameter. Insert cursors do
not support the NextRow (NextFeature) method, nor the UpdateRow method.
Introduction to Programming ArcObjects with VBA
Data management 15-10
Search cursor Search cursors have already been described. These cursors are crea
ted by calling the Search method on a Table or FeatureClass and are used to carr
y out operations that do not require write access to the records. Search cursors
are generally used for tasks such as calculating a statistic for a subset of re
cords (e.g, find the average value for commercially zoned lots), obtaining a cou
nt (e.g., the number of records with a value greater than 1,000), or for display
(e.g., drawing temporary buffers around all vacant lots). Search cursors are cr
eated with a QueryFilter, giving you the ability to store a subset of records in
the cursor (or all records by using the Nothing keyword). If you create a curso
r as a Search cursor, you will not be able to call methods such as InsertRow, De
leteRow, or UpdateRow (they will be available but will return an automation/unsp
ecified error). The only method you will use on a Search cursor is NextRow (Next
Feature) to access each record in the cursor.
Introduction to Programming ArcObjects with VBA
Data management 15-11
Example: Updating misspelled attributes
Dim pQFilt As IQueryFilter Set pQFilt = New QueryFilter pQFilt.WhereClause = "St
ateName = ‘newmexico’" Dim pUpCursor As IFeatureCursor Set pUpCursor = pFClass.U
pdate(pQFilt, False) Only "newmexico" Dim pFeature As IFeature Set pFeature = pU
pCursor.NextFeature Do Until pFeature Is Nothing pFeature.Value(3) = "New Mexico
" Fix misspelling pUpCursor.UpdateFeature pFeature Update the record Set pFeat
ure = pUpCursor.NextFeature Move to the next Loop MsgBox "Features have been up
dated"
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
15-12
Example: Updating records with a cursor When producing an update cursor, you can
specify a query filter to restrict the records returned. In the example, the qu
ery filter is used to make a subset of misspelled records. Remember: to access a
ll records inside a cursor, you need to use a Do While or a Do Until loop. Befor
e entering the loop, the first feature is pulled out of the FeatureCursor (pFCur
sor.NextFeature) and stored in a variable (pFeature). The loop will then check t
o see if pFeature is Nothing, and until it is, the loop will continue to execute
. If, at this point, your FeatureCursor had no records (i.e., nothing met the se
arch criteria) the first object retrieved from the cursor would be Nothing, and
therefore the body of the loop would never be executed. Inside the loop, a new v
alue is written to the feature’s fourth field (presumably, the StateName field).
The dataset is then updated by calling the UpdateFeature method on the cursor.
The next feature is again pulled from the cursor by calling the NextFeature meth
od. Once the loop is complete, a message box is displayed telling the user that
features were successfully updated.
Introduction to Programming ArcObjects with VBA
Data management 15-12
Adding a field
ITable::AddField to add a field to an existing dataset
Do not add a field to the Fields collection
Use an Update Cursor to calculate values for the field
Dim pAverageFld As IFieldEdit Dim pAverageFld As IFieldEdit Set pAverageFld = Ne
w Field Set pAverageFld = New Field With pAverageFld With pAverageFld .Name = "A
verage" .Name = "Average" .Type = esriFieldTypeInteger .Type = esriFieldTypeInte
ger .AliasName = "Average Income" .AliasName = "Average Income" .Length = 16 .Le
ngth = 16 End With End With pTable.AddField pAverageFld pTable.AddField pAverage
Fld
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
15-13
Adding a new field to an existing table or feature class When producing fields f
or a new table or feature class, a programmer can simply make a new field, set i
ts properties, then add it to the Fields collection. The process for creating a
new field in an existing dataset is similar, except there is no need to deal wit
h the Fields collection. After making a new field (using the New keyword) and se
tting its properties, simply call the AddField method on ITable or IFeatureClass
, passing in the new Field object as the required argument. After adding a field
to an existing dataset, the most efficient way to calculate its values is by us
ing an update cursor.
Introduction to Programming ArcObjects with VBA
Data management 15-13
Creating a domain
Domain is an abstract class with two creatable subtypes
RangeDomain: Minimum and maximum values CodedValueDomain: List of appropriate va
lues
Dim pRDomain As IRangeDomain Dim pRDomain As IRangeDomain Dim pDomain As IDomain
Dim pDomain As IDomain Set pRDomain = New RangeDomain CoClass Set pRDomain = N
ew RangeDomain CoClass Set pDomain = pRDomain QueryInterface Set pDomain = pRD
omain QueryInterface pRDomain.MinValue = 0 pRDomain.MinValue = 0 pRDomain.MaxVa
lue = 200 pRDomain.MaxValue = 200 pDomain.Name = "Diameter" pDomain.Name = "Diam
eter" pDomain.FieldType = esriFieldTypeInteger pDomain.FieldType = esriFieldType
Integer
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
15-14
Making a new range or coded value domain In ArcGIS, attribute domains can be use
d with geodatabase tables or feature classes to enforce appropriate values for a
n attribute. Domains are defined at the geodatabase level, and can be applied to
any number of fields in any of that geodatabase’s tables. Domain is an abstract
class that has two creatable subtypes: RangeDomain and CodedValueDomain. Use th
e RangeDomain object to define a range of acceptable values (minimum and maximum
) for a numeric attribute, and a CodedValueDomain object to define a finite list
of acceptable (string or numeric) values. For any Domain that you create, you w
ill need to specify the type of field it is designed for. If, for example, you c
reate a domain for integer fields (esriFieldTypeInteger), it will not be availab
le for use with a field defined as double data type.
Introduction to Programming ArcObjects with VBA
Data management 15-14
Adding a domain to a database
Domains must live in a geodatabase
Add to the database before assigning it to a field IWorkspaceDomains::AddDomain
Dim pAccessFact As IWorkspaceFactory Dim pAccessFact As IWorkspaceFactory Dim pG
DBWorkspace As IWorkspace Dim pGDBWorkspace As IWorkspace Set pAccessFact = New
AccessWorkspaceFactory Set pAccessFact = New AccessWorkspaceFactory Set pGDBWork
space = pAccessFact.OpenFromFile("C:\City.mdb", 0) Set pGDBWorkspace = pAccessFa
ct.OpenFromFile("C:\City.mdb", 0) Dim pWSDomains As IWorkspaceDomains Dim pWSDom
ains As IWorkspaceDomains Set pWSDomains = pGDBWorkspace Set pWSDomains = pGDBWo
rkspace pWSDomains.AddDomain pRDomain pWSDomains.AddDomain pRDomain QueryInterf
ace QueryInterface Add the range domain Add the range domain
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
15-15
Adding a domain to a geodatabase After creating a domain, you cannot simply appl
y it to a field. Domains must be associated with a geodatabase. After a domain i
s added to a geodatabase, it can then be applied to any number of fields that ex
ist in any of the geodatabase’s tables or feature classes (assuming the field is
of the right data type). To add a domain to a geodatabase, use the AddDomain me
thod on the IWorkspaceDomains interface, as shown in the example above. Note: do
mains cannot be used for shapefile or ArcInfo coverage data.
Introduction to Programming ArcObjects with VBA
Data management 15-15
Assigning a domain to a field
IFieldEdit::Domain property
Dim pAverageFld As IFieldEdit Dim pAverageFld As IFieldEdit Set pAverageFld = Ne
w Field Set pAverageFld = New Field With pAverageFld With pAverageFld .Name = "A
verage" .Name = "Average" .Type = esriFieldTypeInteger .Type = esriFieldTypeInte
ger .AliasName = "Average Income" .AliasName = "Average Income" .Length = 16 .Le
ngth = 16 Set .Domain = pRDomain Put by Ref Set .Domain = pRDomain Put by Ref
End With End With pTable.AddField pAverageFld pTable.AddField pAverageFld
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
15-16
Use the Domain property on IFieldEdit to assign a Domain object to a particular
field. Because this property is a property put by reference, (1) the use of the
Set keyword is required, and (2) any change in the domain will be immediately re
flected by the field to which it was assigned. A single domain can be reused by
any number of fields in a geodatabase. Remember that a domain can only be used a
fter it has been added to a geodatabase. If, in the example above, pRDomain was
not first added to the appropriate geodatabase, the code would not return an err
or. Instead, the domain simply would not be enforced.
Introduction to Programming ArcObjects with VBA
Data management 15-16
Exercise 15B overview
Load data using a cursor
IFeatureCursor :: InsertFeature
Add a new field to an existing table Calculate values for a field using a cursor
IFeatureCursor :: UpdateFeature
Create and apply an attribute domain
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
15-17
In this exercise, you will work with the ArcObjects discussed in this lesson rel
ated to data manipulation. You will write code to: • convert data from one forma
t to another • add and edit features using a cursor • add a field to an existing
dataset • create and apply an attribute domain for a geodatabase table
Introduction to Programming ArcObjects with VBA
Data management 15-17
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
15-18
Introduction to Programming ArcObjects with VBA
Data management 15-18
Introduction to Programming ArcObjects with VBA
Application framework and events
Lesson overview Customizing the user interface CommandBars class Types of Comman
dBar objects Components of CommandBar: CommandItems Finding a CommandItem Findin
g an ArcGIS toolbar or menu Document events Example: Displaying a different cont
ext menu Displaying a new shortcut menu Creating new menus Creating commands to
execute macros Updating the ArcID module Lesson overview 16-6 16-7 16-8 16-9 16-
10 16-11 16-12 16-13 16-14 16-15
contents
16-2 16-3 16-4 16-5
Inbound and outbound interfaces Finding outbound interfaces Using an outbound in
terface Events supported by Map Capturing object events Coding object events Exe
rcise 16 overview
16-16 16-17 16-18 16-19 16-20 16-21 16-22
Application framework and events
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
Introduction to Programming ArcObjects with VBA
Application framework and ArcObjects events
16-1
Lesson overview
Programming the user interface
Commandbars collection Displaying existing toolbars and menus Programmatically a
dding controls
Understanding Events
Inbound and outbound interfaces Finding outbound interfaces and events Capturing
ArcObjects Events
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
16-2
Application framework and ArcObjects events One of the first things you learned
in this course was how to modify the user interface using the VBA Customize dial
og box. In this lesson, you will learn how to perform many of the Customize dial
og tasks (adding and removing commands, creating new toolbars, changing command
properties) using Visual Basic code. This section will cover: • The CommandBars
collection • Creating new CommandBars (toolbars, menus, and context menus) • Cre
ating new commands (CommandItems) • Creating and controlling the display of cont
ext menus In the later half, you will learn how to capture and code ArcObjects e
vents. You have already written code for object events, such as events on forms
and controls, and even some ArcObjects events such as the MxDocument events avai
lable in the ThisDocument module.
Introduction to Programming ArcObjects with VBA
Application framework and ArcObjects events
16-2
Customizing the user interface
Programmatically customize interface
This lesson Dynamically change the user interface with code Execute a series of
existing commands in batch
Use drag-and-drop with Customize dialog box
Lesson 2 Static changes persisted in document Similar to Design mode in Visual B
asic
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
16-3
The easiest way to modify the user interface is, of course, to use the Customize
dialog box. There may be times, however, when you need to dynamically alter the
user interface programmatically. Using code, you can add and remove controls, c
hange their properties, and create your own toolbars, menus, and pop-ups. You ca
n also run existing ArcGIS commands using a single line of code. Examples of whe
n you might want to modify the interface with code: • Automatically add a contro
l for calculating property values when a parcel layer is added to the map. • Sho
w a custom pop-up menu that lists the attributes for the feature that was clicke
d on. If a feature was not clicked, show the default ArcMap pop-up. • Enable a s
et of editing tools only if the user provides the proper password. • Add and rem
ove custom layout-related commands when the user switches between data and layou
t view.
Introduction to Programming ArcObjects with VBA
Application framework and ArcObjects events
16-3
CommandBars class
Collection of all CommandBars
ArcMap or ArcCatalog toolbars and menus Custom toolbars and menus
IDocument::CommandBars
Returns the CommandBars collection
Use to create a CommandBar
ICommandBars::Create
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
16-4
CommandBars The CommandBars object is a collection of all the command bars (tool
bars, menus, and popups) available to a document. Use IDocument::CommandBars to
get a reference to the CommandBars collection. The ICommandBars interface is the
only interface supported by the CommandBars class. Use ICommandBars::Create to
make a new command bar and ICommandBars::Find to locate a particular command (Co
mmandItem) in the collection.
Introduction to Programming ArcObjects with VBA
Application framework and ArcObjects events
16-4
Types of CommandBar objects
Toolbar
Can be docked or undocked
Menu
Must be contained by another CommandBar
Pop-up menus
Free floating
Toolbar Toolbar Menus Menus Shortcut menu Shortcut menu
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
16-5
Types of CommandBars The CommandBars object is composed of ( ) several (*) Comma
ndBar objects. New command bars can be created from the CommandBars object. Ther
e are three different types of CommanBars available on the ArcMap or ArcCatalog
user interface: • Toolbars—a collection of/container for commands, such as butto
ns, tools, combo boxes, and so on. Toolbars can also contain menus, which are an
other type of CommandBar. • Menus—a collection of/container for commands. Menus
cannot contain tools (which require mouse input), edit boxes, or combo boxes. Un
like toolbars and pop-up menus (context or shortcut menus), menus must be contai
ned by a toolbar or by another menu (e.g., as a sub-menu). • Pop-up menus—identi
cal to menus (described above), with the exception that they are free-floating (
i.e., are not contained by another toolbar or menu). Pop-up menus are displayed
when a user right-clicks his or her mouse.
Introduction to Programming ArcObjects with VBA
Application framework and ArcObjects events
16-5
Components of CommandBar: CommandItems
CommandItems
Commands, macros, UI controls
Command
MacroItem
UIControl
COM Command
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
16-6
Components of a CommandBar A CommandBar object is composed of CommandItems. Comm
andItems are things such as buttons, tools, combo boxes, and edit boxes that app
ear graphically on the user interface. Notice from the simplified diagram above
that a CommandItem is composed of a single Command object. You can conceptualize
a command as the actual code behind a CommandItem. The ICommandItem interface l
ets you get or set the properties such as Caption, Image, Message, ToolTip, Disp
lay Style, and Help Context ID. This interface also provides methods to execute,
delete, refresh, or reset a particular CommandItem. Use either ICommandBars::Fi
nd or ICommandBar::Find to obtain a reference to a particular CommandItem.
Introduction to Programming ArcObjects with VBA
Application framework and ArcObjects events
16-6
Finding a CommandItem
ArcID module returns UID for all ESRI command items
Items are organized by Category_CommandName
Dim pCommandItem As ICommandItem Set pCommandItem = ThisDocument.CommandBars.Fin
d _ (ArcID.File_AddData)
pCommandItem.Execute
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
16-7
Use the Find method on ICommandBars to return any CommandItem (or CommandBar) av
ailable in the current document. The Find method locates a CommandItem using a U
ID (Unique Identifier), which is a long alphanumeric string stored in your opera
ting system’s registry. Here is the UID for the New Map command: {119591DB-0255-
11D2-8D20080009EE4E51}. Once a CommandItem is located using Find, its code can b
e executed by calling the Execute method (on the ICommandItem interface). Using
the ArcID module Rather than having to locate these unique identifiers, an ArcOb
ject programmer can use the ArcID module (available in the Normal.mxt and Normal
.gxt templates) to look up the required UID using a name that identifies a parti
cular command. The names used by the ArcID module are generally the name of the
command category, followed by the name of the command itself (e.g., File_AddData
).
Introduction to Programming ArcObjects with VBA
Application framework and ArcObjects events
16-7
Finding an ArcGIS toolbar or menu
The CommandBar class implements ICommandItem
Use ArcID module to find a CommandBar
ICommandBar::Dock (dockflags, [referenceBar])
Dockflags: Floating, docked, hidden, etc. [referenceBar]: (optional) Place relat
ive to another bar
Dim pTools As ICommandItem Dim pTools As ICommandItem Set pTools = ThisDocument.
CommandBars.Find _ Set pTools = ThisDocument.CommandBars.Find _ (ArcID.Tools_Too
lbar) (ArcID.Tools_Toolbar) Dim pToolBar As ICommandBar Dim pToolBar As ICommand
Bar Set pToolBar = pTools QI Set pToolBar = pTools QI pToolBar.Dock esriDockHi
de pToolBar.Dock esriDockHide Others: esriDockShow, esriDockToggle, esriDockFlo
at Others: esriDockShow, esriDockToggle, esriDockFloat ReferenceBar locations:
Left, Right, Top, Bottom ReferenceBar locations: Left, Right, Top, Bottom
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming Arc
Objects with VBA
16-8
Finding a CommandBar Because the CommandBar class implements the ICommandItem in
terface, an ArcObjects programmer can use the Find method (described earlier for
locating individual commands) to return entire toolbars, menus, or pop-ups. Use
the ArcID module to locate the unique identifier (UID) for a particular toolbar
, as shown in the example above. Controlling toolbar display Call the Dock metho
d on the ICommandBar interface to place a command bar in a specified location, o
r have it be free-floating. The esriDockFlags constants specify whether a comman
d bar is visible or floating and where it should be docked on the application wi
ndow. Optionally, you can specify another toolbar relative to which the toolbar
should be docked. Example: open the Tools toolbar, dock it next to the Editor to
olbar
Public Sub DockToolsToolbar () Dim pToolsBar As ICommandBar Dim pEditBar As ICom
madBar Set pToolsBar = ThisDocument.CommandBars.Find(ArcID.Tools_Toolbar) Set pE
ditBar = _ ThisDocument.CommandBars.Find(ArcID.Editor_EditorToolbar) pToolsBar.D
ock esriDockShow, pEditBar End Sub
Introduction to Programming ArcObjects with VBA
Application framework and ArcObjects events
16-8
Document events
Use to dynamically alter the interface
Add or remove toolbars according to map contents ActiveViewChanged, MapsChanged,
OpenDocument, etc.
OnContextMenu
Fires when the user right-clicks on screen display Code can display a different
context (popup) menu
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
16-9
Document events may be used to trigger changes to the user interface. For exampl
e, perhaps you want to add or remove controls when your user switches between da
ta and layout view, or maybe add a particular toolbar when a specific data frame
is activated. In addition to the document events you are already familiar with,
such as Open, Close, and New, there is a document event that fires when a user
right-clicks on the display. The OnContextMenu event procedure can be used to pr
ovide logic that dictates which context (popup) menu should be displayed.
Introduction to Programming ArcObjects with VBA
Application framework and ArcObjects events
16-9
Example: Displaying a different context menu
The location clicked (in pixels) The location clicked (in pixels)
Private Function MxDocument_OnContextMenu _ Private Function MxDocument_OnContex
tMenu _ (ByVal X As Long, ByVal Y As Long) As Boolean (ByVal X As Long, ByVal Y
As Long) As Boolean Dim pMenu As ICommandBar Dim pMenu As ICommandBar Set pMenu
= ThisDocument _ Set pMenu = ThisDocument _ CommandBars.Find(ArcID.View_Menu) Co
mmandBars.Find(ArcID.View_Menu) If (m_pMxDoc.FocusMap.Name = "Logan") Then If (m
_pMxDoc.FocusMap.Name = "Logan") Then pMenu.Popup Use Popup to show the context
menu pMenu.Popup Use Popup to show the context menu MxDocument_OnContextMenu =
True MxDocument_OnContextMenu = True Else Else MxDocument_OnContextMenu = False
MxDocument_OnContextMenu = False End If True = the event was handled here End I
f True = the event was handled here End Function End Function
Copyright © 2001–2004 ESRI. All rights reserved.
False = let ArcMap display its menu False = let ArcMap display its menu
Introduction to Programming ArcObjects with VBA
16-10
Dynamically changing the pop-up menu To control which pop-up (i.e., context) men
u is displayed when a user right-clicks on the map display, you must add logic t
o the MxDocument_OnContextMenu event procedure. This event fires when the displa
y is right-clicked with the mouse and before a menu is displayed. The OnContextM
enu event has two parameters that are passed in: the x- and y-coordinates (in di
splay units) where the mouse was right-clicked. As a programmer, you could use t
hese coordinates to see where (or what) the user clicked. Using this information
, you might choose to display different menus according to the type of feature t
hat was clicked. The event procedure returns a Boolean result. If you handle the
event (display a different popup), you must return True to prevent ArcMap from
also trying to display a pop-up. Returning False signals ArcMap to display the s
tandard context menu. The example The code above will fire when the map is right
-clicked by the user. The ArcMap View menu will be popped up when the name of th
e activated data frame is ‘Logan’; otherwise, the default pop-up menu will be di
splayed.
Introduction to Programming ArcObjects with VBA
Application framework and ArcObjects events 16-10
Displaying a new shortcut menu
CommandBars object can create a new CommandBar
Set aNewCBar = aCommandBars.Create (aNameString, aTypeConstant) Set aNewCBar = a
CommandBars.Create (aNameString, aTypeConstant)
Use CommandBar::Add to add menu choices
Dim Dim Set Set pMnu As ICommandBar pMnu As ICommandBar pMnu = ThisDocument _ pM
nu = ThisDocument _ CommandBars.Create("New",esriCmdBarTypeShortcutMenu) Command
Bars.Create("New",esriCmdBarTypeShortcutMenu)
pMnu.Add ArcID.File_AddData Add the ArcMap "Add Data" command pMnu.Add ArcID.Fi
le_AddData Add the ArcMap "Add Data" command pMnu.Popup Display the new contex
t menu pMnu.Popup Display the new context menu MxDocument_OnContextMenu = True
Tell ArcMap not to popup a MxDocument_OnContextMenu = True Tell ArcMap not to
popup a menu menu
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
16-11
Creating new shortcut menus The CommandBars collection can be used to produce ne
w CommandBar objects by calling the Create method. The Create method has two arg
uments: the name of the new CommandBar, and the type (toolbar, menu, or shortcut
menu). The example above creates a new shortcut menu called New. Although the n
ame for a shortcut menu will never be seen by the user (as it will for a toolbar
or menu), it is still a required parameter for the sake of consistency. Adding
CommandItems to a CommandBar The ICommandBar interface uses the Add method to pl
ace CommandItems on a CommandBar. The Add method has one required argument: a UI
D that identifies the CommandItem to add. Optionally, an index indicating the po
sition of the command can also be specified. If no index is given, the new comma
nd will be added to the end (or bottom) of the CommandBar. In the example above,
the ArcID module is used to reference the Add Data command. This item is then a
dded to the shortcut menu. Notice that the properties (such as the icon and labe
l) are already set for this command.
Introduction to Programming ArcObjects with VBA
Application framework and ArcObjects events 16-11
Creating new menus
Menus are created by a CommandBar
Menus must reside on an existing CommandBar
Dim pSubMenu Dim pSubMenu Set pSubMenu Set pSubMenu pSubMenu.Add pSubMenu.Add pM
nu.Popup pMnu.Popup
As ICommandBar As ICommandBar = pMnu.CreateMenu("Sub") = pMnu.CreateMenu("Sub")
ArcID.Help_About ArcID.Help_About Display the new context menu Display the new
context menu
MxDocument_OnContextMenu = True Tell ArcMap not to popup a MxDocument_OnContext
Menu = True Tell ArcMap not to popup a menu menu
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
16-12
The ICommandBar interface supports the CreateMenu method, which is used to creat
e a new (empty) menu on a toolbar, menu, or shortcut menu. Remember that unlike
toolbars and shortcut menus, a menu must always exist on another command bar. Fo
r this reason, you should always call the CreateMenu method on a particular Comm
andBar object to create new menus, rather than calling Create on the CommandBars
collection. Optionally, the position of the new menu on the command bar can be
specified with an index argument. The example above adds a new sub-menu (called
Sub) to the shortcut menu created earlier. Because no index argument was specifi
ed to define the position of the new menu, it was placed at the bottom of the sh
ortcut menu. The About ArcMap command was added to the sub-menu by referencing i
ts UID from the ArcID module.
Introduction to Programming ArcObjects with VBA
Application framework and ArcObjects events 16-12
Creating commands to execute macros
ICommandBar::CreateMacroItem
aMenu.CreateMacroItem aNameString, anIconID, aMacroNameString aMenu.CreateMacroI
tem aNameString, anIconID, aMacroNameString
Add a macro to the context menu Add a macro to the context menu pMnu.CreateMac
roItem "myMacro", 0, "Normal.ThisDocument.Calc" pMnu.CreateMacroItem "myMacro",
0, "Normal.ThisDocument.Calc" pMnu.Popup Display the new context menu pMnu.Popu
p Display the new context menu MxDocument_OnContextMenu = True Tell ArcMap not
to popup a MxDocument_OnContextMenu = True Tell ArcMap not to popup a menu men
u
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
16-13
Creating commands that execute existing macros Use the CreateMacroItem method on
the ICommandBar interface to add a macro from your map to a toolbar, menu, or s
hortcut menu. The required arguments for the CreateMacroItem methods are: • Name
—a string to appear with the command item (‘myMacro’ in the example above). • Fa
ceID—an integer that specifies a standard ArcGIS icon for the command item. • Ma
cro—a string that identifies the procedure to execute when the command item is c
licked.
Introduction to Programming ArcObjects with VBA
Application framework and ArcObjects events 16-13
Updating the ArcID module
Allows imported tools to be identified in ArcID
ICommandBars::Find
Customize dialog box
Options tab Update ArcID module
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
16-14
Updating ArcID module Update the ArcID module by using the Customize dialog box
(Options tab). By updating the ArcID module, you are adding the UID that identif
y any COM classes that have been added to ArcMap such as custom controls and too
lbars. After updating the ArcID module, you can programmatically access these cu
stom controls as you do the existing ArcMap controls (ICommandBars::Find).
Introduction to Programming ArcObjects with VBA
Application framework and ArcObjects events 16-14
Lesson overview
Customizing the user interface
Commandbars collection Displaying existing toolbars and menus Programmatically a
dding controls
Understanding Events
Inbound and outbound interfaces Finding outbound interfaces and events Capturing
ArcObjects Events
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
16-15
Just like the MxDocument, other ArcObjects have events available, ready to code.
In this section, you will learn where to find events on the Object Model Diagra
ms and how to capture their occurrence. Topics for this lesson are: • Outbound v
ersus inbound interfaces • Finding outbound interfaces and events on the diagram
s and using the Help tools • Declaring variables using the WithEvents keyword •
Writing event code • A survey of ArcObjects outbound interfaces and events
Introduction to Programming ArcObjects with VBA
Application framework and ArcObjects events 16-15
Inbound and outbound interfaces
Inbound
Client code makes calls to methods and properties on a server
Outbound
The server class makes calls to client code
Server Server Client Client
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
16-16
Interfaces can be either inbound or outbound. An inbound interface is the most c
ommon kind and the one you have worked with almost exclusively in this course. O
n an inbound interface, client code makes calls to functions within the interfac
e contained on an object. An outbound interface is one where the object makes ca
lls to client code—a technique analogous to the traditional callback mechanism.
Outbound interfaces do not contain methods and properties, only events. Events a
re actions that cause the server class to look for client code to execute.
Introduction to Programming ArcObjects with VBA
Application framework and ArcObjects events 16-16
Finding outbound interfaces
Solid pushpins (lollypop) on the OMDs ( Outbound interfaces have events only
Some events Some events have parameters have parameters
)
Search Object Browser with class name to find events
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
16-17
Finding outbound interfaces and events The object model diagrams list outbound i
nterfaces with a solid (black) pushpin symbol, as opposed to the familiar hollow
(white) pushpin used for the inbound interfaces. Outbound interfaces are genera
lly named with the word Events in the interface name and contain nothing but eve
nts (no methods and properties). Some events will have parameters that are passe
d into the event procedure. The OnContextMenu event listed above, for example, w
ill pass in the x- and ycoordinates where the user clicked (in pixels). As a pro
grammer writing code for this event, you could use these parameters. When search
ing for events for a coclass in the object browser, search for the class itself,
not for the interface name. The object model might show an interface called IMa
pEvents, for example. To find the events for this interface in the object browse
r, you would search for MapEvents. Every ArcObjects coclass that implements more
than one outbound interface will have a default. When examining a coclass in th
e object browser, events for the default outbound interface will be listed.
Introduction to Programming ArcObjects with VBA
Application framework and ArcObjects events 16-17
Using an outbound interface
Declare an object variable using WithEvents
Module-level variable
Private WithEvents m_pMapEvents As Map Private WithEvents m_pMapEvents As Map
Declare as the object, not an interface
Declare with an interface only for an inbound interface
Some classes support more than one outbound interface
Declare as interface name minus the ‘I’
Private WithEvents m_pAVEvents As MapEvents Private WithEvents m_pAVEvents As Ma
pEvents
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
16-18
Visual Basic and outbound interfaces Visual Basic only supports one outbound int
erface (marked as the default outbound interface) per coclass. To get around thi
s limitation, the coclasses that implement more than one outbound interface have
an associated dummy coclass that allows access to events on a secondary outboun
d interface. These coclasses have the same name as the outbound interface they c
ontain, minus the I. For example, by checking the OMD, you will notice that the
Map coclass implements two outbound interfaces: IActiveViewEvents and IMapEvents
. Because IActiveViewEvents is the default outbound interface for the Map coclas
s, you would capture these events like this:
Private WithEvents m_pAVEvents As Map
To capture the events on the secondary outbound interface (IMapEvents), you woul
d declare your variable like this:
Private WithEvents m_pMapEvents as MapEvents
Determining whether an outbound interface is outbound or not The Object Model Di
agrams will indicate in parentheses whether or not an outbound interface is the
default not. You may also want to use the ESRI Object Browser to determine wheth
er an outbound interface is default or not. You can use the ESRI Object Browser
by going to Start > Programs > ArcGIS > Developer Tools > Object Browser. You wi
ll use the ESRI Object Browser in the exercise.
Introduction to Programming ArcObjects with VBA
Application framework and ArcObjects events 16-18
Events supported by Map
ActiveViewEvents (default)
AfterDraw ContentsChanged FocusMapChanged SelectionChanged SpatialReferenceChang
ed
Private WithEvents m_pMap As Map Private WithEvents m_pMap As Map
MapEvents
FeatureClassChanged
Private WithEvents m_pAVEvents As Private WithEvents m_pAVEvents As MapEvents Ma
pEvents
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
16-19
Events on the Map class The Map class supports two outbound interfaces. ActiveVi
ewEvents is the default outbound interface; access these events by declaring a v
ariable (WithEvents) simply as Map. MapEvents is a secondary outbound interface
that supports some additional events. To access these events, declare a variable
(WithEvents) as MapEvents (do not declare it as IMapEvents). Map events allow y
ou to respond to actions taken by a user interacting with the active data frame.
Introduction to Programming ArcObjects with VBA
Application framework and ArcObjects events 16-19
Capturing object events
Initialize the variable declared WithEvents
Must initialize (set) or events will not be fired Commonly initialized when the
document opens
Private WithEvents m_pAVEvents As Map Private WithEvents m_pAVEvents As Map Priv
ate Function MxDocument_OpenDocument() As Boolean Private Function MxDocument_Op
enDocument() As Boolean Dim pMxDoc As IMxDocument Dim pMxDoc As IMxDocument Set
pMxDoc = ThisDocument Set pMxDoc = ThisDocument Set m_pAVEvents = pMxDoc.FocusMa
p Can now access events Set m_pAVEvents = pMxDoc.FocusMap Can now access event
s End Function End Function
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
16-20
The first step for tapping into an object’s events is to declare a variable usin
g the WithEvents keyword. The next step is to initialize the variable as a speci
fic object whose events you want to provide code for. The tricky part can be det
ermining when to initialize the variable. For many applications, you will want t
o have access to object events as soon as the project is opened. In this case, y
ou would initialize your outbound interface variables in the MxDocument_OpenDocu
ment event procedure, as shown in the example above. You may also want to change
the object that your variable is pointing to. When your user changed the focuse
d map, for example, you might need to reinitialize the variable to point to the
new map in order to respond to its events. Until the variable is initialized, co
de you have written for the object’s events will not fire.
Introduction to Programming ArcObjects with VBA
Application framework and ArcObjects events 16-20
Coding object events
Navigate to event procedures in the code module
Object variable appears in the object list (left) Events appear in the procedure
list (right)
Write code to respond to the event
Object Object Procedure Procedure
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
16-21
Writing event code After declaring a variable using the WithEvents keyword, you
will have access to all events supported by that outbound interface. To code a s
pecific event procedure, pull down the object list on the left-hand side of the
code module and choose your WithEvents variable. You will then see each event su
pported by this object in the procedure list (right-hand side of the code module
). By choosing an event, the stub code will automatically be provided for the pr
ocedure. Code you write inside the stubs will execute each time the correspondin
g object event fires. Unlike a COM developer implementing an inbound interface,
a programmer implementing an outbound interface does not have to write code for
every event procedure. When implementing an outbound interface, as in the exampl
e above, you can pick and choose which events you want to provide code for.
Introduction to Programming ArcObjects with VBA
Application framework and ArcObjects events 16-21
Exercise 16 overview
Exercise 16A:
Add CommandItems to a context menu Add a sub-menu to a context menu Turn layers
on/off from a context menu
Exercise 16B:
Declare a variable as an outbound interface Initialize a variable to code layer’
s events Set the display extent according to layer visibility Explore selection
and Catalog events
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
16-22
Exercise 16A: Programming the user interface In this exercise, you will create n
ew context menus and menu choices programmatically. You will write logic to dyna
mically decide which context menu to display. You will also write code to add th
e names of all layers in the map to a context menu, then toggle their visibility
by calling a macro in the project. Exercise 16B: Coding ArcObjects events In th
is exercise, you will write code to capture some ArcObjects events. You will wri
te an application that automatically changes the extent of the map display accor
ding to whether a particular layer is visible or not. When the layer is turned o
n (i.e., visible), you will zoom the extent to the layer. When it is off, you wi
ll zoom back to the full extent. As a challenge, you may try to program selectio
n events in ArcMap and ArcCatalog.
Introduction to Programming ArcObjects with VBA
Application framework and ArcObjects events 16-22
Introduction to Programming ArcObjects with VBA ModuleTitle
ArcObjects beyond VBA
Lesson overview Visual Basic versus VBA Remember COM? Basic steps: Building a CO
M component 1) Create a new COM project 2) Create a COM class 3) Reference the a
ppropriate libraries 4) Implement the required interface(s) Referencing the Appl
ication Example: Branching in a COM component 5) Compile your component DLL 6) R
egistering your COM component Where can COM components plug in? 17-17 17-5 17-6
17-7 17-8 17-9 17-11 17-12 17-13 17-14 17-15 17-18 17-19 17-20 17-21 17-22 17-23
17-24 17-25 17-26 17-27 17-28
contents
17-2 17-3 17-4
Resources for creating custom components Exercise 17 (Optional): Building a COM
command Lesson overview ArcGIS Engine ArcGIS Engine Developer Kit Engine Runtime
Why ArcGIS Engine Developer Kit? ArcGIS Engine Developer Kit resources Lesson o
verview ArcGIS Server Why ArcGIS Server? ArcGIS Server resources
ArcObjects beyond VBA
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
Introduction to Programming ArcObjects with VBA
ArcObjects Beyond VBA
17-1
Lesson overview
Creating COM classes with Visual Basic
Visual Basic versus VBA Building a COM class with Visual Basic
Referencing the ArcObjects libraries Implementing an interface Delivering your c
lass
ArcObjects interfaces
Where can your component plug in?
ArcGIS Engine Developer Kit ArcGIS Server
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
17-2
Overview This optional lesson covers the use of standalone Visual Basic to produ
ce COM components that work in ArcMap or ArcCatalog. It will provide the basic s
teps required to create a COM DLL, as well as a survey of some of the places whe
re your component can plug in to the existing application’s architecture.
Introduction to Programming ArcObjects with VBA
ArcObjects Beyond VBA
17-2
Visual Basic versus VBA
Visual Basic Control Arrays Integrated Debugging Preset Variables Import VBA For
ms Import VB Forms Ability to Compile Code Yes No No Yes __ Yes VBA No Yes Yes _
_ No No
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
17-3
Visual Basic versus Visual Basic for Applications From a syntactical standpoint,
there is virtually no difference between programming in Visual Basic and progra
mming in VBA. In fact, the code you have written during this course using VBA co
uld be ported to Visual Basic with only minor modifications. The table above giv
es a basic overview of some of the differences between VB and VBA. The most impo
rtant difference is standalone Visual Basic’s ability to compile code to disk as
a dynamic-link library (DLL) or executable file (EXE). As you know, all code in
VBA must be stored inside a document, such as a map file (mxd) or template (suc
h as normal.mxt or normal.gxt). The advantage of having your code compiled (as a
DLL, for example) is that it is easier to share with other users, and it is muc
h more secure (those using your DLL or EXE cannot see or modify the actual code)
.
Introduction to Programming ArcObjects with VBA
ArcObjects Beyond VBA
17-3
Remember COM?
COM is a standard for creating classes Classes can be reused between application
s
Independent of programming language
Because of COM, you can design a component that plugs into ArcGIS ArcGIS Desktop
can be extended with COM and .Net APIs
This lesson will focus on COM with Visual Basic
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
17-4
Remain COM Remember that the component object model (COM) is not a programming l
anguage in itself, but is rather a standard for how classes should be written. T
he primary advantage of COM is the ability to create your own components that ca
n easily plug into and work inside an existing architecture. To make this work w
ithout COM, you would have to modify and recompile the original source code for
ArcMap or ArcCatalog every time you wanted to add a component.
Introduction to Programming ArcObjects with VBA
ArcObjects Beyond VBA
17-4
Basic steps: Building a COM component
1. Create 2. Create
a new COM project a COM Class the ArcObjects libraries the required interface(s)
3. Reference 4. Implement 5. Compile 6. Register
the component as a DLL your component with ArcGIS
The steps are the same regardless of the language
This exercise and lecture shows Visual Basic 6.0
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
17-5
It’s as easy as 1, 2, 3, 4, 5, 6 OK, so it is not as easy as some of the other p
rogramming tasks you have tackled this week, but it is not that hard. 1. Create
a new COM project—in order to create a custom COM component, you must use a stan
dalone programming environment that is COM compliant. This lesson discusses the
use of Visual Basic, but you could also use VC++, Delphi, .NET, or a similar pro
gramming environment. 2. Create a COM class- you will create a creatable COM cla
ss. This class will allow you to create objects from it and embed them into ArcM
ap or ArcCatalog. 3. Reference the ArcObject libraries—unlike programming in Arc
Map or ArcCatalog, Visual Basic will not automatically know about the ArcObjects
. 4. Implement the required interface(s)—as described earlier, to ensure that yo
ur component works with the existing architecture, you must implement the proper
interface or interfaces that ArcGIS will expect. 5. Compile the component as a
DLL—write your component out as a dynamic-link library. You may need to perform
some debugging before your component compiles without an error. 6. Register your
component with ArcGIS —ArcGIS ArcObjects are divided into what are called compo
nent categories, which help organize your components. The type of component you
create will determine which category you need to register your component in. Las
tly, you will simply want to test, debug and recompile the component. Test the c
omponent in ArcMap or ArcCatalog. If it does not work as expected, you may need
to return to your VB project to fix bugs and recompile your DLL.
Introduction to Programming ArcObjects with VBA
ArcObjects Beyond VBA
17-5
1) Create a new COM project
Create a new Visual Basic ActiveX DLL project Give project meaningful name
ActiveX DLL ActiveX DLL
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
17-6
Creating a new Visual Basic project To design new COM components, you need to ma
ke sure you create a new ActiveX DLL Visual Basic project, as opposed to a stand
ard executable. When creating your new VB project, make sure you provide meaning
ful names for the project and for each class that you create. The name of the pr
oject will also be the default name of the DLL when it is compiled. Each class i
n your project will be an individual component in your DLL. If I create a class
called Class1 that is going to be a custom control for example, my new control w
ould also be called Class1 inside my DLL. A single DLL can contain several class
es (i.e., components). It is not necessary, therefore, to create a new ActiveX D
LL project for each component you want to create. If needed, you could deliver d
ozens of commands, toolbars, and other components in a single DLL.
Introduction to Programming ArcObjects with VBA
ArcObjects Beyond VBA
17-6
2) Create a COM class
Class scope controlled by Instancing property
Use MultiUse to make a public creatable class
Each class module will Each class module will become a component become a compon
ent (e.g., Control) (e.g., Control)
MultiUse Instancing MultiUse Instancing (Creatable) (Creatable)
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
17-7
In Visual Basic ActiveX DLL projects, the only way to control the public interfa
ce of a new COM class is to set its name and Instancing property. The name contr
ols the name assigned to the object and the name of the default interface. The I
nstancing property controls the scope of the class and determines whether or not
other COM objects can create instances of the object. Instancing property setti
ngs • Private: Class is only visible to the Visual Basic project. • PublicNotCre
atable: Interface and coclass defined; coclass is not creatable using the Visual
Basic New keyword. • MultiUse: Interface and coclass defined; coclass is creata
ble. • GlobalMultiUse: Lets the developer use a reference without declaring it.
Default interface When you implement a COM object using a class module in Visual
Basic, the object will have a default interface that has the same name as the c
lass. However, the class name also has an underscore as a prefix. The underscore
indicates that this interface is hidden in the type library. The Visual Basic O
bject Browser and code completer do not display default interfaces. Don’t be foo
led when you are writing code to declare variables for IApplication and IDocumen
t. Although you will not see references to these interfaces in the VB Object Bro
wser, IApplication and IDocument are default interfaces for ArcObjects.
Introduction to Programming ArcObjects with VBA
ArcObjects Beyond VBA
17-7
3) Reference the appropriate libraries
Project > References > ESRI libraries
Referenced libraries depend on what you are implementing Also reference any othe
r libraries required by your component
esriSystemUI.olb esriSystemUI.olb
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
17-8
Reference the ArcObject library Remember that when you are programming in ArcMap
or ArcCatalog, you do not need to explicitly reference the ArcObject libraries.
This is not the case when programming in a standalone programming environment s
uch as Visual Basic. Any additional libraries that are required (apart from the
Visual Basic library) need to be explicitly brought into your project. To refere
nce additional class libraries, choose References from the Project menu. Each Ar
cObjects class that you work with is stored in a specific library. You can find
out which library a class belongs in by looking at the help or Object Model Diag
rams. You may also use the Library Locator, which is a utility that can be found
in C:\<InstallDirectory>\ArcGIS\ DeveloperKit\Tools to find which library a cla
ss or interface belongs in. Place a check next to the library listings you will
be using in this project to reference, then click OK.
Introduction to Programming ArcObjects with VBA
ArcObjects Beyond VBA
17-8
4) Implement the required interface(s)
Give ArcGIS what it expects from Give ArcGIS what it expects from your component
your component
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
17-9
Implement required ArcObject interfaces To make sure that your component will be
understood by the ArcMap or ArcCatalog application, you need to implement an in
terface (or interfaces) appropriate for your component. In the example above, if
ArcMap is to place a new control on its user interface, it needs to be able to
ask the control for some basic properties, such as What image should be displaye
d on the control? (Bitmap property), What text should be displayed when a user h
overs over the control with the mouse? (ToolTip), and most importantly, What sho
uld I do when the control is clicked? (OnClick event procedure). As a programmer
, you answer these questions by writing code for the proper interface.
Introduction to Programming ArcObjects with VBA
ArcObjects Beyond VBA
17-9
4) Implement the required interface(s)
Implements statement
First line of code in your class module A contract to code everything on the int
erface
Must stub out code for all Must stub out code for all methods and properties met
hods and properties
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
17-10
Write code to make your component work After deciding which interfaces your comp
onent needs to implement, the next step is to write code for every method and pr
operty on each interface. To satisfy the rules of COM, this simply means having
all method and property procedure stubs in your class module. Upon entering the
implements statement in the general declarations (top) portion of the class modu
le, you will be able to choose the interface from the object list (upper-left),
and then see all its methods and properties in the procedure list (upper-right).
You may need to provide code for only a handful of these procedures in order to
make your control function to your liking. You must, however, have stub code fo
r at least each member on your implemented interfaces before your DLL will compi
le.
Introduction to Programming ArcObjects with VBA
ArcObjects Beyond VBA 17-10
Referencing the Application
OnCreate procedure passes in a reference (hook)
Cannot use Application or ThisDocument variables
Store hook in a module-level variable
Will be used throughout your component (e.g., OnClick)
Your way into the object model
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
17-11
Hooking into the ArcMap or ArcCatalog application A major difference that you wi
ll find when programming in a standalone environment such as Visual Basic as opp
osed to VBA is the lack of easily available preset variables. When programming i
n ArcMap or ArcCatalog, you can jump into your code by using the preset Applicat
ion or ThisDocument variables. To get access to the current application or docum
ent from your COM component, you will need to use another technique. Most ArcObj
ect interfaces that your custom components implement pass in a reference to the
application object in one of their event procedures. On the ICommand interface,
the OnCreate event passes in a parameter called hook that is mysteriously referr
ed to as an Object (see the example above). This object is the equivalent of the
Application preset variable. In order to use this object throughout your compon
ent, however, you will need to store it in a module-level variable as shown abov
e (m_pMxApp). The OnCreate event fires when a user drags the command from the Cu
stomize dialog box to a toolbar or menu, or when a map containing the control is
opened.
Introduction to Programming ArcObjects with VBA
ArcObjects Beyond VBA 17-11
Example: Branching in a COM component
Perform different tasks in Perform different tasks in ArcMap and ArcCatalog ArcM
ap and ArcCatalog
Use TypeOf to see if Use TypeOf to see if Control was added to Control was added
to ArcMap or ArcCatalog ArcMap or ArcCatalog
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
17-12
Creating an all-purpose command The example above shows how to create a command
that works in both ArcMap and ArcCatalog. This class implements the ICommand int
erface, which is required for all ArcMap and ArcCatalog commands. When the OnCre
ate event fires, the TypeOf statement is used to see if hook is the ArcMap or Ar
cCatalog application. A string variable is set to record which application the c
ontrol is being used in. The OnClick event uses the string variable (m_strApp) t
o see if the control is being used in ArcMap or ArcCatalog. Depending on the app
lication, the control will serve a different purpose: reporting the selected lay
er in ArcMap, and reporting the selected file in ArcCatalog.
Introduction to Programming ArcObjects with VBA
ArcObjects Beyond VBA 17-12
5) Compile your component DLL
File > Make DLL
Compiles your code and writes it to disk as a DLL Dynamic linked library
Common compile errors
ArcObjects library was not referenced Did not fully implement an interface The c
omponent is in use (ArcMap or ArcCatalog): only for recompile
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
17-13
Compiling the COM DLL Once you have written all the required code to make your c
ontrol work inside of ArcGIS, you need to compile the project to a DLL on disk.
Choose ‘Make <project name>’ to compile your DLL, specifying an output file loca
tion. If there are no syntax errors in your code, the DLL will compile, otherwis
e VB will report an error. Common errors encountered when compiling • ‘Object mo
dule needs to implement <member name> for interface <interface name>’— you did n
ot at least stub out all of the methods and properties for an interface that you
promised to implement. • ‘User-defined type not defined’—you probably forgot to
reference a required library (esriSystemUI.olb, for example). If you forget thi
s, you should be able to clue in quickly as you would not see code completion an
yway. • ‘Permission denied: <DLL filename>’—the DLL is likely being used (by Arc
Map or ArcCatalog, for example). This error might be encountered when you are in
the testing/debugging phase of developing your component.
Introduction to Programming ArcObjects with VBA
ArcObjects Beyond VBA 17-13
6) Registering your COM component
Customize dialog box (Add from file)
ArcGIS will automatically register the component
Component category manager
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
17-14
Registering you COM DLL Before you can use your custom component in ArcMap or Ar
cCatalog, you need to make sure it is registered with your operating system. The
re are three ways in which you can register a component. • Customize dialog box—
when you use the Add from file button to bring in a component, your component DL
L is automatically registered. • Component category manager—the component catego
ry manager allows you to add and remove ArcGIS components. Components are organi
zed into various categories. By adding your DLL to the proper category, your com
ponents will be incorporated into ArcGIS. To add a new edit task that you have c
reated, for example, add your component to the ESRI Edit Tasks category (as in t
he example above).
Introduction to Programming ArcObjects with VBA
ArcObjects Beyond VBA 17-14
Where can COM components plug in?
Edit Task Edit Task
Command Command Table of Contents Tab Table of Contents Tab
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
17-15
COM components on the ArcMap interface Here are some examples of components that
can be added to ArcMap • Command—a button, tool, or menu choice. To create this
component, you must implement ICommand, and may also need to implement ITool, I
ToolCommand, or both. • Edit task—a task that works with the ArcMap Editor in co
njunction with the sketch tool. It must implement IEditTask. • Table of Contents
tab—an additional tab on the ArcMap Table of Contents that implements the ICont
entsView interface.
Introduction to Programming ArcObjects with VBA
ArcObjects Beyond VBA 17-15
Where can COM components plug in?
ClassExtension ClassExtension (Geodatabase) (Geodatabase) ToolControl ToolContro
l
Network Trace Task Network Trace Task
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
17-16
More custom components for ArcMap … Some additional places to use custom COM com
ponents: • Class extension—a component that works with a dataset (feature class
or table) to provide limited custom behavior (attribute calculation or validatio
n, for example). A class extension must implement IClassExtension, and may also
implement IPropertyInspector, IObjectClassValidation, or several others. • Tool
control—a custom control that extends the abilities of simple buttons or tools.
Must implement the ICommand and IToolCommand interfaces. • Network trace task—a
task on the Utility Network toolbar for solving network problems. Implements the
ITraceTask interface.
Introduction to Programming ArcObjects with VBA
ArcObjects Beyond VBA 17-16
Resources for creating custom components
Instructor-led course
Extending the ArcGIS Desktop Applications
http://arcgisdeveloperonline.esri.com
ArcGIS Desktop Developer’s Guide Samples Extending ArcObjects
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
17-17
Extending ArcGIS applications resources The Extending the ArcGIS Desktop Applica
tions instructor-led course will supply a wealth of information to get you start
ed extending ArcGIS applications. This course will cover a variety of COM APIs,
including Visual Basic 6 and .NET languages. ArcGIS Developer Online also provid
es a developers guide, many samples and online books to help assist you in your
development tasks.
Introduction to Programming ArcObjects with VBA
ArcObjects Beyond VBA 17-17
Exercise 17 (Optional): Building a COM command
Create a new Visual Basic project
ActiveX DLL
Add a new Class module Reference the appropriate ArcObjects libraries Implement
the ICommand interface Compile the DLL Add the control to ArcMap
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
17-18
Exercise 17: creating a COM control in Visual Basic In this optional exercise, y
ou will use (standalone) Visual Basic to create a new COM DLL. The COM class you
create will implement the required interface for a command that works in ArcGIS
, ICommand. After writing the required code to implement this interface, you wil
l compile your DLL, and then test it in ArcMap.
Introduction to Programming ArcObjects with VBA
ArcObjects Beyond VBA 17-18
Lesson overview
Creating COM classes with Visual Basic
Visual Basic versus VBA Building a COM class with Visual Basic
Referencing the ArcObjects libraries Implementing an interface Delivering your c
lass
ArcObjects interfaces
Where can your component plug in?
ArcGIS Engine Developer Kit ArcGIS Server
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
17-19
Overview This optional lesson covers the ArcGIS Engine Developer Kit, a new prod
uct at ArcGIS 9. This product allows you to use ArcObjects to build stand alone
custom applications.
Introduction to Programming ArcObjects with VBA
ArcObjects Beyond VBA 17-19
ArcGIS Engine
There are two parts to ArcGIS Engine
(1) Engine Developer Kit
Used by developers
(2) Engine Runtime
What the end user needs to run the developer product
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
17-20
ArcGIS Engine is a complete library of embeddable GIS components for developers
to build custom applications. Using ArcGIS Engine, developers can embed GIS func
tions into existing applications such as Microsoft Word and Excel, as well as bu
ild focused custom applications for delivering a focused GIS task to many users
in their organizations without having an ArcGIS license on the client machine. T
he ArcGIS Engine consists of a software development kit and a re-distributable r
untime required for all ArcGIS applications. The ArcGIS Engine Developer Kit is
a component-based software development product for building and deploying custom
GIS and mapping applications. The ArcGIS Engine Developer Kit is not an end use
r product, but a toolkit for application developers. It allows developers to bui
ld either simple mapping applications or comprehensive GIS applications for Wind
ows, UNIX or Linux users.
Introduction to Programming ArcObjects with VBA
ArcObjects Beyond VBA 17-20
ArcGIS Engine Developer Kit
New developer product that creates standalone desktop applications A toolkit for
developers (not an end user application) Cross Platform COM, .Net, C++(new), Ja
va(new) APIs Development tools
ArcObjects and Controls
Map, PageLayout, Toolbar, TOC, Reader, Scene, Globe controls
Documentation Sample code Help and tutorials
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
17-21
The ArcGIS Engine Developer Kit provides the developer with many resources to co
mplete their development task. The ArcGIS Engine Developer Kit is not a product
for end users. It is strictly for people who are developing applications. As a d
eveloper, you can build applications based on ArcGIS Engine and deliver those pr
ograms to end users. The ArcGIS Engine supports a variety of developer languages
for its use including, COM, .NET, JAVA, and C++ for the applications to be used
in different platforms. This also allows the objects to be programmed using a w
ide range of tools, and should not require you to learn a proprietary language.
Developers will also be provided with a common set of developer controls that al
low them to easily deploy well-crafted applications with a common look and feel
when they get the ArcGIS Engine Developer Kit. An extensive help system along wi
th object model diagrams and sample code to help developers get started is also
included.
Introduction to Programming ArcObjects with VBA
ArcObjects Beyond VBA 17-21
Engine Runtime
Runtime license needed for all custom applications built with Engine Developer K
it Licensing:
Standard Engine Runtime View and author maps, query, analysis, simple editing En
gine Runtime Options GeoDatabase Update Spatial 3D StreetMap
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
17-22
ArcGIS Engine Runtime All applications built with the Engine Developer Kit will
need the ArcGIS Engine Runtime or ArcGIS Desktop with the appropriate level of l
icense to execute successfully. There are different license levels for the Engin
e Runtime. The standard Engine Runtime provides core functionality of all ArcGIS
applications. This standard Engine Runtime can be enhanced with options for ful
l read-write access of the enterprise Geodatabase supports, as well as advanced
functionality for 3D visualization and spatial analysis. Visit the ArcGIS Engine
Developer Guide for a complete listing of functionality for the different runti
me options. To obtain the ArcGIS Engine Runtime, users can contact ESRI for CDs
to install the Engine Runtime for internal use. Business partners that develop a
pplications may also purchase runtime licenses and incorporate them into the set
up program for installing the custom built application.
Introduction to Programming ArcObjects with VBA
ArcObjects Beyond VBA 17-22
Why ArcGIS Engine Developer Kit?
So end users don’t need a full ArcGIS Desktop license on their machine to use a
developer’s standalone application Designed for focused applications that don’t
need everything ArcGIS Desktop offers
Java Example
Windows Example
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming Arc
Objects with VBA
17-23
All over the world people are constantly taking advantage of GIS functionality.
Whether it be creating a simple map, performing a query, or doing some type of a
dvanced overlay analysis, people are using this functionality. This does not nec
essarily mean everyone performing GIS tasks are GIS experts and need a full fled
ged GIS on their machine. If someone only needs to perform a specific task over
and over, it is much easier for them to use an application suited towards their
needs. For example, a utility company may have many employees that make daily ed
its to their database for where new power lines have been created, making update
s and performing network traces if a power line is affected. If this will be the
only tasks they need to do, it will be much easier and efficient for them to us
e a custom application designed specifically to perform these tasks.
Introduction to Programming ArcObjects with VBA
ArcObjects Beyond VBA 17-23
ArcGIS Engine Developer Kit resources
Instructor-led course
Developing Applications with ArcGIS Engine
http://arcgisdeveloperonline.esri.com
ArcGIS Engine Developer Guide Samples Extending ArcObjects
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
17-24
The Developing Applications with ArcGIS Engine instructor-led course will supply
a wealth of information to get you started building and deploying ArcGIS Engine
applications. ArcGIS Developer Online also provides developer guides and sample
s that are specific to building ArcGIS Engine applications.
Introduction to Programming ArcObjects with VBA
ArcObjects Beyond VBA 17-24
Lesson overview
Creating COM classes with Visual Basic
Visual Basic versus VBA Building a COM class with Visual Basic
Referencing the ArcObjects libraries Implementing an interface Delivering your c
lass
ArcObjects interfaces
Where can your component plug in?
ArcGIS Engine Developer Kit ArcGIS Server
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
17-25
Overview This optional lesson covers ArcGIS Server, a new product at ArcGIS 9. A
rcGIS Server provides a framework for using ArcObjects through an Internet or lo
cal area connection through Web browsers or other client applications for an ent
erprise GIS.
Introduction to Programming ArcObjects with VBA
ArcObjects Beyond VBA 17-25
ArcGIS Server
A Web developer framework that makes it easy to build GIS Web applications and e
nterprise GIS applications Supports Client-Server, GIS Web Services, and GIS Web
Applications Cross platform Multiple APIs
.Net, Java
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
17-26
ArcGIS Server is a GIS enterprise application server that provides complete GIS
capabilities throughout an organization while maintaining a centrally managed da
tabase. Mapping, geocoding, spatial queries, editing, tracing and linear referen
cing are all examples of applications that developers can build using ArcGIS Ser
ver. These applications can be consumed by browser-based clients, custom applica
tions built with ArcGIS Engine, and ArcGIS Desktop. ArcGIS Server will support a
ll common development environments (Java, .NET, C++, COM) and all major server p
latforms. The initial release of ArcGIS 9 will support Microsoft Windows, while
other platforms will be supported in subsequent releases.
Introduction to Programming ArcObjects with VBA
ArcObjects Beyond VBA 17-26
Why ArcGIS Server?
So users can perform more advanced analysis over a LAN/Internet (take advantage
of the ArcObjects) So users can interact with an enterprise system
Geodatabase Editing
Network Tracing
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming Arc
Objects with VBA
17-27
ArcGIS Server allows GIS functionality to take place over the Internet or LAN, w
ithout a user having any GIS installed on their machine. All the end user will n
eed is a Web browser. This allows developers to build very focused applications
that people can access at any time. The end users do not need to worry about any
processing occurring on their machine or having unnecessary software installed.
Through Web applications, a developer can make a very intuitive application tha
t end users can operate without having much GIS knowledge. ArcGIS Server also al
lows users to interact with an enterprise system for everyday editing tasks with
out dealing with the administration of the system and data.
Introduction to Programming ArcObjects with VBA
ArcObjects Beyond VBA 17-27
ArcGIS Server resources
Instructor-led course
Developing Applications with ArcGIS Server
http://arcgisdeveloperonline.esri.com
ArcGIS Server Developer Guide Samples
Copyright © 2001–2004 ESRI. All rights reserved.
Introduction to Programming ArcObjects with VBA
17-28
ArcGIS Server resources The Developing Applications with ArcGIS Server instructo
r-led course will supply a wealth of information to get you started building and
deploying ArcGIS Server applications. ArcGIS Developer Online also provides dev
eloper guides and samples that are specific to building ArcGIS Server applicatio
ns.
Introduction to Programming ArcObjects with VBA
ArcObjects Beyond VBA 17-28

You might also like