Introduction To Programming Arc Objects With VBA
Introduction To Programming Arc Objects With VBA
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. This 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 form or by any means, electronic or mechanical,
including photocopying or recording, or by any information storage or retrieval system, except as expressly permitted in writing by
ESRI. All requests should be sent to Attention: Contracts Manager, ESRI, 380 New York Street, Redlands, CA 92373-8100, USA.
ESRI, ARC/INFO, ArcCAD, 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; registration is pending in the European Community. 3D Analyst, ADF, ArcCOGO, the ArcCOGO logo,
ArcGrid, the ArcGrid logo, the ARC/INFO logo, AML, ArcNetwork, the ArcNetwork logo, ArcNews, ArcTIN, the ArcTIN logo,
ArcInfo, the ArcInfo logo, ArcInfo Librarian, ArcInfo—Professional GIS, ArcInfo—The World's GIS, ArcAtlas, the ArcAtlas
logo, the ArcCAD logo, the ArcCAD WorkBench logo, ArcCatalog, the ArcData 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 logo, ArcMap, ArcObjects, the ArcPad logo, Arcplot, the Arcplot logo, ArcPress, the ArcPress logo, the
ArcPress for ArcView logo, ArcReader, ArcScan, the ArcScan logo, ArcScene, the ArcScene logo, ArcSchool, the ArcSDE logo,
the ArcSDE CAD Client 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 Publisher logo, the ArcView Image Analysis logo, the ArcView Internet Map Server logo, the ArcView
Network Analyst logo, the ArcView Spatial Analyst logo, the ArcView StreetMap logo, the ArcView StreetMap 2000 logo, the
ArcView Tracking Analyst logo, ArcVoyager, ArcWorld, the ArcWorld logo, Atlas GIS, the Atlas GIS logo, AtlasWare, Avenue,
the Avenue logo, the BusinessMAP logo, DAK, the DAK logo, Database Integrator, DBI Kit, the Digital Chart of the World logo,
the ESRI Data logo, the ESRI Press logo, ESRI—Team GIS, ESRI—The GIS People, FormEdit, Geographic Design System,
Geography Matters, GIS by ESRI, GIS Day, the GIS Day logo, GIS for Everyone, GISData Server, InsiteMAP, MapBeans,
MapCafé, the MapCafé logo, the 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 Personal Geographic Information System are trademarks;
and ArcData, ArcOpen, ArcQuest, ArcWatch, ArcWeb, Rent-a-Tech, Geography Network, the Geography Network logo,
www.geographynetwork.com, www.gisday.com, @esri.com, and www.esri.com are service marks of ESRI.
The names of other companies and products herein are trademarks or registered trademarks of their respective trademark owners.
ArcView GIS uses HCL Technologies Ltd. Presenter software under license.
C O N T E N T S
4 Using variables
Lesson overview 4-2
Variables 4-3
Working with variables 4-4
Dim (dimension) statement 4-6
Assigning a value to a variable 4-8
Function procedures 4-10
Comparing values 4-12
Decision making: The If Then statement 4-14
14 Using tools
Lesson overview 14-2
Tool events 14-3
Getting the user X and Y 14-4
Display transformation 14-5
Convert display coordinates to map units 14-6
Example: Rubberbanding 14-7
IGraphicsContainer 14-8
Managing graphics 14-9
Refreshing the display 14-10
Partially refresh the display 14-11
Exercise 14 overview: Choose one 14-12
Exercise 14A: Create a tool to draw point graphics
Exercise 14B: Create a Parcel Proximity tool
15 Data management
Lesson overview 15-2
Name objects 15-3
Object Model overview: Name classes 15-4
Creating a DatasetName 15-5
Data manipulation objects 15-6
Converting feature classes 15-7
Exercise 15A overview 15-8
Exercise 15A: Data conversion
Editing with a cursor 15-9
Editing cursors 15-10
Example: Updating misspelled attributes 15-12
Adding a field 15-13
Creating a domain 15-14
Adding a domain to a database 15-15
Assigning a domain to a field 15-16
Exercise 15B overview 15-17
Exercise 15B: Data management
Introduction to
ModuleTitle
Programming
ArcObjects with VBA Welcome 1-2
Logistics
Course materials
Course objectives
contents
1-3
1-4
1-5
Course timeline 1-6
What is ArcGIS? 1-7
Software support resources 1-8
Learning paths 1-9
VBA: Visual Basic for Applications 1-11
What can ArcObjects do? 1-12
Exercise options 1-16
Exercise typographic conventions 1-17
Exercise 1 overview 1-19
Introduction to
Programming ArcObjects
with VBA
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA
Organization
Role in organization
Programming experience
GIS experience
Goals and expectations
for this class
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 1-2
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.
Facilities
Your instructor will provide information regarding the facilities.
Internet access
Some training facilities provide Internet access for your use during class. ESRI® regards
Internet access as an essential business resource for classroom demos, exercises, arranging
travel, and maintaining contact with your office. Please limit your use of the Internet to
business activities only and, as a courtesy to your classmates, refrain from typing or surfing
during lecture presentations.
Course data
Samples
Online course evaluation
http://classeval.esri.com
Requires Course Identification Number
Software evaluation
E-mail enhancement requests to product teams
[email protected]
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 discussions, demonstrations, computer-
based exercises, and review questions.
Class materials
Your class materials include lecture and exercise course books, and Object 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 required for the
course. Here you will find all the map documents, data, and solution code used for each
exercise. You will also find over 100 different code samples that are not described or used
during the course, but that you might find useful 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 ArcSDE 8.1 for SQL Server software, which you will install later today.
Course evaluation
Your feedback improves ESRI’s courses. At the end of the week, please evaluate the
following:
• Instructor • Course materials • Teaching facilities • Overall course
Software evaluation
If you have access to a Web-based e-mail account during class, 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.
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 focuses on the
concepts of the component object model (COM), object oriented programming, and
understanding the ArcObject object model. Although no prior experience with Visual Basic
(VB) is assumed, the introductory portion of the course moves very quickly. Fundamental VB
topics are covered in the first couple of lessons, and then applied (and thus reinforced)
throughout the week.
You will learn to program through a combination of instructor-led lectures and hands-on
programming exercises. You should expect to spend the majority (approximately 60%) of
your class 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 problem.
By the end of the course, you can expect to have a solid understanding of 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 functionality of ArcGIS.
COM Classes
Day 2
Reading OMDs
Symbolizing layers
Day 4
Data management
Application framework
Day 5
ArcObjects beyond VBA
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 1-6
I
O
ArcView
ArcView Web
Web
ArcReader
ArcReader N ArcPad
ArcPad browser
browser
S
Components ArcObjects
ArcObjects
Network
ArcGIS
ArcGIS Server
Server ArcIMS
ArcIMS
Application/Data ArcSDE
ArcSDE
servers
RDBMS
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 1-7
ArcGIS is the name used to identify ESRI’s flagship family of GIS products. ArcGIS®
includes ArcGIS client software, components, and application and data server software.
ArcGIS itself is not a GIS application; rather, it is a set of software 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 application can create,
manage, analyze, and serve data stored in one or more formats.
•ArcGIS Desktop: Integrated suite of advanced GIS applications consisting of three software
products: ArcView®, ArcEditor™, and ArcInfo®. The ArcGIS Desktop applications provide the
same core mapping, editing, and analysis functionality. The level of functionality available
differs depending on which license you have. ArcInfo provides users with the most complete
level of GIS functionality. It is composed of ArcInfo Desktop and ArcInfo Workstation.
•ArcReader™: Allows users to view high-quality published maps (PMFs) created in ArcMap™.
•ArcGIS Engine: Developer toolkit of embeddable GIS components for building custom
stand-alone applications 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 software objects used to build and develop server-
side 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 information from external RDBMs to ArcGIS clients.
For more information, go to http://www.esri.com/software/index.html.
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 of 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 topic-
focused white papers organized by product, system requirement information, and product
documentation.
Downloads
Obtain the latest software correction, software and code samples, utilities, tutorials, user
contributed scripts and sample code (ArcScripts), data models, and evaluation software from
ESRI’s Download page.
User Forums
In the user forums, you can ask questions, provide answers, and exchange ideas with other
ESRI product users. Resources include several discussion forums, and two subscription 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 is 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.
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, and 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 Instructor-led and Web-based courses—including a list of topics
covered, intended audience, 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.html.
On the ESRI Training Web site, you can also find information about new courses developed
since the course catalog was printed.
Web-based courses offer convenience 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 free modules within minutes at http://campus.esri.com.
In addition to Web-based courses, the Virtual Campus also offers free live training seminars,
training seminars, and Web workshops. Live training seminars are focused lectures on a
variety of GIS topics for all levels of users. Consult the Virtual Campus for upcoming topics,
dates, and times. Training seminars are free recordings of live training seminars, viewable at
your convenience. Workshops are recordings of live training seminars, viewable at your
convenience, plus printable slides of the presentation, questions and answers from the live
training seminar, a software exercise with accompanying data, an optional exam to assess
understanding, and a certificate for successfully completing the exam.
Introduction to Introduction to
Extending the
Visual Basic Programming
W i ArcGIS
for ESRI ArcObjects i
Desktop
software with VBA
Applications
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 1-10
Courses identified with the i symbol occur in a classroom with an instructor. The W
symbol indicates Web-based courses available on the ESRI Virtual Campus at
http://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 (Introduction to Programming ArcObjects with VBA) are expected
to have a least a basic understanding of programming languages. The Web based course
Visual Basic for ESRI Software will provide sufficient information for taking this course.
ESRI’s Virtual 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 find 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 proficient with using
ArcObjects.
After completing Introduction to Programming ArcObjects with VBA, you may want to further
your knowledge by taking advanced ArcObjects courses. This course is a prerequisite to the
advanced ArcObjects courses that ESRI provides. The subject matter of these advanced
courses will be discussed on the following slides and the last section in this course..
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 1-11
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 1-12
Table
Table of
of Contents
Contents Tab
Tab
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 1-13
Java Example
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 1-14
Network Tracing
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 1-15
ArcGIS Server
ArcGIS Server allows you to build custom Web-based applications, exposing ArcObjects
through the Internet or LAN (Local Area Network). ArcGIS Server is a GIS enterprise
application server that provides complete GIS capabilities throughout an organization while
maintaining a centrally managed database. Mapping, geocoding, spatial queries, editing,
tracing and linear referencing are all 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 development environments (Java, .NET, C++, COM) and all major server platforms.
The information on this subject matter is discussed in the Developing Applications with
ArcGIS Server instructor-led course.
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 shortcut summarizes the steps found in
the main exercise. Each shortcut step corresponds 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 course, if you cannot complete the shortcut step, you can refer to the main
exercise for more detail.
9
9 Control
Note name
Keyboard
input
Warning
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 1-17
Before you begin your first exercise, you need to recognize the typographic conventions 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 ArcMap”; 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 indicates 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 complete each task.
This is especially helpful when shifting your attention between your book and your computer
monitor.
Control name
Names of objects on your monitor with which you interact are italicized in your exercise
coursebook. These include windows, menus, and buttons. Many buttons reveal their names
when you hold your mouse pointer over them.
Warning
The large exclamation point symbol and bold text signals critical information for performing
the next action. Warnings may alert you to a subtle syntactical rule in a command you will
type or inform you that the next button you click will produce an error intentionally. If you
have questions about a warning, ask your instructor for clarification before proceeding.
Keyboard input
Text you need to type—like commands in a Command Prompt, entering a file name in a Save
dialog, and pressing Ctrl + Alt + Delete—appears in bold, constantly-spaced font.
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 1-19
environment
Lesson overview 2-2 Writing Visual Basic statements 2-20
The VBA development
environment
ArcGIS commands
2-3
2-4
Some common Visual Basic
functions
Procedure types
contents
2-21
2-23
Using the Customize dialog box 2-5 Running an event procedure 2-24
The Customize dialog 2-6 Navigating event procedures in a
Using the Customize dialog box 2-8 module 2-25
Creating a new command 2-9 The ThisDocument module 2-26
Setting control properties 2-10 Creating a new module 2-27
Accessing your customizations 2-11 Creating a new sub or function
Storing your customizations 2-13 procedure (macro) 2-28
Examining a control’s source Defining procedure scope 2-30
code 2-14 Running a subroutine or function
Demonstration 2-15 procedure 2-31
Overview 2-16 Adding a macro to a toolbar 2-32
The Visual Basic Editor 2-17 Getting help 2-33
Understanding ArcMap Exercise 2 overview 2-34
software’s code storage 2-19
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 properties
Storing and distributing customizations
Visual Basic Editor
Code storage
Modules
Procedures
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 2-2
Lecture 2 overview
In this lesson, you will learn about the VBA development environment. 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 lesson will discuss the Customize dialog box. You will learn how to
modify the ArcMap and ArcCatalog user interface by (1) adding new toolbars, (2) adding
existing ArcGIS commands, (3) removing existing commands from toolbars and menus, (4)
altering command properties (e.g., icon), and (5) creating custom interface controls. You will
also learn how to store and distribute your customizations.
The last 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
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.
An advantage of using VBA that you will soon discover is that several applications use the
VBA development environment for customization. While these environments are not identical,
they are very similar. All Microsoft Office products, for example, will have a Customize
dialog box that allows you to add, remove, and rearrange interface controls. All of these
applications will have a Visual Basic Editor for writing macros or designing forms. Once you
are familiar with the ArcGIS™ VBA development environment, your skills will be portable to
several other applications.
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 UIControls
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). Commands are
things such as buttons and menus, macros (Visual Basic procedures), and UIControls (user
interface controls). UIControls are custom controls that an ArcGIS VBA developer can add to
the interface to perform specialized tasks. There are four types of UIControls:
UIButtonControls, UIToolControls, UIEditBoxControls, and UIComboBoxControls. COM
commands are similar to UIControls, except they are stored in DLL, EXE (executable), or
similar files and are created by a developer in a full-scale programming environment such as
Visual Basic or C++.
Users interact with commands by clicking, typing, selecting, or applying, depending on the
type of control. Behind each control, there is associated code that will execute in response to
user interaction. As a developer of a UIControl, you can write 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 location on a toolbar or menu. You can even drag them between
toolbars and menus or remove 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 box open, you can …
Rearrange or remove existing commands
Add new toolbars and commands
Change command 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 adding new
toolbars, menus, and commands to the user interface. You may want to simply 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 rearrange them or
change their properties. Once you are satisfied with the interface customizations you have
made, close the Customize dialog box to begin working with 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 commands onto the interface
Options: Lock customization with a password, etc.
A
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 2-6
The Customize dialog has three panels: Toolbars, Commands, and Options. The Toolbars and
Commands tabs are the ones you will use to modify the user interface, while the Options tab
provides some control over basic customization options.
Toolbars
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 them. 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 toolbars. When creating a new
toolbar, you will be prompted for a name and a location in which to save it (more about storing
customizations later). A new toolbar 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 contains all existing ArcMap or ArcCatalog
commands (depending on which application you are customizing). Commands can be dragged
from the Customize dialog onto a toolbar 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 basic properties of
your customization development environment.
Lock Customization: Clicking this will allow you to provide a password to protect your
customizations. When a user tries to access the Customize dialog box or the Visual Basic
Editor, 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. When you open such a document or perform an action that triggers a macro virus, the
macro virus might be activated, transmitted to your computer, and stored in your 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 stored in a special document called the
ArcID module. Update this module to write unique 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 here
Some that are not on the interface by default
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 into
categories. By highlighting a category on the left side of the dialog, you will see all commands
in the category listed on the right. Some familiar categories are things like Selection,
Pan/Zoom, and File. You will also find categories for Visual Basic procedures you write
yourself (Macros), for creating new menus (New Menu), and for creating new custom controls
(UIControls). Because many of the commands you find here are not found on the default (out-
of-the-box) ArcGIS interface, you might find a few gems here: functionality that you did not
know existed.
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 interaction 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
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 properties
Characteristics that define appearance
Name
Image
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 use the context (popup) menu that appears.
With the dialog open, you can modify the following command properties.
Name
The text that appears for a command if Text 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 menu or browsing to one of your own. If you create your own image, it
must be a bitmap (.bmp) that is 16 x 16 pixels.
Groups
Beginning a group adds a separator line to the left of the selected 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
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 customizations: the Normal
template (Normal.mxt), an intermediate (or base) template (*.mxt), and the current map
document (*.mxd). Each level of customization is represented by a document. Upon opening a
map, these documents are read from top to bottom in the graphic above in order to incorporate
customizations from all levels.
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 AddData command turned off,
but a base template may turn on the AddData command.
Normal 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 stored 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 different customizations stored in the Normal templates even
if they are running the same installation of ArcGIS.
In ArcCatalog, all customizations are stored in the 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 elements for the creation of standard maps. When
initially creating a new ArcMap map document, you can choose to base your map on a
template. While there are several predefined base templates that come with ArcGIS, you can
actually save any map 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 document. 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 templates.
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
Copyright © 2001–2004 ESRI. All rights reserved. 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 changing a command’s
image is saved in Normal.mxt, a base template (*.mxt), or with the 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 login. 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 periodic backups of the
Normal template if you are storing a lot of customizations there.
Base template
Base templates are designed primarily to store a set of map layout elements, such as north
arrows, scale bars, and base layers, to aid in the production of standard maps. These templates
may also contain customizations such as specialized controls or scripts. As an example, your
organization might work with parcel maps that all have a custom property value calculator
control inherited 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 example, you might have a map document that contains sensitive information
such as archaeological site locations. You could protect this particular document with a custom
startup routine that prompts for a password when the map document is opened.
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 runs when its corresponding event occurs
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 2-14
Code window
When you first create a UIControl, it only knows how to be a control but has no real code to
make it work. It other words, if it is a button it will click like any 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
associated 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 button 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
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 properties
Storing and distributing customizations
Visual Basic Editor
Code storage
Modules
Procedures
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects 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 controls, the Visual Basic Editor is
where you write code to make new controls work. You 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 use the Visual Basic Editor, how
code is stored and organized in ArcMap and ArcCatalog, as well as some basic VB-related
terminology (e.g., module, procedure, macro). Finally, you will learn to write Visual Basic
statements and how to use some simple Visual Basic functions.
Introduction to Programming ArcObjects with VBA The VBA development environment 2-16
The Visual Basic Editor
Project
Explorer
Projects
Project Explorer
The Visual Basic Project Explorer window organizes all code written for a particular ArcMap
document or for the ArcCatalog application into three kinds of projects: the Normal template, a
base template (if one is referenced), and the current project, also known as your currently
opened map document. Use the Project Explorer to access all available Visual Basic programs.
Projects
Projects are like root directories 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 current 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 three 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 three kinds of procedures: event,
subroutine, and function.
The example above shows the Project Explorer organizing two projects (Normal.mxt and
Malaysia.mxd). There are two open modules shown (as shown in the Project Explorer,
Malaysia.mxd contains 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 that stores modules (e.g., Normal.mxt)
Module: Document that stores code
Procedure: 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
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 statement. Statements are
simply lines of code, and each statement carries out some simple action. Statements, therefore,
are the building blocks for constructing sub procedures and functions. Although individual
statements can be executed in the Immediate window, for practical purposes all statements will
exist inside of a procedure.
Statements may or may not have arguments. An argument is simply some extra piece of
information that must be specified for a statement to work correctly. 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 displayed. Multiple arguments can be specified as a comma-
delimited list, as shown below.
'3 arguments: a Message, a Style, a Title
MsgBox "Continue?", vbYesNo, "Abort operation?"
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: "
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 2-21
Message boxes
To display various types of message boxes, use the Visual Basic MsgBox function. This
function has only one required argument, a message (prompt) to display. By specifying values
for the optional arguments below, you can further define the appearance of your message box.
Buttons: Use any combination of Visual Basic MsgBox constants to specify the type of
buttons, icons, or both to appear on the message box. To use several of these options, you can
simply add the constants together. 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 button
• vbExclamation—display an exclamation mark image on the message box
• vbInformation—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 message 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 function. 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 pause 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 Cancel button on the input box, an empty string is returned (“”).
Concatenation
To concatenate two strings, use the ampersand (&) character. The concatenation function does
not add a space between the strings. To add a space between concatenated strings, use one of
the methods as shown below.
MsgBox "Hello, my name is " & strFirstName
MsgBox "My full name is " & strFirstName & " " & strLastName
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)
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 distinctions that can be made about
specific types of procedures, however, as described below.
Event procedures
Event procedures are associated with objects. More specifically, they are associated with an
object event. Execution of these procedures is triggered when the associated event occurs. For
example, when UIButtonControl3 is clicked, the code in the UIButtonControl3_Click event
procedure executes. When the mouse cursor hovers over UIButtonControl3, the
UIButtonControl3_ToolTip 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 an 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) but are not able to pass back a value. Functions, on the other
hand, are generally used to produce some value to pass back to the procedure that called it
(calculating 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 (intValueA, 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
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 2-24
The example
When the control above (UIButtonControl1) is clicked by the user, its Click event code is
executed (UIButtonControl1_Click), which reports 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!"
Finding a procedure
To start coding (or just to find) an event procedure in a particular module, select an object and
an event procedure from the respective dropdown lists. The Object box (upper left) contains all
the objects available in the module (e.g., UIControls), while the Procedure box (upper right)
lists all the event procedures for the object selected in the Object box. If you choose an object
and an event procedure for which there is already code, the module will scroll to this
procedure. Otherwise, a new event procedure definition will be created.
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 provide inside (between) the wrapper lines will be executed
when the event is triggered.
The example
In the example above, UIButtonControl1 was chosen in the object list. Upon pulling down the
procedure list, the five available event procedures for UIButtonControl1 are displayed. After
Click is chosen from the procedure list, wrapper lines are automatically added to the code
module (Private Sub … End Sub). The code inside the wrapper lines will execute when
UIButtonControl1 is clicked 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)
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 2-26
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 class 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
Class module
Class modules are used to design custom classes. The ArcObjects library already has classes
such as Maps, Layers, Symbols, and PageLayout. By writing code in a class module, you can
define your own class to use in your programs. The specifics of programming a custom class
will be discussed in more detail in Lesson 5.
UserForm Module
UserForm modules are code modules associated with a form (dialog). In the Visual Basic
Editor, you can design a form by adding and rearranging controls (CommandButtons,
TextBoxes, 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 controls 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: List all required inputs
Return Type: Type of data returned (functions only)
Parameter
List
Scope Name
Return
Type
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 2-28
Scope
Scope defines how widely a procedure may be used and can be defined as either Public or
Private. A procedure 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.
Parameters
The 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 additional input to work
properly, and this is where any required inputs (parameters) can be defined. If you were
creating an AddLayer procedure, for example, you would probably define a layer as a required
parameter. Notice that the parameters are 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 definition 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 (double-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 not the procedure should be called from outside its own code
module. A procedure that enables controls on a particular user form would probably have a
private scope because no other form would need to call that procedure. A procedure that
calculates a total area value would probably have a public scope because this procedure would
be useful for other modules to use.
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 never run unless they are explicitly told to. You can
tell a subroutine or function procedure to execute in one of the following ways.
From code
Subroutine and function procedures 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
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 ArcCatalog
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 category on the Commands tab.
Macros you find there can simply be dragged onto the 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, you may right-click the macro and choose Change Button Image.
Introduction to Programming ArcObjects with VBA The VBA development environment 2-32
Getting help
F1 key for context-sensitive help
ArcObjects Developer Help
ArcGISDeveloperonline.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 documentation available
for Visual Basic as well as help specific to using ArcObjects. In addition to the traditional
sources for help described below, there are several utilities available in the Visual Basic Editor
for helping you write code. You will be exposed to several resources for help throughout the
course.
Context-sensitive help
You can obtain context-sensitive help by highlighting a word in your code and pressing the F1
key on your keyboard. If the word you highlight is related to Visual Basic, the Visual Basic Help
will launch and take you directly to the appropriate Help page; if the highlighted piece of code is
related to ArcObjects, the appropriate ArcObject Help page will open.
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
Introduction to Programming ArcObjects with VBA The VBA development environment 2-34
Visual Basic code:
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 Visual Basic code: How, where, and when? 3-1
Lesson overview
How?
Object-oriented programming
Visual Basic syntax
Application and ThisDocument variables
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 Basic code. You will learn
about object-oriented programming, basic VB syntax, creating user forms, and coding various
user events. This lesson will answer the following 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 customizations?
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, symbols, tables, …
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 3-3
Introduction to Programming ArcObjects with VBA Visual Basic code: How, where, and when? 3-3
Example: Object-oriented terms
Car Map
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 3-4
Properties
As described on the previous page, properties are characteristics of an object and are generally
nouns (color, for example). 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
MapUnits. Notice that the property is a noun, indicating that it is some characteristic that the
Map has. Similarly, an everyday object like car has a horsepower characteristic.
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 method 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 associated 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). Likewise,
a Map can respond to the user making a new selection by executing some code that you provide
(events will be covered in more detail in a later lesson).
Introduction to Programming ArcObjects with VBA Visual Basic code: How, where, and when? 3-4
How: Visual Basic syntax
Get the value of a property with Object.Property
MsgBox "The map name is " & myMap.Name
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 3-5
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 properties 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 updated 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 = SomeFunction (Arg1)
Example:
theAnswer = MsgBox ("Continue?", vbYesNo) 'This returns either vbYes or
'vbNo and stores the value in theAnswer
MsgBox "Continue?", vbYesNo 'This displays a message 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
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 will serve as the starting point
for much of your code: Application and ThisDocument. These object variables are always
available as soon as you launch ArcMap or ArcCatalog. While the number of methods and
properties that are available on these variables is fairly limited, they serve as a stepping stone to
other objects you might want to program with (maps, layers, files, etc.).
Application
Application is a preset variable that points to (you guessed it) the current application. In
ArcMap, Application refers to the ArcMap application, while in ArcCatalog, it refers to
ArcCatalog. In either environment, the Application variable will always 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 property that will always return the name of the application as a string
(ArcMap or ArcCatalog)
• RefreshWindow: a method to redraw the application window
ThisDocument
The ThisDocument preset variable points to the document that is currently open in the
application. In ArcCatalog, ThisDocument always refers to the Normal.gxt template, while in
ArcMap it refers to the current map document (.mxd). Unlike the Application preset variable,
there are some differences in the methods and 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 properties 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,
UtahMap.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 typed
If the list is not displayed, the object is not recognized
PressTab,
Press Tab,
Enter, or
Enter, or
Space
Space
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 3-9
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 completion described above for object methods and properties,
there is a way to automatically 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 name
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 variable.
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 interaction
More sophisticated than message boxes and input boxes
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 3-11
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 written 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: Displays a list of values from which the user can select (one or several items).
ListBoxes 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
Codemodule
module
Properties
Propertieswindow
window
Form
FormDesigner
Designer
Toolbox
Toolbox
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 3-13
Designing a form
Remember that a form consists of a design window and a code module. A new user form will
simply be an empty form designer to which you can add controls and an associated empty code
module. By clicking and dragging from the toolbox to the form designer window, you can add
several types of controls to the form. At design time for a form (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.
Introduction to Programming ArcObjects with VBA Visual Basic code: How, where, and 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
Naming controls
One property that is common to all controls (and to the form itself) is the Name property. While
the user will never care (or even know) what your controls are named, this property is very
important to the programmer. In your code, you will always 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 type 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, followed by a
description of what the control does (often this description will correspond 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.
See the Microsoft Web site listed below for a comprehensive list of recommended naming
conventions:
http://msdn.microsoft.com/library/default.asp?url=/library/en-
us/vbcon98/html/vbconcodingconventionsoverview.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 reveal its code
Each control on a form has several event procedures
Code
CodeModule
Module
Form
FormDesigner
Designer
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 3-16
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
strFTemp = ( txtCelsius.Text * 9 / 5 ) + 32
lblFahrenheit.Caption = "Fahrenheit: "& strFTemp
End Sub
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 3-17
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 respond. 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 different 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 Event Example
UserForm Initialize Set variables, fill combo or list boxes
TextBox Change Enable/Disable controls according to what is entered
KeyPress Check for a valid character before writing it to the
TextBox (e.g., numeric values only)
CommandButton Click Execute code with values on the form
(e.g., TextBoxes), close the form
OptionButton Click 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. The default events for several Visual Basic controls are listed below.
Object Default Event
UserForm Click
CommandButton Click
TextBox Change
Label Click
CheckBox Click
ComboBox Change
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)
Object
ObjectList
List
Procedure
ProcedureList
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 events related to the document.
In ArcCatalog, the document is simply the Normal template (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 three documents: the Normal template (normal.mxt), a base template
(*.mxt), or the map document itself (*.mxd).
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 event (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 (*.mxd)
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 document (*.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
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 degrees
Test and debug the form
Work with preset variables
Application
ThisDocument
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 3-23
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
Using variables
Introduction to Programming ArcObjects with VBA
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA
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.
Decision-making structures
• If Then
• Select Case
Variable scope
• Procedure
• Module
• Public
This lesson will discuss the use of variables to contain simple data types, such as numbers
and text. The use of object variables will be covered in a later lesson.
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 4-3
Sparky
Sparky
strDog
A
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects 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 when you need it.
Declaring variables
To create a variable, you can declare it. Declaring a variable accomplishes two things: first,
it specifies the name for your 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
declare all variables before you use them (and it is very poor programming technique 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 on the following slide).
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 give you an error). As the name
implies, Dim defines what will be stored in your variable and therefore the amount of
memory required for it.
There are three parts 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 will 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. Using mixed case in variable names will allow for easier
debugging later (as you will 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.
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 evaluated on the
right side of the equal sign will be stored in the variable. Variables may be given a value
explicitly, or may derive a value from a calculation, function, or object property.
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 MsgBox and InputBox. As a
programmer using these functions, you can treat them simply 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.
In addition to using the standard Visual Basic functions, you may want to write your own.
Functions can make your life easier as a programmer because they give you the ability to
centralize useful pieces of code into reusable units. For example, you might write a function
that returns the average area for a polygon layer. Anytime you need this functionality, you
can simply call your function, passing in the required layer argument, instead of having to
rewrite the functionality (sub procedures can also be reused to perform common tasks; they
cannot, however, return a value).
IsNumeric
IsNull
TypeName
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
Connectors
In order to check several criteria and return a single Boolean value, you can string together
more complex expressions by using connectors such as and, not, and or. To return a True
result, both conditions of an and statement must be true; only one condition of an or
expression needs to be true to return a True result. The not connector is used to reverse the
result of an expression.
Expression Evaluation
13 < 108 True
"Bob" < > "Sally" True
"Bob" = "Sally" False
13 < 108 AND 10 > 25 False
13 < 108 OR 10 > 25 True
NOT 1 > 99934599 True
"ArcMap" Like "Arc Map" False
'Syntax example:
If a condition is true Then ?
'do something...
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 making mechanism in
your code. There may be situations in which your program will break under certain
conditions such as dividing by zero. In order to avoid such pitfalls and to gracefully handle
these situations, you can write an If Then statement 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!!" 'ÅThis code only
'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
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.LayerCount > 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
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 4-15
Exit Sub
When the Exit Sub line of code is encountered, execution of the procedure is terminated
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 want to verify that the input is numeric (e.g., 20.00 instead
of $20.00, or twenty) 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 'Å check to see if the input is
NOT
'numeric
MsgBox "Please enter only numbers!", vbExclaimation,
"Exiting"
Exit Sub 'Å**Stop execution of the procedure if the error-
'causing condition is true!**
End If
dblDiscount = dblPrice * 0.20 'Å calculate a 20% discount on the
'price, this line will only execute if dblPrice is numeric
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 programmer 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 intBirthDay
Case Is < 0 'Å **evaluate a relationship
MsgBox "C’mon! You aren’t even born yet??!!"
Case 1 To 5 'Å **evaluate against a range
MsgBox "Enjoy yourself before you begin school!"
Case 16, 18, 21 'Å **evaluate against a list
MsgBox "Your next birthday will be a landmark!"
Case 55 'Å **evaluate against a single value
MsgBox "Congrats! You’re eligible for the Senior
Discount!"
Case Is > 100 'Å **evaluate a relationship
MsgBox "Willard Scott will read your name on the air!"
Case Else 'Å **if none of the cases above are true
MsgBox "There’s nothing interesting about your next
birthday"
End Select
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 lifetime 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 throughout 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.
'Procedure1
Private Sub cmdSet_Click()
Dim intNumber As Integer 1
intNumber = intNumber + 1
lblnumber.Caption = intNumber
End Sub
'Procedure2
Private Sub someOther_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 ArcObjects with VBA 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 declared using the Dim
statement inside a procedure (sub or function). Any variable that is declared inside of a
procedure will automatically be procedure-level in scope.
Procedure-level variables are re-dimensioned each time the procedure executes. 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 Static variables, which will be described
later).
The example
In the example above, the first procedure declares a procedure-level variable called
intNumber. When the procedure is executed, the Dim statement will create this variable and
initialize 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 re-
created (and set to 0) when it runs again. This means the label will always read ‘1’ no matter
how many times 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.
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 destroyed after the
execution of a procedure. Therefore, the values of module-level variables can be retained
and referenced (or changed) by any procedure inside the module. 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 module, form module,
or class module). To declare a module-level variable, simply place the declaration statement
in the module’s General Declarations section (which 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. There is no difference between using Dim or Private in a
module-level variable declaration, 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, they cannot be initialized (set) there. You can only assign values to a variable within
a procedure.
Copyright © 2001–2004 ESRI. All rights reserved. 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 them truly global
variables.
Public-level variables can be declared in any code module (standard module, form module,
or class module). To declare a public-level variable, simply place the declaration statement
in the module’s General Declarations section (just as you would for a module-level variable).
The declaration statement for a public-level variable must use the Public keyword.
Although module-level and public-level variables are always declared in a module’s General
Declarations section, they cannot be initialized (set) there. As a reminder, values are always
assigned to any variable inside a procedure.
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 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 they were declared, they
have the advantage of remembering their last value. In other words, each time you call a
procedure that uses a static variable, you can get at its last value.
The Static keyword is used to declare procedure-level variables only. You cannot declare a
module-level or public-level variable with the Static keyword. Module-level and public-level
variables are, by nature, static. They retain their values until their associated module or
project are unloaded from memory.
The example
Remember the earlier example for procedure-level variables? In that example, the Dim
statement was used to declare the variable, which meant that the variable’s value would be
destroyed each time the procedure finished and then reinitialized (to 0) when the procedure
was called again.
In the example above, intNumber is still procedure-level in scope, which means it cannot be
recognized outside of this procedure (Private Sub Count). Its value, however, will 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 the user calls the procedure
(clicks the Set button).
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 4-25
class
Lesson overview 5-2
Class
Classes and objects
Class libraries
contents
5-3
5-4
5-5
ArcObjects Class Libraries 5-6
Exploring class libraries with the
Object Browser 5-7
Object Browser icons 5-9
Creating objects at design time 5-10
Instantiating an object in code 5-11
To Set or not to Set? 5-13
Coding a class with Visual Basic 5-14
Client and server environment 5-15
Distributing your classes 5-16
Demonstration: Creating a
simple class 5-17
Exercise 5 overview 5-18
Programming
with class
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA
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 class
New
Ferrari Ferraris
Class
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 objects created
from the class will look and behave. A class defines all the properties and methods that a
particular type of object will have.
As a familiar example, all the command buttons you have added to your Visual Basic forms
belong to the CommandButton class. The CommandButton class defines all properties,
methods, and events that any CommandButton object will have. In other words, every
CommandButton 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 will look exactly the same? Of course not.
Although the same properties, methods, and 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 type 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 provide a good analogy for classes and the objects they create. You can think of the car
factory as the Class. The factory knows how to produce a certain type of car—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 definition.
Map class
Label
Extent
Layers
Scale
Projection
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects 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 for how an object will look
and behave. In this respect, a class is abstract; it is not real. An object, on the other hand, is a
concrete thing that has been created from a class. An object, of course, has all the
characteristics and behaviors that have been defined on the class, but it is a real object that can
be manipulated in your code. In other words, you are able to get and set an object’s properties,
call its methods to carry out tasks, or write code to respond to its events.
An ArcObjects example
There is an ArcObjects class called Map. The Map class defines the properties and behaviors
that all maps have. Obviously, this does not mean that all maps you work with in ArcMap will
be identical—simply that they will all have the same familiar properties such as Scale, Spatial
Reference (Projection), and Layers (none, one, or several). Every map is produced from this
same mold, ready to be manipulated by the map user.
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 within 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 library 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 worked with to create user forms such as Forms, CommandButtons, and
TextBoxes. All of the ArcGIS objects are defined in ArcObjects libraries and contain classes
such as Map, Layer, Polygon, and Table.
Geometry
Cartography
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 libraries, based on
functionality (Geometry, GeoDatabase, Cartography, Editor, etc.). This is to allow for smaller,
more manageable and modular arrangement of the classes. If you click on Tools > References
in the Visual Basic Editor, you will notice that all of ESRI’s class libraries are referenced for
you. These libraries are 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 regarding this
class, including the class library it’s contained in (ESRICarto). There is 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\ArcGIS
\DeveloperKit\tools if you install the Developer Kit with ArcGIS Desktop.
Further discussion on the various class libraries will be left for Lesson 17 and the Extending
ArcGIS Desktop Applications instructor-led course.
Library
Library
list
list
Search
Search
string
string
Search
Search
matches
matches
Classes
Classes Properties
Properties
list
list and
and
methods
methods
Arguments
Argumentsandand
return
returnvalues
values
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 5-7
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 class 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 these 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 the same ones that appear in the Visual Basic code completion list when
you are typing your code.
Objects
Objects
Class
Class
Class
Class Library
Library
Object
Object Properties
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 development 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 interactive environment with objects such as forms and
controls.
CallPet
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 referred to as run time.
The example
The code above works with a class called Dog. By looking at the simple 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 class (arrows for methods, boxes for properties).
As programmers using the Dog class, 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 referred to as Server code, while the code that uses a Dog object is called Client code. The
server provides a service that the client (somewhat ignorantly) takes advantage 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 code declares a variable of the appropriate type, Dog. The variable is then
instantiated (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.
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 5-13
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 5-14
Server
Server Client
Client
Map Table
MyClass ArcObjects Libraries
Layer
Text Box
Form
Microsoft Forms Library
Command Button
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 5-15
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 5-16
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 goes for saving modules to template files.
Anyone using a template has access to that template’s code modules.
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.
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 5-18
storm
Lesson overview 6-2
Introducing COM
COM classes have interfaces
Working with ArcObjects
contents
6-3
6-4
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
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 restricted to developing with a proprietary language
(e.g., Avenue or AML). In the basic object model approach, only the original GIS software
vendor has complete customization capabilities and is free from performance and functionality
bottlenecks. Also, because of the closed nature of the object model approach, users are bound
to proprietary macro languages for their customization efforts. With the object component
approach, users can extend the data model with exactly the same technology 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-supplied 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. When 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, you can only use one interface. However, after
instantiation, you can query for any other interface.
Polymorphism
Classes can share the same interface but have unique 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 applications
Independent of programming language
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 language. COM is a
binary specification that establishes a common method of building software components. These
components can then be dynamically interchanged between applications.
The Country class of the previous lesson can only be used in Visual 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 access to source code, header files, or object libraries in order to extend the system,
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 works; he or she only
needs to know what the class is able to do. Because the ArcObjects are COM classes, you can
easily work with them in conjunction with other COM objects and applications.
Technologies
There are many terms in circulation that refer in part to COM: OLE DB, ActiveX, DirectX, and
so on; all are technologies based on the COM specification. COM provides support for
distributed computing, which is often referred to as DCOM. COM components that interact
with each other 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 operating 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 RaceCar
IDrive Fuel IDrive Fuel
Accelerate Accelerate
Brake Brake
IGarbage Dump IRace LapTime
PickUp 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 communication between COM
components happens via the components’ interfaces. Interfaces 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 interfaces?
Some object-oriented programming languages use only classes and objects without interfaces.
Problems can arise when a class needs to be updated and code 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 player. But what if you own cassettes, not CDs? Programming with interfaces
would allow the dealer to install the new CD interface without changing or removing the
cassette interface.
Interfaces solve this problem of evolving code. Once written, code for an interface never
changes; therefore, client code is less likely to break. The client code can assume an interface
will never change. If the class needs to be reprogrammed, new interfaces are created. The class
evolves without causing headaches for the existing client code.
When a new interface comes out, the class stays the same, but the client can interact with the
class through the newest 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
IDrive Fuel
Dim pGarbage As IDrive
Set pGarbage = New GarbageTruck Accelerate
Brake
pGarbage.Fuel = "Full" IGarbage Dump
pGarbage.Accelerate
PickUp
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 through interfaces. You need to remember
that methods and properties are not available 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 properties.
How do I know which interface to use?
Before writing your code, you need to understand the interfaces that are available for the
objects you are using and which ones contain the methods and properties you require. The next
lesson will discuss 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 Browsers will be
discussed.
How do I specify the interface I want to use?
The interface used to work with an object is specified when the object variable is declared.
When you declare a variable as a pointer to a particular interface, that variable can be used on
any object that uses (supports) that interface. Only the methods and properties that exist on that
interface may be used, however, and a programmer 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 interface. Variables
are declared as an interface; they are instantiated, however, to point to a specific object. In the
example above, pGarbage is set equal to a new 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 is selected, will not hear the radio
IRadio
ITape
ICD
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 6-6
The example
The code above shows an example of a common error when programming with interfaces. 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, would 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 associated with an interface;
the code associated with an interface comes from a class implementation. An interface defines
properties and methods of an object that chooses to implement the interface. How that interface
is implemented can be different depending on the object. The objects inherit the type of
interface, not its implementation, so it is called Type Inheritance.
A programmer who defines an interface simply provides definitions for how an object should
be interacted with. 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 method called
Accelerate to speed the vehicle up, and one called Brake to slow it down. The programmer also
decided that these two methods will not have any arguments 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 choose to support a given interface can decide
how each method and property should be executed. In the example above, every vehicle could
implement the IDrive interface. If this were the case, each vehicle could potentially carry out
each method and property differently.
Even though a boat, for example, would accelerate differently than a horse and buggy, the code
a programmer uses to call Accelerate on the IDrive interface would be the same.
Dim pWagon As IDrive Dim pTitanic As IDrive
Set pWagon = New HorseAndBuggy Set pTitanic = New Boat
pWagon.Accelerate 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 file types (shapefile, map, table, etc.)
IActiveView: Map (data view) and PageLayout (layout view)
Several others …
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 6-8
ILayer
All layers that can be brought into ArcMap support the ILayer interface. There are, of course,
several different types of layers: FeatureLayers (point, line, polygons), RasterLayers (images),
and GraphicsLayers, 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 with 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 location on disk) and can be opened, saved, edited, or closed, these
properties and methods 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
functionality that is common to both views such as refreshing the display, getting the visible
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 methods, set properties
'Create a new RaceCar with IDrive RaceCar
Dim pDrive As IDrive IDrive Fuel
Set pDrive = New RaceCar
Accelerate
pDrive.Accelerate
Brake
pDrive.Fuel = "Full"
IRace LapTime
pDrive.PitStop PitStop
To work with an ArcObjects COM class, you need to dimension a variable that points to an
interface supported by that class. Dimensioning an interface variable, however, does not give
you access to any particular object; it simply defines how you will eventually communicate
with the object once it is referenced.
The next step, therefore, is to initialize the variable to point to an actual object. Some objects
can be created by using the New keyword, while others can only be returned from another
object (a Table can create a Row, for example). Once you point your variable to a specific
object, you can use any methods or properties that exist on that particular interface. The code
above, for example, returns an error because the PitStop method exists on an interface other
than the one you used 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 RaceCar
pDrive.Accelerate IDrive Fuel
Q I Accelerate
'Switch interfaces
Brake
Dim pRace As IRace
Set pRace = pDrive IRace LapTime
pRace.PitStop
PitStop
pDrive.Accelerate
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 interfaces, you may need to declare more
than one variable when working with a single 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 of interfaces is that,
contrary to other programming they may have done, one object does not mean one variable. In
fact, you may require several variables to work with a single object in your code.
QueryInterface
The term QueryInterface refers to the process of using additional interfaces on the same object.
You will hear this term used often throughout this course, and in the code you will often see it
abbreviated as ‘QI’.
Here is the basic form for QueryInterface:
Dim A As IInterfaceA
Set A = New SomeObject 'This instantiates the object variable (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 the IDrive interface. This
variable is then used to access any methods or properties 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 method, 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, so the next
step is to instantiate the pRace variable.
A common mistake at this point 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 IRace
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 variables 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 to 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
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 object 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 variable was properly
instantiated. This is particularly important for code that relies on the user to provide input. By
using an If/Then structure like the one above, your code can handle invalid input a little more
gracefully by reporting the error to the user and then stopping execution of the procedure.
Nothing is used 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 that 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 the selected layer is not Nothing (as described above).
Next, you would need to evaluate 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 statement is:
If TypeOf SomeObjectVariable Is SomeInterface Then …
What the TypeOf statement is really asking is, Does this object support this interface? 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 'ÅYou can be sure that this
'layer supports IRasterLayer
End If
Introduction to Programming ArcObjects with VBA COM before the storm 6-13
COM class code
Class module
Implement methods
and properties
Server
Interface module Interface
Interface
Define methods and
properties
Client module
Instantiate class
Client
Use methods and
properties
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 6-14
Interfaces
To create an interface, simply write the stub code for methods (subs or functions) and
properties you want to define. When developing an interface, you need to make sure you
produce a group of methods and properties that form a logical group. It is also the interface
developer’s duty to define any parameters required for the methods defined and whether
properties are read-only, write-only, or read–write.
Class modules that define interfaces are generally named with a leading ‘I’ (e.g., ICountry).
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 will support. By using the Implements
statement, a COM programmer is agreeing to write code for every method and property that
has been defined on the interface. Remember that it is the Class module that actually
implements (performs some action) for methods and properties; therefore, other Class modules
could implement the same interface and use different code for the interface’s procedures
(polymorphism).
Introduction to Programming ArcObjects with VBA COM before the storm 6-14
Clients and servers
Classes, such as the ArcObjects, provide a service. A programmer using these classes does not
need to know how the code works inside (and there 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 provided.
As an ArcObject programmer, you will spend the great majority of your programming time
writing client code. As the name implies, client code is code that simply takes advantage of
services provided by pre-defined classes. Client code uses objects that have been defined by a
server (a class library, DLL, or class 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
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 potential conflicts with class or interface names
between different libraries. Some class 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 that 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
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 with 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 defining 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
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
Understanding object
Introduction to Programming ArcObjects with VBA
model diagrams
Lesson overview 7-2 Finding the right OMD: Step 3 7-20
ArcObject object model diagrams
Relationship symbols
ArcMap objects
7-3
7-4
7-5
Finding the right OMD: Step 4
Where to begin? Getting into
the OMD
contents
7-21
7-22
Creatable Class (CoClass) 7-6 Example: MxDocument > Map
Instantiable Class (Class) 7-7 > layer 7-23
Abstract class 7-8 Exercise 7B overview 7-24
Inheritance 7-9
Property and method symbols 7-10
Getting properties 7-11
Setting properties 7-12
Finding interfaces 7-13
Wormholes 7-14
Exercise 7A overview 7-15
Lesson overview 7-16
Finding object model diagrams 7-17
Finding the right OMD: Step 1 7-18
Finding the right OMD: Step 2 7-19
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
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 between classes
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 classes are
defined in a series of libraries with an .olb extension that work together to create this one
conceptual object model. With a default installation, these 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 subsets of ArcObject classes, can be used to determine how one ArcObject is
related to 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 model diagram.
You will find the object model diagrams useful for answering the following questions …
• Which interfaces does this class support?
• Which objects will 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, however, are not the only source of help you will use when writing
code. The diagrams are commonly used in conjunction with other sources of help, such as the
Visual Basic object browser and ArcObject class help. The diagrams, for example, are not
designed to always answer these questions …
• What methods and properties are on this interface?
• Are there any hidden methods or properties on this interface?
• 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 Bird Nest
CoClass
Abstract
Creates a
Multiplicity *
_____ Chicken Feather
Association CoClass * Class
2
Egg
Class Wing
Class
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 7-4
Introduction to Programming ArcObjects with VBA Understanding object model diagrams 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 points to the currently running
application (ArcMap or ArcCatalog). In the simplified object model shown above, you can see
that the ArcMap Application object is composed of (¡) exactly one MxDocument object. This
relationship is more than simple 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 user interface. Again, in this
composed of relationship, the Map could not exist independently of an MxDocument.
A Map, in turn, is composed of (¡) potentially several (*) Layer objects. Layer is an abstract
class that has several subtypes (U), such as RasterLayer, TinLayer, and CadLayer.
FeatureLayers are Layers that are based on a shapefile, coverage, or geodatabase dataset, such
as the States layer 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
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 creatable (CoClasses). In ArcMap, for
example, you may want to create new Maps, FeatureLayers, FillSymbols, or GraphicElements.
Although objects can be created new from a coclass, an ArcObject programmer might still want
to access existing instances 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
though you could, it is a coclass), but instead would reference the existing FeatureLayer 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
Class
Some objects in the ArcObject libraries can only be created from another ArcObject. Referred
to as Instantiable Classes or sometimes just Classes, instances of these classes are often created
by the object that will contain them. A Table object, for example, can create new Rows, a
FeatureClass can create new Features, 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
proper context. This makes more sense than creating a brand new Row, for example, and then
having to place it in the appropriate Table.
Attention
Although instances of instantiable classes must always be obtained from another object, you
will not always find the ‘creates a’ (---X) relationship explicitly listed on the diagram for these
classes. On the Geodatabase OMD, for example, there is no dashed arrow between the
Workspace and Table classes. Upon scanning the methods on the Workspace class, however,
you will find that a Workspace can indeed be used to create 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
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 7-8
Abstract classes
As the name implies, an instance of an abstract class cannot exist (in your code) as a concrete
object. Abstract classes are used only to organize 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 (U). In the example above, Layer is an abstract class that
is used to organize a set of subtypes, such as CoverageAnnotationLayer, FeatureLayer, and
TinLayer. Because of the superclass-subclass relationship, a programmer working with any
subtype of Layer can use all the interfaces defined on Layer (ILayer or IGeoDataset).
The concept of the abstract class exists in your daily lives as well. When you talk about a Car,
for example, you are talking about an object that has a certain set of characteristics (properties)
and has certain things it can do (methods), but does not really exist as a concrete object. In other
words, although you know a Car can accelerate and has an engine, you never 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
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 7-9
Type of Inheritance
Type of Inheritance is what you will typically work with when using ArcObjects. Type of
Inheritance is provided by the Type of relationship on the Object Model Diagrams. For instance,
on the last slide Abstract Classes were discussed. Any class below an abstract class will inherit
all interfaces on the abstract class 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 interface on the Object Model Diagram, the first line before all methods and properties
will indicate which interface is being inherited. In the example above, it is shown as
IFeatureClass: IObjectClass. This means that IFeatureClass inherits from the IObjectClass
interface.
The majority of ArcObject interfaces will inherit from IUknown, which provides the backbone
for how COM classes are created and the 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 interface 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, the code completion will show properties and methods for both IFeatureClass and
IObjectClass. IObjectClass also inherits from IClass, which means IFeatureClass inherits 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
PropertyGet
Get Property
PropertySetSet
(read)
(read) (write)
(write)
Method
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 7-10
Introduction to Programming ArcObjects with VBA Understanding object model diagrams 7-10
Getting properties
Return a value
Name: String
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
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 7-12
There are two ways in which a value may be assigned to an object property, by value 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 someObjectVariable.PropertyX
In the example above, even though the value of valueY changes later in the program,
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 anotherObjectVariable.PropertyB
When a property is assigned with a reference, there is a dynamic association between 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 property.
When to use set
Notice that you must use the Set keyword when assigning a property 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 assigning a value to an object property. The symbols described above
will indicate which method you must use.
Introduction to Programming ArcObjects with VBA Understanding object model diagrams 7-12
Finding interfaces
Lollypop symbols ( )
Inherited
Inherited interfaces
interfaces are
are available.
available.
This
This interface
interface is
is used
used by
by the
the class.
class.
All
All methods
methods and
and properties
properties are
are listed.
listed.
These
These interfaces
interfaces are
are available.
available.
Must
Must look
look elsewhere
elsewhere for
for specific
specific
methods and properties
methods and properties
(e.g.,
(e.g., Object
Object Browser).
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 writing your code.
Object model diagrams are useful for showing all the interfaces supported 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 the Map class, for example, you will find a listing for IMap, which is the
interface you would be most likely to use. You will also be able to identify other interfaces
supported by the Map class, such as IMapBookmarks, without a complete listing of its methods
and properties. Once you know that the Map class supports the IMapBookmarks interface,
however, you can use the object browser (or other help tool) to find more specific information
about that interface.
Keep in mind that when you see the inheritance (U) 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 following books or Web pages related to COM programming:
David Chappell. Understanding OLE and ActiveX. Microsoft Press, 1996.
ISBN 1-57231-216-5.
Wayne S. Freeze. Visual 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
Layer Class
Class on
on
Carto
Carto Layer OMD
Layer OMD Element
Element Class
Class on
on
Carto
Carto OMD
OMD
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 7-14
Remember that there is only one ArcObject object model. All of the ArcObject classes are
defined in multiple libraries, and all of these classes are somehow related 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 related to a class on another diagram, a Wormhole is used to
indicate the related class and the diagram on which it appears. As a programmer, this is your
bridge that 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
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 about relationships illustrated there.
You will then move on to interpret the ArcObjects diagrams to answer similar questions and
then to write some code in ArcMap 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
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 > Developer 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
You will also find object model diagrams included with your training material. Your class
database CD contains Adobe Acrobat versions of each diagram, in addition to the three poster-
sized hard copy diagrams that you have been provided (ArcMap, Map Layer, and Geodatabase).
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
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, and methods) are stored in
libraries. Many libraries are used to package all the ArcObjects. Each library is listed in the
ArcGIS Developer Help. The example above, shows the ArcMapUI Library, which contains the
MxDocument class as seen on the last slide. The help panel also shows all the other interfaces
the ArcMapUI library contains. You could click on an individual interface to find the members
of 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
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 7-20
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 Name of
Class from Step 1 OMD/Library
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 7-21
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: IDocument interface of the MxDocument object
Application
ArcMapUI OMD
ThisDocument
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 7-22
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 ( * )
MxDocument
Get a layer from the the Map
Many types of layers ( ) *
Map
Dim pMxDoc As IMxDocument
Set pMxDoc = ThisDocument
Dim pMap As IMap *
Set pMap = pMxDoc.FocusMap Layer
Dim pLayer As ILayer
Set pLayer = pMap.Layer(1)
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 7-23
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 caption
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 determining which objects and classes you need to
use. This exercise is intended to show the relationships between classes and symbology on the
Object Model Diagrams. The following exercises will provide more detail about the specific
classes and objects you use.
Introduction to Programming ArcObjects with VBA Understanding object model diagrams 7-24
Maps and layers
Introduction to Programming ArcObjects with VBA
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA
Enumerations
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 8-2
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 number 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.
Do While and Do Until loops are used to loop based on a condition. These loops will execute
as long as (or until) a condition is true. Do While/Do Until loops are 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 statement.
Endless loops
If you have a logic error in your loop, you might get caught in an infinite loop. The most
common cause of an endless loop is forgetting to update the condition on which your loop is
iterating. If you get caught in an endless loop, use <Control>+<Break> on the keyboard to get
into Break mode (and out of the endless loop).
MxDocument
DataSet
*
Map Carto
* Geodatabase
Layer
Table
Carto Layer
0 .. 1 FeatureClass * FeatureDataset
FeatureLayer
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. Because of how the
object model diagrams are organized, the objects discussed here can 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 Geodatabase, 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 dBASE).
As you already know, the ArcMap Application is composed of a single MxDocument object.
The MxDocument is composed of several (indicated by the asterisk, *) Map objects, which
are also composed of several Layers.
Layer is an abstract class. 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 geodatabase
format). A FeatureLayer has either 0 or 1 associated FeatureClass object (indicated by the
0 .. 1 in the diagram).
Notice that a FeatureLayer’s associated FeatureClass is listed on the Geodatabase object
model diagram. There is a wormhole between FeatureLayer on the Carto diagram and
FeatureClass in the Geodatabase diagram. A FeatureClass is the data being displayed by the
FeatureLayer (a shapefile, for example). In reality, a FeatureClass is nothing more than a
Table that also stores coordinate geometry (shape). A Table, according to the diagram above,
is a type of dataset.
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 8-5
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 8-6
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 condition 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 loop are to use either the Exit For statement
within a For loop or an Exit Do statement 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 loop 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), execution of the loop is terminated prematurely by using
the Exit For statement. Using Exit For and Exit Do can make your code more efficient in
examples such as this because it avoids the execution of unnecessary code.
Example
Below is an example 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 with this yet?"
Loop
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 8-8
Enumerations (Enums)
An enumeration, usually called an enum for short, is a package of objects contained
(managed) in a single object. It is very similar in concept to a collection. It differs from a
collection in several important aspects, however. An enum generally 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 pointer back to the top of the enum.
Notice that, unlike a collection, there is no way to (easily) reference an object by its position
(order) inside the enum. There is also no easy way to get the number of items in the enum
(such as the Count property found on collections).
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 8-9
Plates analogy
Working with any enum is like taking plates off a stack. You can take plates off one at a time
until you reach the bottom 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
collection. To begin working your way down through the stack again, you need to Reset in
order to put the stack back into its original state.
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 8-10
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 properties
pLayer.Name = "Streets"
pLayer.Visible = True
pLayer.ShowTips = False
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 8-11
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. Remember that a Layer
is nothing more than a pointer to some dataset on disk, and the symbology (and other basic
properties) used to display the data in the map. The 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 Grid (or some other image format), TinLayers to display TIN data, and
FeatureLayers 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 access the
document’s activated data frame (FocusMap). The AddLayer method is called on the Map,
and the new FeatureLayer is passed in as the only required argument. After the code above
executes, an empty layer would appear in the ArcMap Table of Contents (as shown above).
Before adding a layer, obviously, a programmer would generally set some of its basic
properties, such as its name and the data on disk that it will display in the map. You will learn
more about working with these layer properties in a later lesson.
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 8-13
The example
The code above simply gets the FeatureClass from one FeatureLayer in the map, then assigns
it as the data source for a new FeatureLayer by setting the new layer’s FeatureClass 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
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, layers in the
maps, and fields in each attribute table. You will also write code that adds a layer to the map.
creation
Lesson overview 9-2 Work with fields in a table 9-23
Data creation objects
Opening an existing Workspace
9-3
9-5
Connecting to an ArcSDE database 9-7
Exercise 9B overview
contents
Adding rows and values to a table 9-24
9-26
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA
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 will be examined:
WorkspaceFactory
Workspace
FeatureDataset
Table
FeatureClass
Fields/Field
Name
Row
Feature
Field Fields
*
1 ..
ShapefileWorkspaceFactory
Row Table
AccessWorkspaceFactory
FeatureClass
ArcInfoWorkspaceFactory
Others
Which
Which ones
ones can
can be
be created
created new?
new?
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 9-3
Workspaces
Although all Workspaces implement the same interfaces, Workspace objects come in various
forms, some of which are listed below (this is a good example of polymorphism).
ArcInfo Workspace: A directory containing 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, feature datasets, and layers
Raster Workspace: A Workspace containing grids and images
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 Workspace objects in your code to get at all these datasets (one Shapefile Workspace
and one ArcInfo Workspace).
Dim
Dim pWFactory
pWFactory As
As IWorkspaceFactory
IWorkspaceFactory
Set
Set pWFactory
pWFactory == New
New ArcInfoWorkspaceFactory
ArcInfoWorkspaceFactory
Dim
Dim pWorkspace
pWorkspace As
As IWorkspace
IWorkspace
Set
Set pWorkspace
pWorkspace == pWFactory.OpenFromFile("D:\Covers",
pWFactory.OpenFromFile("D:\Covers", 0)
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 contains the data.
Because the Workspace class is a Class (instantiable, but not creatable), a programmer must
access objects of this class from other objects. In the case of an existing Workspace, you can
use the WorkspaceFactory object to instantiate a Workspace.
WorkspaceFactory
As the name implies, a WorkspaceFactory can create Workspace objects. According to the
type of data you want to access, use the corresponding WorkspaceFactory CoClass. For
example, to access ArcInfo coverages, you need to create your Workspace using an
ArcInfoWorkspaceFactory; to open personal geodatabase feature classes, you need to create
a Workspace from an 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.
Open: use to open Workspaces that you need to connect to such as an ArcSDE database. The
Open method takes a PropertySet object as an argument, which contains all connection
information.
Both methods (OpenFromFile and Open) have a second argument being a window handle (or
OLE_HANDLE). A window handle is a long value, that the operating system assigns to each
window on your computer. Therefore, if for example, you type in the wrong path to your
directory, VBA will tie the dialog box indicating this error, with the ArcMap application. In
VBA, you may specify 0, as this is a default number that tells VBA to get the ArcMap
window handle.
hWnd
This argument is very important for the user-interface programmer. OpenFromFile and Open
might display a dialog if the 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 that 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 pass in the ArcMap application’s
hWnd.
Getting the ArcMap or ArcCatalog hWnd: Application.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.
Use IWorkspaceFactory to
retrieve a workspace
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 OpenFromFile 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 allows you to set the database connection
properties.
Note that when using the example below, the password is exposed in the code. You could get
around this by having the user fill it in through a form that you create. The password could
also be stored by creating custom components (.dlls). Creating custom components is
discussed in the Extending ArcGIS Desktop Applications instructor-led course.
Public Function openSDEWorkspace(Server As String, Instance As String, User As String, _
Pswd As String, Optional Dbse As String = "", Optional version As String =
"SDE.DEFAULT") As IWorkspace
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. ArcInfo coverages, for example,
are all FeatureDatasets. A single coverage may contain several feature types (such as
Polygons, Lines, Label Points, and Tics), each of which is a FeatureClass. A Geodatabase
might also contain FeatureDatasets, which, like coverages, can organize a set of
FeatureClasses. The concept of a FeatureDataset does not exist for Shapefiles, as Shapefiles
are FeatureClasses in themselves and cannot contain more than one feature type.
Getting a FeatureDataset
On the Workspace class, the IFeatureWorkspace interface has several methods that 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 coverages or geodatabase
feature datasets (depending on the type of Workspace you have referenced).
To open a feature dataset from a Workspace, you only need to provide the name of the
dataset, as shown in the example above.
Dim
Dim pFCC
pFCC As
As IFeatureClassContainer
IFeatureClassContainer
Dim
Dim pStreetArcs
pStreetArcs As
As IFeatureClass
IFeatureClass
Set
Set pFCC
pFCC == pCover
pCover 'QI
'QI for
for IFeatureClassContainer
IFeatureClassContainer
Set
Set pStreetArcs
pStreetArcs == pFCC.ClassByName("arc")
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 same feature type (all points,
lines, or polygons), the same set of attributes, and 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 particular ArcInfo coverage.
In a geodatabase, FeatureClasses can exist either inside a FeatureDataset or directly inside
the Workspace (both situations can exist in the same geodatabase).
Getting a FeatureClass
Using the IFeatureWorkspace interface on the Workspace class, a programmer can access
FeatureClasses that are stored directly inside the Workspace by using the OpenFeatureClass
method (this is how you would access a Shapefile from a particular folder, for example).
In the case of FeatureClasses that are stored in a FeatureDataset, a programmer can use the
IFeatureClassContainer interface on the FeatureDataset object. As the name implies, the
IFeatureClassContainer interface is used to get at the contents of a FeatureDataset.
FeatureClasses can be accessed from this interface with properties such as ClassByName,
ClassByID, or Class(index). All FeatureClasses can be accessed (and returned as an enum)
by using the Classes property.
Get
Get the
the MxDocument
MxDocument using
using ThisDocument
ThisDocument
Get
Get the
the active
active Map
Map from
from the
the MxDocument
MxDocument
Make
Make aa new
new FeatureLayer
FeatureLayer object
object
Make
Make aa new
new ShapefileWorkspaceFactory
ShapefileWorkspaceFactory object
object
Get
Get aa Workspace
Workspace from
from the
the ShapefileWorkspaceFactory
ShapefileWorkspaceFactory
Get
Get the
the FeatureClass
FeatureClass from
from the
the Workspace
Workspace
Set
Set the
the FeatureClass
FeatureClass for
for the
the FeatureLayer
FeatureLayer
Assign
Assign the
the Name
Name and
and ShowTips
ShowTips properties
properties for
for the
the FeatureLayer
FeatureLayer
Add
Add the
the FeatureLayer
FeatureLayer to
to the
the Map
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; instead, 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 structure of a Visual Basic program. After outlining a
program in pseudocode, it should be a fairly straightforward task to convert the pseudocode
into actual Visual Basic code.
The pseudocode above adds a shapefile as a new layer in the active dataframe. Does this
pseudocode help you better see the overall process? Would you find this helpful in writing
your code, or an unnecessary step?
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 or output
files. Like ArcCatalog, GxDialog lets you connect or disconnect folders or view thumbnails
of your spatial data. GxDialog will always open modally, meaning 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.
Before 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 show in the dialog box. Use the
Title and the ButtonCaption to specify text for the 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 IEnumGxObject object is provided as a
parameter.
pGxDialog.AllowMultiSelect = True
pGxDialog.StartingLocation = "C:\Esri\EsriData\Mexico"
pGxDialog.Title = "Select Files for Input"
pGxDialog.ButtonCaption = "GO!"
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 intuitive dialog
box for specifying several input files.
Notice that a required parameter for the DoModalOpen method is an EnumGxObject. This
variable will contain all files (GxObjects) selected by the user. If AllowMultipleSelect is set
to false (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 method 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 Nothing, because the user might have pressed
Cancel)
Dim pGxObject As IGxObject
Set pGxObject = pGxObjEnum.Next
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 9-13
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 9-14
IUnknown Pointer
If you look at the Open method (on IName) on the Geodatabase object 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 several classes that support the IName interface, including
FeatureDatasetName, WorkspaceName, and TableName, there is no way the diagram can list
specifically what will be returned when the Open method is called. When Open is called on a
TableName object, for example, a Table is returned. When it is called on a
FeatureDatasetName, a FeatureDataset is returned, and so on. Because all COM objects
inherit the generic interface IUnknown, the diagram lists this as the return type.
As a programmer, you would know what is actually being returned, of course, because you
would know what type of Name object you were opening.
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 9-15
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 9-17
CreateFeatureClass
CreateFeatureDataset
CreateRelationshipClass
CreateTable
Remember, the type of data you create is dictated by the type of Workspace object you
created or opened. If, for example, you use the CreateFeatureClass method on a
ShapefileWorkspace, you have created a Shapefile. If you called CreateTable on this same
Workspace, you would create a dBASE table (the table format for Shapefiles).
Creatable
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 9-18
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.
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 9-19
pFieldsEdit.AddField pOIDField
pFieldsEdit.AddField pNameField
pFieldsEdit.AddField pSalesField
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 IFieldsEdit interface to put each Field you
have defined into the collection. Each Field 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 should 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
Table without an OID field, you will receive an error.
IFieldsEdit methods
AddField Adds a field to the collection. This is a hidden method by
default.
DeleteAllFields Deletes all fields from the collection.
DeleteField (index) Deletes a field at the position specified by the index (integer).
Table
Table Name
Name CLSID
CLSID and
and EXTCLSID
EXTCLSID
(Custom
(Custom Behavior
Behavior DLLs)
DLLs)
Fields
Fields Collection
Collection ArcSDE
ArcSDE Configuration
Configuration
Keyword
Keyword
CreateFeatureClass
CreateFeatureClass takes
takes additional
additional
FeatureType
FeatureType and
and ShapeFieldName
ShapeFieldName parameters
parameters
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 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 CreateFeatureClass method on a
Workspace object’s IFeatureWorkspace interface.
The syntax for the CreateTable method is:
Set aTable = aWorkspace.CreateTable (aTableName,
aFieldsCollection,_ aClassID, _aClassExtensionID, aConfigKeyword)
aTable: A variable declared as an ITable object.
aTableName: The name of the table as it will appear on disk (e.g., Streets.dbf).
A string.
aFieldsCollection: The fields to appear in the table. A Fields object.
aClassID: A GUID that identifies a DLL used to define custom behavior for
the table. A UID object.
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 require 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 must be provided; a programmer could not
ignore this parameter.
intFieldNum = pTable.Fields.FindField("Area")
If intFieldNum > -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 ArcObjects with VBA 9-23
Members on Ifields
FieldCount: returns the total number of field objects in the collection. 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 from 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 appears 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 Fields collection. The Field
property requires an index number in order to access a Field. Use the FindField method
described above to first locate the Field’s position, then use the Field property to get the
Field itself.
You can also chain code together to access a Field from the collection, as shown
below.
pIncomeField = pTable.Fields.Field(pTable.FindField ("Income") )
Feature
Feature has
hasaa Shape
Shapeproperty
propertyto
tostore
store geometry
geometry
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 9-24
pFeature.Store
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 layer to a map.
Create a new personal geodatabase on disk.
Make a Fields collection.
Create a new table inside your geodatabase by using the Fields collection.
Add records (Rows) to the table and add new information.
geoprocessing
Lesson overview 10-2
Geometry objects
Feature geometry
Points and multipoints
contents
10-3
10-4
10-5
Segments 10-6
Polylines and polygons 10-7
Envelopes 10-8
Zooming in to a Feature 10-9
Displaying features 10-10
Geometry spatial operator
interfaces 10-11
ITopologicalOperator 10-12
IRelationalOperator 10-13
IProximityOperator 10-14
Area and length 10-15
Spatial reference 10-16
Spatial reference OMD 10-17
Exercise 10 overview 10-18
Geometry and
geoprocessing
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA
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
Measuring proximity
Examining spatial relationships
Displaying features
Geometry * Geometry
collection
Polycurve
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 10-3
1 Line 1 Poly
ArcMap geometry
When storing geometry in a geodatabase, you have the potential to create multipart features.
This means a single feature (one record in the Feature Class table) can store the coordinates
for several spatially distinct geometries.
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 of geometry such as lines or polygons. Although the above
geodatabase geometry illustration is accurate (points can aggregate to form segments,
segments to form paths, etc.), notice that any geometry can be produced directly from a
collection of points.
Multipoint with
Dim pMultiPts As IPointCollection
six points
Set pMultiPts = New MultiPoint
pMultiPts.AddPoint 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 composed of a
single pair of x- and y-coordinates. Using the IGeometryCollection or IPointCollection
interface, geometry of any type may be built with a collection of points.
A Multipoint feature is a single feature that stores the coordinates for several points. Several
locations for a single fast food chain, for example, could be represented with a Multipoint
feature.
To
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 10-6
ISegmentCollection
More complex geometry, such as paths, rings, polylines, and polygons, may be built by first
aggregating segments. The Path and Ring classes directly support the ISegmentCollection
interface, while Polyline and Polygon support the more generic IGeometryCollection
interface. ISegmentCollection has methods such as AddSegment, RemoveSegment,
AddSegmentCollection, and SegmentCount.
ICircularArc
ICircularArc has more than 30 methods. Examine the ArcGIS Developer Help for more
information.
Dim pArc AS ICircularArc
Set pArc = New CircularArc
pArc.ConstructThreePoints pPoint1, pPoint2, pPoint3
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
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, which can be
described as the feature’s minimum bounding rectangle, or extent. The Envelope property is
defined in the IGeometry interface and can be used to retrieve (but not set) any geometry’s
envelope. The Envelope class is a CoClass. This means a programmer may create an envelope
object using the New keyword.
pMxDoc.ActiveView.Extent
pMxDoc.ActiveView.Extent == pFeature.Shape.Envelope
pFeature.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 Envelope property returns the
minimum bounding rectangle for a shape (Envelope is a property 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 zooming in on the bounding rectangle of the feature.
Example: Zooming into each Feature in a FeatureCursor
Public Sub ZoomToRoads ()
Dim pQFilter As IQueryFilter
Set pQFilter = New QueryFilter
pQFilter.WhereClause = "LENGTH > 100000"
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 Display object.
Use one of the geometry drawing methods between StartDrawing and FinishDrawing
statements.
You will learn more about display and saving graphics later. For now, the Start and Finish
drawing methods draw geometry to the display area, but the geometry is not saved. This means
when you refresh the display, the geometry and its symbol will not be there. Use this quick
draw when you do not want to save the graphics.
ScreenCache options
• esriNoScreenCache
• esriAllScreenCaches
• esriScreenRecording
IProximityOperator
IRelationalOperator
Use to …
Perform familiar spatial operations such as buffer, cut, and clip
Measure distances 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. These
interfaces allow you to do things such as:
Measure distances between features.
Evaluate spatial relationships.
Produce new geometry based on spatial relationships of existing features.
Query features based on spatial criteria.
Cut Clip
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects 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 be 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 interface is supported by the Point, Multipoint, Polyline, and
Polygon geometry classes. When you are working with one of these objects, you can
QueryInterface the 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.
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 10-13
IRelationalOperator interface
IRelationalOperator is supported by the Envelope class as well as the classes that support the
ITopologicalOperator interface (i.e., Point, Multipoint, Polyline, and Polygon classes).
Working with the IRelationalOperator interface lets the programmer ask questions about a
geometry’s spatial relationship to other geometry.
Some of the relationships the programmer can check for are listed above; check your object
model diagram for all supported methods. All methods on this interface require another piece
of geometry as an argument. The resulting answer will always be a Boolean object (true or
false).
Because the IRelationalOperator interface is supported by the Envelope class, the programmer
can check the spatial relationships between the envelopes (extents) of two features.
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 10-14
IProximityOperator interface
Unlike the ITopologicalOperator and IRelationalOperator interfaces, IProximityOperator is
supported by all ArcInfo geometry classes. This interface only has a handful of methods, and
each one asks proximity questions of geometry. Using IProximityOperator, the programmer
can measure distance between geometries or locate the nearest point on one geometry relative
to another.
Polygon
IPolygon
Dim pCurve As ICurve
IPolygon: IPolycurve
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) and polygons. You
can work with the ICurve interface by performing a queryinterface to an existing piece of
geometry. You then will have access to the length.
IArea is an interface that allows you to work with the area of polygons. Like ICurve, 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 pointer to IPoint, the center of gravity of the
polygon.
Both the area and length return 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.
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 10-16
Unknown
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 10-17
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 10-18
and selections
Lesson overview 11-2
Object Model overview
SelectionSet
Cursors and FeatureCursors
contents
11-3
11-4
11-6
Creating a QueryFilter 11-7
Returning a Search cursor 11-8
SpatialFilter 11-10
Three types of cursors 11-12
Accessing records in a cursor 11-14
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
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
FeatureCursor
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 records with ArcObjects. In
this lesson, you will learn:
How to get an existing selection 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
… using 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 display 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
QueryFilter
SpatialFilter
FeatureCursor
Feature FeatureClass
== ‘in
‘in conjunction
conjunction with’
with’
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 11-3
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 (TableWindow)
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects 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 common for an ArcObjects programmer to get the selection
directly from the FeatureLayer or TableWindow in which the user is working.
The example above shows the easiest way to get the selection from a FeatureLayer in a map.
The FeatureLayer class supports the IFeatureSelection interface, which allows you to get at
selected features by using the SelectionSet property. By dimensioning a variable as the
IFeatureSelection interface, you can QueryInterface from a FeatureLayer (the example 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 the 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 retrieve selected rows. Use the SelectionSet property on
ITableWindow to get a SelectionSet object as shown below.
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., selection)
AA Fields
Fields property
property for
for accessing
accessing attributes
attributes
•• Same
Same fields
fields and
and order
order as
as the
the parent
parent table
table
Methods
Methods for
for working
working with
with records
records
(rows
(rows or
or features)
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 in a Cursor can be defined
using spatial criteria, attribute criteria, or both. Once a Cursor is produced, you will have a
convenient mechanism for looping through 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 FeatureClass from which the Cursor was derived. These fields are in
the same order in the Cursor 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 objects have several methods for working with their content rows or features.
Depending on the type of Cursor you work with (the three types of Cursors will be covered
later), you will have methods for inserting, deleting, updating, or simply accessing 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 with in your application. If you want to display these
records as a visible selection 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 QueryFilter
QueryFilter
keyword
Set the WhereClause property
(string)
Dim
Dim pQFilter
pQFilter As
As IQueryFilter
IQueryFilter
Set
Set pQFilter
pQFilter == New
New QueryFilter
QueryFilter
pQFilter.WhereClause
pQFilter.WhereClause == "LENGTH
"LENGTH >> 100000"
100000"
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, they can be created with
the New keyword. Before producing a Cursor or FeatureCursor from a dataset (Table or
FeatureClass), you need to have a QueryFilter or SpatialFilter to define your selection criteria. A
QueryFilter object has a WhereClause 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. SpatialFilters are discussed in
more detail on a later slide.
SQL syntax
The SQL syntax of your QueryFilter’s WhereClause expression should use the format of the data
you are querying. For example, INFO, SQL, BASE, Oracle, and Access databases use slightly
different query syntax. The expression that appears between the quotes gets passed on to the
database being queried.
SQL for Access (personal geodatabase)
Here 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 like ’%p%‘ or STATE_NAME like ’%P%‘ "
SQL for Coverages
The same query above on an 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
Dim pFCursor
pFCursor As
As IFeatureCursor
IFeatureCursor
Set
Set pFCursor
pFCursor == pFClass.Search(pQFilter,
pFClass.Search(pQFilter, True)
True)
'What
'What do
do you
you think
think this
this code
code does?
does?
Set
Set pFCursor
pFCursor == pFClass.Search(Nothing,
pFClass.Search(Nothing, True)
True)
QueryFilter
FeatureClass
Search FeatureCursor
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 11-8
Nothing
Remember that the Visual Basic keyword Nothing can sometimes be used to satisfy 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 FeatureClass and place them in the returned Cursor
object. Specifying Nothing is essentially 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 specifies whether
memory will be recycled for records retrieved from the Cursor. Recycling memory means that
each record pulled from the Cursor will occupy the same location in memory and results in
better performance. If memory is not recycled, each record pulled from the Cursor will occupy
its own location in memory. For Cursor used for editing or data loading (Update or Insert
Cursors), memory should not be recycled. Cursors used for read-only operations such as
display or simple 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 allocated.
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
Dim pSFilter
pSFilter As
As ISpatialFilter
ISpatialFilter
Set
Set pSFilter
pSFilter == New
New SpatialFilter
SpatialFilter
Set
Set pSFilter.Geometry
pSFilter.Geometry == pBufferPolygon
pBufferPolygon
pSFilter.SpatialRel
pSFilter.SpatialRel == esriSpatialRelContains
esriSpatialRelContains
Set
Set pFCursor
pFCursor == pCityFClass.Search
pCityFClass.Search (pSFilter,
(pSFilter, True)
True)
Geometry
Geometry Property
Property
•• Point
Point
•• Line
Line
•• Polygon
Polygon
SpatialRel
SpatialRel Property
Property
•• Inside
Inside
•• Contains
Contains
•• Intersects
Intersects
•• Etc
Etc …
…
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 11-10
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 within (esriSpatialRelWithin)
the specified piece of geometry (pBufferPolygon). These 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 the 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, each feature in the Cursor will occupy the same location in memory (memory will be
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 Dim
Dim myCursor
myCursor As
As IFeatureCursor
IFeatureCursor
Search method Set
Set myCursor
myCursor == pFClass.Search(pQFilter,
pFClass.Search(pQFilter, True)
True)
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 from a Table or FeatureClass. The
type of cursor returned depends solely on the method 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 suited 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 return
an error.
Search cursor
Search cursors have already been described. These cursors 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. Search 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),
obtaining a count (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 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 create 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 access 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 database from which the cursor was
created (Table or FeatureClass). Like Search cursors, Update cursors are created with a
QueryFilter object, giving you the ability 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 not 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) using the Insert method on a Table or a
FeatureClass. Use an Insert cursor to insert new records into the database from which the
cursor was created (Rows 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 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 return records (Row/Feature)
myCursor
myCursor initializes
initializes here
here
Nothing
Nothing is
is returned
returned when
when all
all records
records have
have been
been accessed
accessed
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 pointer is
established above the first record. To pull a record out of the cursor, use the NextRow method
(or NextFeature for a FeatureCursor). This method will move 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 moves down one record in the cursor and returns the Row or
Feature it finds.
When the 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 Nothing 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 cursor object itself. There is also no way to jump to a certain record (e.g.,
using 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 return the pointer to its
original position (above the first record) the cursor must 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::FeatureCount to count features
Dim pFeature As IFeature
Dim intLength As Long
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 11-15
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
'Zoom to
to Qatar
Qatar ……
pQFilter.WhereClause
pQFilter.WhereClause == "Name
"Name == ‘Qatar’"
‘Qatar’"
Set
Set pFCursor
pFCursor == pFClass.Search
pFClass.Search (pQFilter,
(pQFilter, True)
True)
Set
Set pFeature
pFeature == pFCursor.NextFeature
pFCursor.NextFeature
If
If Not
Not pFeature
pFeature Is
Is Nothing
Nothing Then
Then
Dim
Dim pEnv
pEnv As
As IEnvelope
IEnvelope
Set
Set pEnv
pEnv == pFeature.Shape.Envelope
pFeature.Shape.Envelope
pMxDoc.ActiveView.Extent
pMxDoc.ActiveView.Extent == pEnv
pEnv
End
End If
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 Envelope property returns the
minimum bounding rectangle for a shape (Envelope is a property 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
End Sub
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
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 11-18
The example
In the example above, a variable is declared as IFeatureLayerDefinition (pFDefine). This
variable is set to the selected layer in the current document 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 DefinitionExpression property on IFeatureLayerDefinition is set to
display only those features 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 the 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
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 selections and
producing subsets of data based on attribute criteria, spatial criteria, 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 attribute 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 and world country layer according to a population
threshold.
• Calculate some simple statistics for a subset of world countries.
• Select cities based on a spatial 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 cursor 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
Symbolizing elements
Introduction to Programming ArcObjects with VBA
and layers
Lesson overview 12-2
Subclasses of Symbol
Using color
ColorRamps
contents
12-3
12-4
12-5
Creating simple graphic elements 12-6
Example: Make a new element,
set its symbol 12-7
Defining an element’s position 12-8
Adding an element to the map
(or layout) 12-9
FeatureRenderers 12-11
SimpleRenderer 12-12
UniqueValueRenderer 12-13
ClassBreaksRenderer 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 overview 12-19
Symbolizing elements
and layers
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA
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 control how elements
(“graphics”) and layers are displayed on the map.
• Symbol—There are several creatable subtypes of Symbol, including text symbols, line
symbols, and fill symbols, for example.
• Color—The (abstract) Color class has five creatable 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 data 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 programmatically 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 from disk.
* Several additional types of symbols are listed on the Display OMD, including TextSymbols
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects 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 FillSymbols to display geometry, and
TextSymbols to display text elements. There are also 3DChartSymbols for drawing charts
(graphs).
The ISymbol interface (supported by each subtype of Symbol) has methods for drawing a symbol
directly to a device context (DC). A device context is basically a window display, such as the
ArcMap display, an ArcCatalog preview pane, or a (standalone Visual Basic) user form.
Each symbol subclass has methods and properties a programmer can use to define 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 CharacterMaker to define a marker from a specific font and
character, for example.
RgbColor
CmykColor
RgbColor HlsColor
HsvColor
GrayColor
GrayColor
Properties for defining color
Red, Green, Blue values (0–255)
Grayscale (0=white – 255=black)
Cyan, Magenta, Yellow, Black
AlgorithmicColorRamp
PresetColorRamp
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 create them
with the New keyword. After instantiating a ColorRamp object, the number of colors are
specified by setting the Size property; the ramp is then created 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.
Map frames
North arrows, legends, scale bars
Table frames
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 change unless the user does so
explicitly. Graphic elements are things like simple shapes (markers, lines, polygons), text strings,
or images (such as a company logo).
FrameElements, on the other hand, are elements that contain objects, such as tables, maps, or
map surrounds. Map surrounds are map-related elements added to the PageLayout that will
dynamically change to reflect changes in an associated 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 this section, you will learn the basics of working with graphic elements. In a later section, you
will learn more about adding frame elements to the page layout.
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 12-7
At this point, the graphic element is completely defined, but does not yet appear on the display.
Dim
Dim pElem
pElem As
As IElement
IElement
Set
Set pElem
pElem == pMarkerElem
pMarkerElem 'QI
'QI
Dim
Dim pPoint
pPoint As
As IPoint
IPoint
Set
Set pPoint
pPoint == New
New Point
Point
pPoint.PutCoords
pPoint.PutCoords -63.91,
-63.91, -8.77
-8.77
pElem.Geometry
pElem.Geometry == pPoint
pPoint
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 12-8
Dim
Dim pMxDoc
pMxDoc As
As IMxDocument
IMxDocument
Set
Set pMxDoc
pMxDoc == ThisDocument
ThisDocument
pMxDoc.ActiveView.GraphicsContainer.AddElement
pMxDoc.ActiveView.GraphicsContainer.AddElement pElem,
pElem, 00
'--OR—
'--OR—
Dim
Dim pGContainer
pGContainer As
As IGraphicsContainer
IGraphicsContainer
Set
Set pGContainer
pGContainer == pMxDoc.FocusMap
pMxDoc.FocusMap
pGContainer.AddElement
pGContainer.AddElement pElem,
pElem, 00
pMxDoc.ActiveView.Refresh
pMxDoc.ActiveView.Refresh
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 12-9
MsgBox "There are " & intGraphicCount & " graphics on the page"
Exit Sub
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 returned through the
Renderer property, which is defined on the IGeoFeatureLayer interface. The Renderer property
is a property put by reference, so you must use the Set 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 with the New keyword. In this lesson, you will be introduced to the common renderers
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 different symbol to each unique value found in a given
attribute field. A land cover map, for example, could be displayed with a
UniqueValueRenderer to show a handful of unique land cover types that may exist for
several thousand polygons.
• ClassBreaksRenderer
Uses a classification based on one of the layer’s numeric attributes to display statistically
(or manually) defined groups of features. The class boundaries may be set explicitly or by
using one of the ArcMap Classify objects (NaturalBreaks, DefinedInterval, Quantile,
EqualInterval, or StandardDeviation).
• 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 more general symbology when he or she zooms out, for example.
USA
Properties
Symbol: Color and Style
Label: A string to appear in the legend
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 number 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
Properties
Breaks: Cut-off points between classes
Field: Attribute on which classes are derived
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 ArcObjects with VBA 12-14
1:75,000,000
1:7,000,000
Properties
Breaks: Cut-off points (scale ranges)
Renderers: Renderers in the ScaleDependentRenderer
RendererCount: Number of renderers contained
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 12-15
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 part 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., shapefile) 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 having 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 consistent (standard) symbology.
GxCatalog
GxLayer
IGxLayer : IUnknown
IGxLayer
Layer: ILayer
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 12-17
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 12-18
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 12-19
elements
Lesson overview 13-2
Object Model overview
Review: Elements
FrameElements
contents
13-3
13-4
13-5
Example: Reference MapFrames
on the layout 13-6
Review: Subclasses of Symbol 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
Getting the item 13-12
Basic steps: Adding a map
surround 13-13
StyleSelector 13-14
Printing a layout 13-15
Exporting a layout 13-16
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 review
Symbols
Colors
Elements
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 13-2
Lesson overview
• Object model overview
• Working with layout frame elements
• Finding existing elements, creating new ones
• Review: Symbols, Colors, Elements
• Referencing elements in the ArcMap style gallery
• Outputting a layout to a printer or file
Introduction to Programming ArcObjects with VBA Working with layout elements 13-2
Object Model overview
MxDocument
ArcMap
ArcMapOMD
OMD
*
GraphicElement FrameElement Map
TextElement MapFrame *
MapSurround
LineElement MapSurroundFrame
ScaleBar
MarkerElement 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 composed of
(potentially) several Element objects. Element is an abstract class that has several sub-types.
On the IElement interface (implemented by every subclass 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 defined in map units or page units, whichever is appropriate.
Introduction to Programming ArcObjects with VBA Working with layout elements 13-3
Review: Elements
Several creatable classes
Graphic elements IElement Element Geometry
On the PageLayout
BmpPictureElement MarkerElement
Map frames
North arrows, legends, scale bars
Table frames
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 13-4
MsgBox "The layout has " & intMapFrames & " map frames, " & _
intMSFrames & " map surround frames, " & _
intTextElements & " text elements, and " & _
intOtherElements & " miscellaneous element types."
End Sub
Introduction to Programming ArcObjects with VBA Working with layout elements 13-4
FrameElements
Added to the PageLayout MapSurroundFrame
MapSurroundFrame
MapSurroundFrame elements
Container for MapSurrounds (e.g., Scalebars)
Contents are dynamically updated
MapSurround
MapSurround
IElement Element PageLayout
*
*
TextElement MapFrame MapSurround
MapSurroundFrame ScaleBar
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 13-5
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 IGraphicsContainer
Set pGC = pMxDoc.PageLayout
pGC.Reset 'Like an enum, Reset moves above the 1st item
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 13-6
Introduction to Programming ArcObjects with VBA Working with layout elements 13-6
Review: Subclasses of Symbol
ISymbol Symbol *
* Several additional types of symbols are listed on the Display OMD, including TextSymbols
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects 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 FillSymbols to display geometry, and
TextSymbols to display text elements. There are also 3DChartSymbols for drawing charts (graphs).
The ISymbol interface (supported by each subtype of Symbol) has methods for drawing a symbol
directly to a device 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 symbol subclass has methods and properties a programmer can use to define 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 CharacterMaker to define a marker from a specific font and character, for
example.
Introduction to Programming ArcObjects with VBA Working with layout elements 13-7
Review: Color classes
Five creatable subclasses IColor Color
RgbColor
CmykColor
RgbColor Hls Color
HsvColor
CmykColor Hs vColor
HlsColor
GrayColor GrayColor
ColorSelector object
Allow the user to choose a color
Same dialog available from the user interface
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 13-8
If Not bMadeChoice Then Exit Function '*If user hit "Cancel", exit
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 classes and style items
MxDocument StyleGallery * StyleGalleryClas s
EnumStyleGalleryItem ColorStyleGalleryClas s
'Get
'Get the
the style
style gallery
gallery
Set
Set pMxDoc
pMxDoc == ThisDocument
ThisDocument
Dim
Dim pGallery
pGallery As
As IStyleGallery
IStyleGallery FillSymbolStyleGalleryClas s
Set
Set pGallery
pGallery == pMxDoc.StyleGallery
pMxDoc.StyleGallery
'—OR
'—OR --
-- make
make aa new
new style
style gallery
gallery
Set
Set pGallery
pGallery == New
New StyleGallery
StyleGallery NorthArrowStyleGalleryClas s
StyleGalleryItem
TextSymbolStyleGalleryClas s
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 13-9
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
'Get the
the North
North Arrows
Arrows in
in the
the ESRI.style
ESRI.style style
style set
set
Dim pEnumNorth
Dim pEnumNorth As IEnumStyleGalleryItem
As IEnumStyleGalleryItem
Set
Set pEnumNorth
pEnumNorth == pGallery.Items
pGallery.Items __
("North
("North Arrows",
Arrows", "ESRI.style",
"ESRI.style", "Default")
"Default")
StyleSet Name
Style Category Name
Style Class Name
'Get
'Get ALL
ALL north
north arrows
arrows (from
(from all
all loaded
loaded styles)
styles) ……
Set pEnumNorth
Set pEnumNorth == pGallery.Items
pGallery.Items ("North
("North Arrows",
Arrows", "",
"", ""
"" ))
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 13-10
Accessing StyleGalleryItems
When accessing a particular StyleGalleryItem, the first step (after getting the StyleGallery
object) is to retrieve an enum of all items of a particular StyleGalleryClass. Use the Items
property (read-only) on IStyleGallery 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 particular 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 styles 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 all 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
Dim intIndex As Integer
For intIndex = 0 To 7
Set pNorthItem = pEnumNorth.Next
Next intIndex
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 13-11
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 item
Color, North Arrow, Fill Symbol, Color Ramp, etc.
'Get
'Get the
the item
item (North
(North Arrow)
Arrow)
Dim
Dim pArrow As INorthArrow 'This
pArrow As INorthArrow 'This is
is aa MapSurround
MapSurround
Set
Set pArrow
pArrow == pNorthItem.Item
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 reference a StyleGalleryItem from the StyleGallery, what you have is not the
actual item (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.
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. Create a MapSurround (or get it from the StyleGallery)
2. Associate the MapSurround with a Map
3. Create a MapSurroundFrame
4. Add the MapSurround to the MapSurroundFrame
5. Add the MapSurroundFrame to the layout (IGraphicsContainer)
'Code
'Code on
on previous
previous slide
slide created
created pArrow
pArrow —1-
—1-
Set MapSurround
MapSurround
Set pArrow.Map
pArrow.Map == pMxDoc.FocusMap
pMxDoc.FocusMap '—2-
'—2-
'Put
'Put the
the surround
surround (North
(North Arrow)
Arrow) in
in aa frame
frame
Dim
Dim pMSFrame
pMSFrame As
As IMapSurroundFrame
IMapSurroundFrame
Set
Set pMSFrame
pMSFrame == New
New MapSurroundFrame
MapSurroundFrame '—3-
'—3-
Set
Set pMSFrame.MapSurround == pArrow
pMSFrame.MapSurround pArrow '—4-
'—4-
pGContainer.AddElement
pGContainer.AddElement pMSFrame,
pMSFrame, 00 '—5-
'—5-
MapSurroundFrame
MapSurroundFrame
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 13-13
I was framed
MapSurrounds are not added directly to a page layout, instead they are added to a special type
of frame element, called a MapSurroundFrame. As the name indicates, a MapSurroundFrame
is simply a container for MapSurrounds. 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 Geometry 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
'Let the
the user
user choose
choose aa north
north arrow
arrow
Dim pNorthSel
Dim pNorthSel As IStyleSelector
As IStyleSelector
Set BackgroundSelector
Set pNorthSel
pNorthSel == New
New NorthArrowSelector
NorthArrowSelector
Dim
Dim bMadeChoice
bMadeChoice As
As Boolean
Boolean
bMadeChoice
bMadeChoice == pNorthSel.DoModal
pNorthSel.DoModal __ LegendItemSelector
(Application.hWnd)
(Application.hWnd)
'Was
'Was aa choice
choice made?
made?
If
If Not
Not bMadeChoice
bMadeChoice Then
Then Exit
Exit Sub
Sub NorthArrowSelector
'Get
'Get the
the user’s
user’s selection
selection
Dim
Dim pNArrow
pNArrow As
As INorthArrow
INorthArrow ScalebarSelector
Set
Set pNArrow
pNArrow == pNorthSel.GetStyle(0)
pNorthSel.GetStyle(0)
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 displayed 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: text symbol (for layout text elements, etc.)
• LegendItemSelector: legend item format
• MapGridSelector: gradicule, grid, or index for map frame
• NorthArrowSelector: north arrows
• ScalebarSelector: scalebars
• ScaleTextSelector: text symbol for representative scale
• ShadowSelector: shadow symbol for map frame (fill)
After displaying a style selector dialog, use the GetStyle method (on IStyleSelector) to
reference the selected style. This method returns a pointer to IUnknown because this interface
is the “lowest common denominator” for all the items listed above.
Introduction to Programming ArcObjects with VBA Working with layout elements 13-14
Printing a layout
Variety of subclasses IPrinter Printer
EmfPrinter (enhanced meta-file)
PsPrinter (postscript)
EmfPrinter Ps Printer
ArcPressPrinter
ArcPres s Printer
Paper class
Manages printer page settings
Application Paper
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 13-15
Introduction to Programming ArcObjects with VBA Working with layout elements 13-15
Exporting a layout
Variety of export formats IExporter Exporter
ArcPress
IExporter::StartExporting
Export the FocusMap or the PageLayout
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 13-16
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 13-17
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
Using tools
Introduction to Programming ArcObjects with VBA
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA
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 controls differ from
buttons in that they allow for user interaction with the display and therefore have many more
events that can be coded, such as MouseUp, MouseDown, MouseMove, and so on.
Mouse clicks from a tool are returned in display coordinates (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 illustrated in this lesson
including panning and zooming, drawing, and providing a user with display feedback.
CursorID
ToolTip
Message
Copyright © 2001–2004 ESRI. All rights reserved. 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 for 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 executes when
a key is pressed and when it is released. You can also write logic based on which key is
pressed.
In addition to the events related to mouse and keyboard input, tools also provide some of the
same button events that control appearance, such as Enabled, ToolTip, and Message. The
CursorID event can be used to provide a different mouse cursor when your tool is active. Use
one of the built-in CursorIDs shown above, or use your own cursor using one of the methods
illustrated below. Tools are in design mode while the Visual Basic Editor window is open.
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_CursorID() As Variant
Set UIToolControl1_CursorID = UserForm1.Image1.Picture
End Function
Private
Private Sub
Sub UIToolControl1_MouseDown(ByVal
UIToolControl1_MouseDown(ByVal button
button As
As Long,
Long, __
ByVal
ByVal shift
shift As Long, ByVal x As Long, ByVal y As Long)
As Long, ByVal x As Long, ByVal y As Long)
MsgBox
MsgBox "X
"X == "" && xx
MsgBox
MsgBox "Y
"Y == "" && yy
End
End Sub
Sub
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 14-4
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 creating geometry in map
coordinates from pixel locations. Use the DisplayTransformation property on the IDisplay
interface to access these methods. When converting coordinates from the display, the output
map point will be in the current spatial reference defined for your map.
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 14-6
DisplayTransformation
The DisplayTransformation object, which can be accessed from the AppDisplay object, allows
the conversion between display and map coordinates.
The example above is typical for tool mouse event procedures that require map coordinates.
After using QueryInterface to access the IMxApplication interface on the ArcMap Application
object, code is chained together to first access the AppDisplay (IMxApplication :: Display),
then the DisplayTransformation (IDisplay :: DisplayTransformation). The ToMapPoint method
is called on the IDisplayTransformation interface, and the required x and y pixel coordinate
arguments are passed in. A Point object is returned as a result of calling the method (IPoint).
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 14-7
Display Feedback
The DisplayFeedback objects are used to give users an interactive representation 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 Developer Help for more information on Display Feedback.
MxDo c ume nt
Manage elements
AddElement, AddElements,
DeleteElement, DeleteAllElements
Pag e Layo ut
IGraphicsContainer
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 14-8
IGraphicsContainer interface
The IGraphicsContainer interface has methods for working with elements in ArcMap. This is
where you will find familiar graphic management methods such as SendToBack,
BringToFront, AddElement, DeleteElement, and so on. Remember that elements can be simple
graphic elements such as text, shapes, or pictures, and can also be frame elements that contain
legends, scalebars, or entire maps.
IGraphicsContainer is supported by both the PageLayout and the Map 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 adding an element to the map.
DIM pGContainer As IGraphicsContainer
Set pGContainer = pMxDoc.FocusMap
pGContainer.AddElement pCompanyLogo
The GraphicsContainer can also be accessed as a property on the IActiveView interface, which
is also supported by both the Map and the PageLayout class. Use this property to work with
elements in whichever view your user has active. The code below shows an example of adding
an element to the Map or the PageLayout, depending on which is currently being viewed.
pMxDoc.ActiveView.GraphicsContainer.AddElement pNewText
'Add
'Add an
an element
element to
to the
the Layout
Layout
Set
Set pMxDoc
pMxDoc == ThisDocument
ThisDocument
Dim
Dim pGC
pGC As
As IGraphicsContainer
IGraphicsContainer
Set
Set pGC
pGC == pMxDoc.PageLayout
pMxDoc.PageLayout
pGC.AddElement
pGC.AddElement pElemArea,
pElemArea, 00
pMxDoc.ActiveView.Refresh
pMxDoc.ActiveView.Refresh
'Send
'Send selected
selected graphics
graphics to
to the
the back
back on
on Layout
Layout
Dim
Dim pGCSelect
pGCSelect As
As IGraphicsContainerSelect
IGraphicsContainerSelect
Set
Set pGCSelect
pGCSelect == pGC
pGC ‘QI
‘QI
pGC.SendToBack pGCSelect.SelectedElements
pGC.SendToBack pGCSelect.SelectedElements
pMxDoc.ActiveView.Refresh
pMxDoc.ActiveView.Refresh
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 14-9
IScreenDisplay::Invalidate
Redraws a specified rectangle (envelope)
IMxDocument::UpdateContents
Notifies the document that its contents have changed
Refreshes the Table of Contents
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 refresh (redraw) the contents of
the display or the document. In ArcObjects, you will find a variety of ways to refresh; choose
the method that is most appropriate for the situation.
• IActiveView :: Refresh—call to redraw the entire display area while in data (Map) or
layout (PageLayout) view
• IScreenDisplay :: Invalidate—call to redraw all layers and elements within a specified
area (defined by passing in an Envelope object)
• IMxDocument :: UpdateContents—call to redraw the legends in the ArcMap Table of
Contents
IActiveView::PartialRefresh
Use in Layout or Data view
Specify what needs to be refreshed (e.g., graphics)
Specify 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 therefore be called on a Map
or a PageLayout object. PartialRefresh is very similar to IScreenDisplay::Invalidate in that it
can be used to redraw only a specified area (envelope) of the display. PartialRefresh gives you
more control, however, as it allows you to also specify what you want refreshed (geography,
graphics, selection, etc.).
Using PartialRefresh is more efficient than redrawing everything on the entire display,
especially for maps that contain a lot of data and graphics.
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 14-12
15-4
Creating a DatasetName 15-5
Data manipulation objects 15-6
Converting feature classes 15-7
Exercise 15A overview 15-8
Editing with a cursor 15-9
Editing cursors 15-10
Example: Updating misspelled
attributes 15-12
Adding a field 15-13
Creating a domain 15-14
Adding a domain to a database 15-15
Assigning a domain to a field 15-16
Exercise 15B overview 15-17
Data management
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA
Insert
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 ArcObjects. In this lesson, you will
learn …
• How to use Name objects
WorkspaceNames
DatasetNames
• How to convert feature classes and tables
FeatureDataConverter
ObjectLoader
• How to edit using a cursor
Update
Insert
• How to add fields and domains
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 object. By working with Name
objects, you have access to some of the basic properties 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 by 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 card can obtain basic information about you, such as your e-mail address and
phone number. If that person needs you, he or she can e-mail or call you to obtain the actual
object represented by your card (you).
If your application needs to search the contents of an entire workspace to find a particular
dataset, for example, it is much more efficient to search the dataset Names. Once the desired
dataset 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 as
opposed to the full object. You can use Name objects for things such as Tables, FeatureClasses,
and Workspaces.
Name
Not
Not all
all Name
Name subtypes
subtypes
are
are shown
shown here
here
WorkspaceName DatasetName
FeatureDatasetName TableName
TinName
RelationshipClassName
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 objects 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
objects. 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 access 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 opening its dataset
Public Sub OpenCities()
Dim pWSFactory As IWorkspaceFactory
Dim pWS As IWorkspace
Dim pEnumDSNames As IEnumDatasetName
Dim pDSName As IDatasetName
Dim pCities As IFeatureClass
'Identify
'Identify its
its workspace
workspace
Set
Set pFCName.WorkspaceName == pWSName
pFCName.WorkspaceName pWSName
'Identify
'Identify its
its filename
filename
pFCName.Name
pFCName.Name == "States.shp"
"States.shp"
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 15-5
Example
If writing code to create a new table called PoisonFrogs.dbf in the (new) folder
C:\Madagascar\Data, you would write code such as the following:
Dim pShapeWSFactory As IWorkspaceFactory
Dim pWorkName As IWorkspaceName 'Å a Name to represent the workspace
Dim pTableName As IDatasetName 'Å a Name to represent the table
'** The code below returns a WorkspaceName, not a Workspace
Set pShapeWSFactory = New ShapefileWorkspaceFactory
Set pWorkName = pShapeWSFactory.Create ("C:\Madagascar", "Data",_
Nothing, Application.hWnd)
'** co-create a new TableName, set its properties
Set pTableName = New TableName
Set pTableName.WorkspaceName = pWorkName
pTableName.Name = "PoisonFrogs.dbf"
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
Required arguments
Input and output FeatureClassNames
Output FeatureDatasetName
A QueryFilter
Several Others … 'Create
'Create aa new
new FeatureDataConverter
FeatureDataConverter object
object
Dim
Dim pFDConvert
pFDConvert As
As IFeatureDataConverter
IFeatureDataConverter
Set
Set pFDConvert
pFDConvert == New
New FeatureDataConverter
FeatureDataConverter
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 15-7
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 15-8
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 15-9
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 from a Table or FeatureClass. The
type of cursor returned depends solely on the method 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 suited 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 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 records in the database from which the cursor was created
(Table or FeatureClass). Like Search cursors, Update cursors are created with a QueryFilter
object, giving you the ability 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 not 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) using the Insert method on a Table or a
FeatureClass. Use an Insert cursor to insert new records into the database from which the cursor
was created (Rows 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.
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 15-12
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 15-13
Dim
Dim pRDomain
pRDomain As
As IRangeDomain
IRangeDomain
Dim
Dim pDomain
pDomain As
As IDomain
IDomain
Set
Set pRDomain
pRDomain == New
New RangeDomain
RangeDomain 'CoClass
'CoClass
Set
Set pDomain
pDomain == pRDomain
pRDomain 'QueryInterface
'QueryInterface
pRDomain.MinValue
pRDomain.MinValue == 00
pRDomain.MaxValue
pRDomain.MaxValue == 200
200
pDomain.Name
pDomain.Name == "Diameter"
"Diameter"
pDomain.FieldType
pDomain.FieldType == esriFieldTypeInteger
esriFieldTypeInteger
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 15-14
Dim
Dim pAccessFact
pAccessFact As
As IWorkspaceFactory
IWorkspaceFactory
Dim
Dim pGDBWorkspace
pGDBWorkspace As
As IWorkspace
IWorkspace
Set
Set pAccessFact
pAccessFact == New
New AccessWorkspaceFactory
AccessWorkspaceFactory
Set
Set pGDBWorkspace
pGDBWorkspace == pAccessFact.OpenFromFile("C:\City.mdb",
pAccessFact.OpenFromFile("C:\City.mdb", 0)
0)
Dim
Dim pWSDomains
pWSDomains As
As IWorkspaceDomains
IWorkspaceDomains
Set
Set pWSDomains
pWSDomains == pGDBWorkspace
pGDBWorkspace 'QueryInterface
'QueryInterface
pWSDomains.AddDomain
pWSDomains.AddDomain pRDomain
pRDomain 'Add
'Add the
the range
range domain
domain
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 15-15
Dim
Dim pAverageFld
pAverageFld As
As IFieldEdit
IFieldEdit
Set
Set pAverageFld
pAverageFld == New
New Field
Field
With
With pAverageFld
pAverageFld
.Name
.Name == "Average"
"Average"
.Type
.Type == esriFieldTypeInteger
esriFieldTypeInteger
.AliasName
.AliasName == "Average
"Average Income"
Income"
.Length
.Length == 16
16
Set
Set .Domain
.Domain == pRDomain
pRDomain 'Put
'Put by
by Ref
Ref
End
End With
With
pTable.AddField
pTable.AddField pAverageFld
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 reflected 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 after 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 error. Instead, the domain simply would not be enforced.
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 related to data
manipulation.
You will write code to:
• convert data from one format 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
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 adding 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
In the later half, you will learn how to capture and code ArcObjects events. 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 available 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
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, change their properties, and
create your own toolbars, menus, and pop-ups. You can also run existing ArcGIS commands
using a single line of code.
Examples of when you might want to modify the interface with code:
• Automatically add a control for calculating property values when a parcel layer is added to
the map.
• Show a custom pop-up menu that lists the attributes for the feature that was clicked on. If a
feature was not clicked, show the default ArcMap pop-up.
• Enable a set of editing tools only if the user provides the proper password.
• Add and remove custom layout-related commands when the user switches between data
and layout 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
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 (toolbars, menus, and pop-
ups) 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 (CommandItem) 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 Shortcut
Shortcut menu
menu
Menus
Menus
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 (*) CommandBar objects. New
command bars can be created from the CommandBars object. There are three different types of
CommanBars available on the ArcMap or ArcCatalog user interface:
• Toolbars—a collection of/container for commands, such as buttons, tools, combo boxes,
and so on. Toolbars can also contain menus, which are another type of CommandBar.
• Menus—a collection of/container for commands. Menus cannot contain tools (which
require mouse input), edit boxes, or combo boxes. Unlike toolbars and pop-up menus
(context or shortcut menus), menus must be contained by a toolbar or by another menu
(e.g., as a sub-menu).
• Pop-up menus—identical 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
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. CommandItems are things such as
buttons, tools, combo boxes, and edit boxes that appear 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 lets you get or set the properties such as Caption, Image,
Message, ToolTip, Display Style, and Help Context ID. This interface also provides methods to
execute, delete, refresh, or reset a particular CommandItem. Use either ICommandBars::Find
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.Find _
(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)
available in the current document. The Find method locates a CommandItem using a UID
(Unique Identifier), which is a long alphanumeric string stored in your operating system’s
registry. Here is the UID for the New Map command: {119591DB-0255-11D2-8D20-
080009EE4E51}. Once a CommandItem is located using Find, its code can be executed by
calling the Execute method (on the ICommandItem interface).
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 relative to another bar
Dim
Dim pTools
As
As ICommandItem
pTools
ICommandItem
Set
Set pTools
== ThisDocument.CommandBars.Find
ThisDocument.CommandBars.Find __
pTools
(ArcID.Tools_Toolbar)
(ArcID.Tools_Toolbar)
Dim
Dim pToolBar
pToolBar As
As ICommandBar
ICommandBar
Set
Set pToolBar
pToolBar == pTools
pTools 'QI
'QI
pToolBar.Dock esriDockHide
pToolBar.Dock esriDockHide
'Others:
'Others: esriDockShow,
esriDockShow, esriDockToggle,
esriDockToggle, esriDockFloat
esriDockFloat
'ReferenceBar
'ReferenceBar locations: Left,
locations: Left, Right,
Right, Top,
Top, Bottom
Bottom
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 16-8
Finding a CommandBar
Because the CommandBar class implements the ICommandItem interface, 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.
Example: open the Tools toolbar, dock it next to the Editor toolbar
Public Sub DockToolsToolbar ()
Dim pToolsBar As ICommandBar
Dim pEditBar As ICommadBar
Set pToolsBar = ThisDocument.CommandBars.Find(ArcID.Tools_Toolbar)
Set pEditBar = _
ThisDocument.CommandBars.Find(ArcID.Editor_EditorToolbar)
pToolsBar.Dock 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 example, perhaps
you want to add or remove controls when your user switches between data 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 provide logic that dictates which context (pop-
up) menu should be displayed.
Introduction to Programming ArcObjects with VBA Application framework and ArcObjects events 16-9
Example: Displaying a different context menu
The
The location
location clicked
clicked (in
(in pixels)
pixels)
Private
Private Function
Function MxDocument_OnContextMenu
MxDocument_OnContextMenu __
(ByVal
(ByVal X As
X As Long,
Long, ByVal
ByVal YY As
As Long)
Long) As
As Boolean
Boolean
Dim pMenu As ICommandBar
Dim pMenu As ICommandBar
Set
Set pMenu
pMenu == ThisDocument
ThisDocument __
CommandBars.Find(ArcID.View_Menu)
CommandBars.Find(ArcID.View_Menu)
If
If (m_pMxDoc.FocusMap.Name
(m_pMxDoc.FocusMap.Name == "Logan")
"Logan") Then Then
pMenu.Popup
pMenu.Popup 'Use Popup to show the
'Use Popup to show the context
context menu
menu
MxDocument_OnContextMenu
MxDocument_OnContextMenu == TrueTrue
Else
Else
MxDocument_OnContextMenu
MxDocument_OnContextMenu == False
False
End
End If
If True == the
True the event
event was
was handled
handled here
here
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 16-10
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 the activated data frame is ‘Logan’; otherwise, the default
pop-up menu will be displayed.
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
Set aNewCBar
aNewCBar == aCommandBars.Create
aCommandBars.Create (aNameString,
(aNameString, aTypeConstant)
aTypeConstant)
Dim
Dim pMnu
pMnu As
As ICommandBar
ICommandBar
Set
Set pMnu
pMnu == ThisDocument
ThisDocument __
CommandBars.Create("New",esriCmdBarTypeShortcutMenu)
CommandBars.Create("New",esriCmdBarTypeShortcutMenu)
pMnu.Add
pMnu.Add ArcID.File_AddData
ArcID.File_AddData 'Add
'Add the
the ArcMap
ArcMap "Add
"Add Data"
Data" command
command
pMnu.Popup
pMnu.Popup 'Display
'Display the
the new
new context
context menu
menu
MxDocument_OnContextMenu
MxDocument_OnContextMenu == True
True 'Tell
'Tell ArcMap
ArcMap not
not to
to popup
popup aa
menu
menu
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 16-11
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
Dim pSubMenu
pSubMenu As
As ICommandBar
ICommandBar
Set
Set pSubMenu
pSubMenu == pMnu.CreateMenu("Sub")
pMnu.CreateMenu("Sub")
pSubMenu.Add
pSubMenu.Add ArcID.Help_About
ArcID.Help_About
pMnu.Popup
pMnu.Popup 'Display
'Display the
the new
new context
context menu
menu
MxDocument_OnContextMenu
MxDocument_OnContextMenu == True
True 'Tell
'Tell ArcMap
ArcMap not
not to
to popup
popup aa
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 create 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. For this reason, you
should always call the CreateMenu method on a particular CommandBar 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 specified to define the position of the new menu, it was placed
at the bottom of the shortcut menu. The About ArcMap command was added to the sub-menu
by referencing its 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
aMenu.CreateMacroItem aNameString,
aNameString, anIconID,
anIconID, aMacroNameString
aMacroNameString
'Add
'Add aa macro
macro to
to the
the context
context menu
menu
pMnu.CreateMacroItem
pMnu.CreateMacroItem "myMacro",
"myMacro", 0,
0, "Normal.ThisDocument.Calc"
"Normal.ThisDocument.Calc"
pMnu.Popup
pMnu.Popup 'Display
'Display the
the new
new context
context menu
menu
MxDocument_OnContextMenu
MxDocument_OnContextMenu == True
True 'Tell
'Tell ArcMap
ArcMap not
not to
to popup
popup aa
menu
menu
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 16-13
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
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 16-14
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 adding 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 Diagrams and how to capture
their occurrence.
Topics for this lesson are:
• Outbound versus inbound interfaces
• Finding outbound interfaces and events on the diagrams 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 common kind and
the one you have worked with almost exclusively in this course. On an inbound interface, client
code makes calls to functions within the interface contained on an object. An outbound interface
is one where the object makes calls to client code—a technique analogous to the traditional
callback mechanism.
Outbound interfaces do not contain methods and properties, only events. Events are 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
Someevents
events
have
have parameters
parameters
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 16-17
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
Private WithEvents
WithEvents m_pMapEvents
m_pMapEvents As
As Map
Map
Private
Private WithEvents
WithEvents m_pAVEvents
m_pAVEvents As
As MapEvents
MapEvents
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA -
16-18
Introduction to Programming ArcObjects with VBA Application framework and ArcObjects events 16-18
Events supported by Map
ActiveViewEvents (default)
AfterDraw Private
Private WithEvents
WithEvents m_pMap
m_pMap As
As Map
Map
ContentsChanged
FocusMapChanged
SelectionChanged
SpatialReferenceChanged
MapEvents Private
Private WithEvents
WithEvents m_pAVEvents
m_pAVEvents As
As
MapEvents
MapEvents
FeatureClassChanged
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 16-19
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
Private WithEvents
WithEvents m_pAVEvents
m_pAVEvents As
As Map
Map
Private
Private Function
Function MxDocument_OpenDocument()
MxDocument_OpenDocument() As
As Boolean
Boolean
Dim
Dim pMxDoc
pMxDoc As
As IMxDocument
IMxDocument
Set
Set pMxDoc
pMxDoc == ThisDocument
ThisDocument
Set
Set m_pAVEvents
m_pAVEvents == pMxDoc.FocusMap
pMxDoc.FocusMap 'Can
'Can now
now access
access events
events
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 using the WithEvents
keyword. The next step is to initialize the variable as a specific object whose events you want to
provide code for. The tricky part can be determining when to initialize the variable. For many
applications, you will want to have access to object events as soon as the project is opened. In this
case, you would initialize your outbound interface variables in the MxDocument_OpenDocument
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 focused 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, code 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)
Object
Object Procedure
Procedure
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 16-21
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
Introduction to Programming ArcObjects with VBA Application framework and ArcObjects events 16-22
Introduction to Programming ArcObjects with VBA
ArcObjects beyond
ModuleTitle
VBA
Lesson overview 17-2 Resources for creating custom
Visual Basic versus VBA
Remember COM?
Basic steps: Building a COM
17-3
17-4
components
Exercise 17 (Optional): Building
a COM command
contents
17-17
17-18
component 17-5 Lesson overview 17-19
1) Create a new COM project 17-6 ArcGIS Engine 17-20
2) Create a COM class 17-7 ArcGIS Engine Developer Kit 17-21
3) Reference the appropriate Engine Runtime 17-22
libraries 17-8 Why ArcGIS Engine Developer
4) Implement the required Kit? 17-23
interface(s) 17-9 ArcGIS Engine Developer
Referencing the Application 17-11 Kit resources 17-24
Example: Branching in a COM Lesson overview 17-25
component 17-12 ArcGIS Server 17-26
5) Compile your component DLL 17-13 Why ArcGIS Server? 17-27
6) Registering your COM ArcGIS Server resources 17-28
component 17-14
Where can COM components
plug in? 17-15
ArcObjects beyond
VBA
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA
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 produce COM components
that work in ArcMap or ArcCatalog. It will provide the basic steps required to create a COM
DLL, as well as a survey of some of the places where your component can plug in to the
existing application’s architecture.
Import VB Forms __ No
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 17-3
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 language in itself,
but is rather a standard for how classes should be written. The primary advantage of COM is
the ability to create your own components that can easily plug into and work inside an existing
architecture. To make this work without COM, you would have to modify and recompile the
original source code for ArcMap or ArcCatalog every time you wanted to add a component.
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 programming 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
standalone 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 programming
environment.
2. Create a COM class- you will create a creatable COM class. This class will allow you to
create objects from it and embed them into ArcMap or ArcCatalog.
3. Reference the ArcObject libraries—unlike programming in ArcMap or ArcCatalog, Visual
Basic will not automatically know about the ArcObjects.
4. Implement the required interface(s)—as described earlier, to ensure that your 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 component categories, which help organize your components. The type of component
you create will determine which category you need to register your component in.
Lastly, you will simply want to test, debug and recompile the component. Test the component
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.
ActiveX
ActiveX DLL
DLL
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 17-6
Each MultiUse
MultiUseInstancing
Instancing
Eachclass
classmodule
module will
will (Creatable)
become
becomeaacomponent
component (Creatable)
(e.g.,
(e.g.,Control)
Control)
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 interface of a new
COM class is to set its name and Instancing property. The name controls the name assigned to
the object and the name of the default interface. The Instancing property controls the scope of
the class and determines whether or not other COM objects can create instances of the object.
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 class. 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 Object Browser and code completer do not display default
interfaces. Don’t be fooled when you are writing code to declare variables for IApplication
and IDocument. Although you will not see references to these interfaces in the VB Object
Browser, IApplication and IDocument are default interfaces for ArcObjects.
esriSystemUI.olb
esriSystemUI.olb
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 17-8
Give
Give ArcGIS
ArcGIS what
what itit expects
expects from
from
your
your component
component
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 17-9
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 17-10
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 17-11
Perform
Performdifferent
differenttasks
tasksin
in
ArcMap
ArcMapand
andArcCatalog
ArcCatalog
Use
UseTypeOf
TypeOfto
tosee
seeifif
Control
Controlwas
wasadded
addedto to
ArcMap
ArcMapororArcCatalog
ArcCatalog
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 17-12
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 17-13
• ‘Object module needs to implement <member name> for interface <interface name>’—
you did not at least stub out all of the methods and properties for an interface that you
promised to implement.
• ‘Permission denied: <DLL filename>’—the DLL is likely being used (by ArcMap or
ArcCatalog, for example). This error might be encountered when you are in the
testing/debugging phase of developing your component.
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 17-14
Command
Command
Table
Table of
of Contents
Contents Tab
Tab
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 17-15
ClassExtension
ClassExtension
(Geodatabase)
(Geodatabase) ToolControl
ToolControl
Network
Network Trace
Trace Task
Task
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 17-16
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
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 17-18
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 product at ArcGIS 9. This
product allows you to use ArcObjects to build stand alone custom applications.
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 functions into existing
applications such as Microsoft Word and Excel, as well as build focused custom applications
for delivering a focused GIS task to many users in their organizations without having an
ArcGIS license on the client machine.
The ArcGIS Engine consists of a software development kit and a re-distributable runtime
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 user product, but a toolkit for
application developers. It allows developers to build either simple mapping applications or
comprehensive GIS applications for Windows, UNIX or Linux users.
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 complete
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 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 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 wide 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 allow 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 with object model diagrams
and sample code to help developers get started is also included.
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 17-22
Windows
Example
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects 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 advanced overlay analysis,
people are using this functionality. This does not necessarily mean everyone performing GIS
tasks are GIS experts and need a full fledged 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 edits to their database for where new power lines have been created, making updates 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 use a custom application designed
specifically to perform these tasks.
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 samples that are specific to
building ArcGIS Engine applications.
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. ArcGIS Server
provides a framework for using ArcObjects through an Internet or local area connection
through Web browsers or other client applications for an enterprise GIS.
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 database. Mapping,
geocoding, spatial queries, editing, tracing and linear referencing are all 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 development environments (Java,
.NET, C++, COM) and all major server platforms. The initial release of ArcGIS 9 will support
Microsoft Windows, while other platforms will be supported in subsequent releases.
Geodatabase Editing
Network Tracing
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 17-27
ArcGIS Server allows GIS functionality to take place over the Internet or LAN, without a user
having any GIS installed on their machine. All the end user will need 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 that end users can operate without having much GIS knowledge. ArcGIS
Server also allows users to interact with an enterprise system for everyday editing tasks
without dealing with the administration of the system and data.
http://arcgisdeveloperonline.esri.com
ArcGIS Server Developer Guide
Samples
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 17-28