You are on page 1of 408

Introduction to

Programming
ArcObjects with VBA
(Final)

Jeremiah Lindemann
Lisa Markham
Robert Burke
Janis Davis
Thad Tilton
Copyright © 2001–2004 ESRI
All rights reserved.
Course version 3.2. Revised July 2004.
Printed in the United States of America.

The information contained in this document is the exclusive property of ESRI. 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.

The information contained in this document is subject to change without notice.

U. S. GOVERNMENT RESTRICTED/LIMITED RIGHTS


Any software, documentation, and/or data delivered hereunder is subject to the terms
of the License Agreement. In no event shall the U.S. Government acquire greater
than RESTRICTED/LIMITED RIGHTS. At a minimum, use, duplication, or
disclosure by the U.S. Government is subject to restrictions as set forth in FAR
§52.227-14 Alternates I, II, and III (JUN 1987); FAR §52.227-19 (JUN 1987) and/or
FAR §12.211/12.212 (Commercial Technical Data/Computer Software); and DFARS
§252.227-7015 (NOV 1995) (Technical Data) and/or DFARS §227.7202 (Computer
Software), as applicable. Contractor/Manufacturer is 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

1 Introduction to Programming ArcObjects with VBA


Welcome to Intro to Programming ArcObjects 1-2
Logistics 1-3
Course materials 1-4
Course objectives 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
Exercise 1: Install the class database

2 The VBA development environment


Lesson overview 2-2
The VBA development environment 2-3
ArcGIS commands 2-4
Using the Customize dialog box 2-5
The Customize dialog 2-6
Using the Customize dialog box 2-8
Creating a new command 2-9
Setting control properties 2-10
Accessing your customizations 2-11
Storing your customizations 2-13
Examining a control’s source code 2-14
Demonstration 2-15
Overview 2-16
The Visual Basic Editor 2-17
Understanding ArcMap software’s code storage 2-19
Writing Visual Basic statements 2-20
Some common Visual Basic functions 2-21
Procedure types 2-23
Running an event procedure 2-24

Copyright © 2001–2004 ESRI i


Introduction to Programming ArcObjects with VBA Contents

Navigating event procedures in a module 2-25


The ThisDocument module 2-26
Creating a new module 2-27
Creating a new sub or function procedure (macro) 2-28
Defining procedure scope 2-30
Running a subroutine or function procedure 2-31
Adding a macro to a toolbar 2-32
Getting help 2-33
Exercise 2 overview 2-34
Exercise 2: Explore the Visual Basic Editor

3 Visual Basic code: How, where, and when?


Lesson overview 3-2
Object-oriented programming 3-3
Example: Object-oriented terms 3-4
How: Visual Basic syntax 3-5
Preset ArcObjects variables 3-7
Automatic code completion 3-9
Where: Controls, documents, and forms 3-11
Working with forms 3-13
Setting properties at design time 3-14
Writing code for a form 3-16
Using control properties at run time 3-17
When: Form and control events 3-18
When: Map document events 3-20
Saving your work 3-22
Exercise 3 overview 3-23
Exercise 3: Create a user form

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

ii Copyright © 2001–2004 ESRI


Contents

Controlling If Then 4-15


Decision making: The Select Case statement 4-17
Levels of variable scope 4-19
Procedure-level variables 4-21
Module-level variables 4-22
Public-level variables 4-23
Static variables 4-24
Exercise 4 overview 4-25
Exercise 4A: Work with variable scope
Exercise 4B: Create a guessing game

5 Programming with class


Lesson overview 5-2
Class 5-3
Classes and objects 5-4
Class libraries 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
Exercise 5: Work with your own object

6 COM before the storm


Lesson overview 6-2
Introducing COM 6-3
COM classes have interfaces 6-4
Working with ArcObjects COM classes 6-5
More on interfaces … 6-6
Polymorphism 6-7
ArcObjects polymorphism 6-8
Using methods and properties 6-9

Copyright © 2001–2004 ESRI iii


Introduction to Programming ArcObjects with VBA Contents

Getting other interfaces 6-10


Testing an object reference 6-12
COM class code 6-14
Using library names 6-16
Using the ESRI Object Browser 6-17
Demonstration: Creating a COM class 6-18
Exercise 6 overview 6-19
Exercise 6: Work with COM classes

7 Understanding object model diagrams


Lesson overview 7-2
ArcObject object model diagrams 7-3
Relationship symbols 7-4
ArcMap objects 7-5
Creatable Class (CoClass) 7-6
Instantiable Class (Class) 7-7
Abstract class 7-8
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
Exercise 7A: Navigating the object model diagrams
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
Finding the right OMD: Step 3 7-20
Finding the right OMD: Step 4 7-21
Where to begin? Getting into the OMD 7-22
Example: MxDocument > Map > layer 7-23
Exercise 7B overview 7-24
Exercise 7B: Using the object model diagrams

iv Copyright © 2001–2004 ESRI


Contents

8 Maps and layers


Lesson overview 8-2
Loop review 8-3
Object model overview 8-4
Accessing maps 8-5
Looping through a collection of maps 8-6
Managing flow in a loop 8-7
Accessing layers 8-8
Working with a map’s layers 8-9
Looping through layers 8-10
Working with layer properties 8-11
Adding a new layer to a map 8-12
Setting a FeatureLayer’s data source 8-13
Exercise 8 overview 8-14
Exercise 8: Working with maps and layers

9 Data access and creation


Lesson overview 9-2
Data creation objects 9-3
Opening an existing Workspace 9-5
Connecting to an ArcSDE database 9-7
Getting a FeatureDataset 9-8
Getting FeatureClasses 9-9
Pseudocode: Adding a data layer 9-10
GxDialog 9-11
Example: GxDialog 9-12
Exercise 9A overview 9-13
Exercise 9A: Create a layer from a shapefile
Working with Name objects 9-14
Creating a new Workspace 9-15
Creating a new Table or FeatureClass 9-17
Field and Fields classes 9-18
IField and IFieldEdit 9-19
Creating a Fields collection 9-20
Creating a Table or FeatureClass 9-21
Work with fields in a table 9-23
Adding rows and values to a table 9-24
Exercise 9B overview 9-26
Exercise 9B: Creating data

Copyright © 2001–2004 ESRI v


Introduction to Programming ArcObjects with VBA Contents

10 Geometry and geoprocessing


Lesson overview 10-2
Geometry objects 10-3
Feature geometry 10-4
Points and multipoints 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
Exercise 10: Use coordinate input to draw features

11 Working with subsets and selections


Lesson overview 11-2
Object Model overview 11-3
SelectionSet 11-4
Cursors and FeatureCursors 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
Exercise 11: Working with subsets and selections

vi Copyright © 2001–2004 ESRI


Contents

12 Symbolizing elements and layers


Lesson overview 12-2
Subclasses of Symbol 12-3
Using color 12-4
ColorRamps 12-5
Creating simple graphic elements 12-6
Example: Make a new element, set its 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
Exercise 12: Symbolizing elements and layers

13 Working with layout elements (Optional)


Lesson overview 13-2
Object Model overview 13-3
Review: Elements 13-4
FrameElements 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
Exercise 13 overview 13-17
Exercise 13: Working with layout elements

Copyright © 2001–2004 ESRI vii


Introduction to Programming ArcObjects with VBA Contents

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

16 Application framework and events


Lesson overview 16-2
Customizing the user interface 16-3
CommandBars class 16-4

viii Copyright © 2001–2004 ESRI


Contents

Types of CommandBar objects 16-5


Components of CommandBar: CommandItems 16-6
Finding a CommandItem 16-7
Finding an ArcGIS toolbar or menu 16-8
Document events 16-9
Example: Displaying a different context menu 16-10
Displaying a new shortcut menu 16-11
Creating new menus 16-12
Creating commands to execute macros 16-13
Updating the ArcID module 16-14
Lesson overview 16-15
Inbound and outbound interfaces 16-16
Finding outbound interfaces 16-17
Using an outbound interface 16-18
Events supported by Map 16-19
Capturing object events 16-20
Coding object events 16-21
Exercise 16 overview 16-22
Exercise 16A: Program the user interface
Exercise 16B: Coding ArcObjects events

17 ArcObjects beyond VBA


Lesson overview 17-2
Visual Basic versus VBA 17-3
Remember COM? 17-4
Basic steps: Building a COM component 17-5
1) Create a new COM project 17-6
2) Create a COM class 17-7
3) Reference the appropriate libraries 17-8
4) Implement the required interface(s) 17-9
Referencing the Application 17-11
Example: Branching in a COM component 17-12
5) Compile your component DLL 17-13
6) Registering your COM component 17-14
Where can COM components plug in? 17-15
Resources for creating custom components 17-17
Exercise 17 (Optional): Building a COM command 17-18
Lesson overview 17-19
ArcGIS Engine 17-20

Copyright © 2001–2004 ESRI ix


Introduction to Programming ArcObjects with VBA Contents

ArcGIS Engine Developer Kit 17-21


Engine Runtime 17-22
Why ArcGIS Engine Developer Kit? 17-23
ArcGIS Engine Developer Kit resources 17-24
Lesson overview 17-25
ArcGIS Server 17-26
Why ArcGIS Server? 17-27
ArcGIS Server resources 17-28
Exercise 17: Creating COM classes with Visual Basic (Optional)

x Copyright © 2001–2004 ESRI


Course name goes here

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

Introduction to Programming ArcObjects with VBA Introduction 1-1


Welcome to Intro to Programming ArcObjects
‹ Instructor introduction
‹ Student introductions
‹ Name

‹ Organization

‹ Role in organization
‹ Programming experience
‹ GIS experience
‹ Goals and expectations
for this class

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 1-2

Welcome to Introduction to Programming ArcObjects with VBA.

Prerequisites: Introductions to Visual Basic for ESRI software (Virtual Campus


course)
Introduction to Programming ArcObjects with VBA is a five day course, consisting of
approximately 40 hours of class time. The course uses instructor-led lectures and
demonstrations in conjunction with hands-on programming exercises. You should expect to
spend most of your class time engaged in writing Visual Basic code for the ArcMap and
ArcCatalog applications.

Introduction to Programming ArcObjects with VBA Introduction 1-2


Logistics
‹ Daily schedule
‹ Start _______________
‹ Lunch _______________
‹ Finish _______________
‹ Facilities
‹ Refreshments and break area
‹ Restrooms

‹ Telephones and messages


‹ Internet access
‹ Student ID badges
‹ Parking

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 1-3

Daily schedule
Under normal conditions, the class will begin each day at 8:30 a.m. and continue until 5:00
p.m. There will be at least one break in the morning and one in the afternoon. You will
generally be given one hour for lunch.

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.

Introduction to Programming ArcObjects with VBA Introduction 1-3


Course materials
‹ Books
‹ Lecture
‹ Exercise
‹ CDs ESRI
Training Data

‹ Course data
‹ Samples
‹ Online course evaluation
http://classeval.esri.com
‹ Requires Course Identification Number
‹ Software evaluation
‹ E-mail enhancement requests to product teams
Š desktop_comments@esri.com

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 1-4

Teaching methods
Research indicates that students learn differently. This course maximizes your learning
experience by combining instructor-led lectures and 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.

Introduction to Programming ArcObjects with VBA Introduction 1-4


Course objectives
‹ Reinforce VBA programming techniques
‹ Build VBA Applications with ArcObjects
‹ Understand Object Oriented Programming
‹ Gain familiarity with COM classes
‹ Interpret ArcObject Object Model Diagrams
‹ Gain comfort in programming with some of the commonly used
ArcObjects

‹ Ask questions and participate in discussions

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 1-5

Introduction to Programming ArcObjects with VBA is a five day course that 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.

Introduction to Programming ArcObjects with VBA Introduction 1-5


Course timeline
‹ VBA Skills
Day 1
‹ Working with Classes

‹ COM Classes
Day 2
‹ Reading OMDs

‹ Maps and Layers


Day 3
‹ Selections and Subsets

‹ 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

Day 1 Day 2 Day 3 Day 4 Day 5


Lesson 1: Lesson 6: Lesson 9A: Lesson 12: Lesson 15B:
Introduction Working with Data access Layer Data
Lesson 2: COM and creation Rendering Management
The VBA
Environment

Break Break Break Break Break


Lesson 3: Lesson 7A: Lesson 9B: Lesson 13: Lesson 16A:
Visual Basic Understanding Data access Working with Application
code: How, Object Model and creation Layout Framework
where, when? Diagrams Elements

LUNCH LUNCH LUNCH LUNCH LUNCH


Lesson 4: Lesson 7B: Lesson 10: Lesson 14: Lesson 16B:
Using Understanding Working With Using Tools Events
Variables Object Model Geometry
Diagrams

Break Break Break Break Break


Lesson 5: Lesson 8: Lesson 11: Lesson 15A: Lesson 17:
Programming Maps & Subsets and Data ArcObjects
with Class Layers Selections Management beyond VBA

Introduction to Programming ArcObjects with VBA Introduction 1-6


What is ArcGIS?
E
E ArcGIS Desktop ArcGIS Engine X
T
X E
T ArcInfo
Custom
Custom N
ArcInfo application
S
E application I
ArcGIS clients N O
N
S ArcEditor
ArcEditor S

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.

Introduction to Programming ArcObjects with VBA Introduction 1-7


Software support resources
‹ ESRI Support Center
a gateway to resources
http://support.esri.com
‹ Knowledge Base
‹ Technical articles
‹ White papers
‹ System requirements
‹ Downloads
‹ Patches and service packs
‹ Data models
‹ ArcScripts ‹ For Developers
‹ User Forums ‹ Developer resources
‹ Discussion groups ‹ Request ESRI Technical Support
‹ E-mail lists ‹ Available to support subscribers
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 1-8

ESRI’s primary resource for software support is the ESRI Support Center at
http://support.esri.com.

Knowledge Base
The Knowledge Base is a searchable database 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.

Introduction to Programming ArcObjects with VBA Introduction 1-8


Learning paths
http://www.esri.com/training_events.html

‹ Learning Guide
‹ Learning paths organized
by software and topic

‹ Learning options
‹ Instructor-led courses
‹ Virtual Campus courses
‹ Training seminars
‹ Web workshops

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 1-9

Depending on which ESRI software your organization has licensed, your skills, 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 Programming ArcObjects with VBA Introduction 1-9


Learning paths
Foundation Extensions
ArcSDE
Introduction to Learning
i W Databases
ArcGIS I ArcGIS I
Many Others

Customization / Advanced Customization /


Programming Programming

Introduction to Introduction to
Extending the
Visual Basic Programming
W i ArcGIS
for ESRI ArcObjects i
Desktop
software with VBA
Applications

Other ArcObjects/VBA Resources


Developing Developing
Virtual
Getting to Applications Applications
Campus VBA i i
W B Know with ArcGIS with ArcGIS
Workshop
ArcObjects Engine Server
Series

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..

Introduction to Programming ArcObjects with VBA Introduction 1-10


VBA: Visual Basic for Applications

‹ Evolution of software customization languages


‹ VBA: Single programming language and development
environment embedded within an application
Past Future Now
Applications had separate Applications can share one
customization languages customization environment

Application Programming Application Programming


Language Language

Access Access Basic Access


ArcView® Avenue™ ArcView
Word Word Basic VBA
Word
ArcInfo AML ArcInfo

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 1-11

Visual Basic for Applications


The VBA development environment consists of two primary tools: the Customize dialog box
for interactively modifying the user interface, and the Visual Basic Editor for creating user
forms and for writing, testing, and debugging Visual Basic code. Because VBA is the industry
standard, there are two big advantages to programming in this environment. First, if you are
familiar with using VBA in a particular application, you will find it very similar (sometimes
nearly identical) in other applications that support it. Second, you will be able to (easily) use
object libraries between applications. When developing an application for Power Point, for
example, you might choose to embed objects from the ArcObject library (or vice versa).

Other applications that use the VBA development environment


Microsoft Office: Excel, PowerPoint, Word, and so on.
Visio
Corel WordPerfect Office 2000
Corel Draw 9
AutoCAD
MYOB Accounting (Accounting package for small businesses)
Micrografx iGrafx series (Business graphics)
OmniTrader (Securities tracking and analysis )
Many others …

Introduction to Programming ArcObjects with VBA Introduction 1-11


What can ArcObjects do?
‹ Use VBA to extend ArcMap/ArcCatalog
‹ Create custom
user forms,
buttons and
tools
‹ Automate
workflows
‹ Subject of this
course

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 1-12

Using VBA to extend ArcMap/ArcCatalog


Both ArcMap and ArcCatalog come with Visual Basic for Applications (VBA). VBA
provides an integrated programming environment and the Visual Basic Editor. VBA is an
excellent way to create custom commands. You can create a new button, tool, combo box, or
edit box (all referred to as UIControls), then attach code to the control’s events. Once you
have your custom control created, you can drag it to any toolbar. Macros can also be created
which can be executed from the Tools toolbar. By creating the UIControls and Macros you
can build sophisticated ArcGIS applications for the user to interact with and automate
workflows. All of these concepts will be covered in this course.

Introduction to Programming ArcObjects with VBA Introduction 1-12


What can ArcObjects do?
‹ Use stand alone programming language to extend
Desktop applications and geodatabase
‹ Create custom components
to enhance functionality Edit
Edit Task
Task
‹ Extending the ArcGIS
Desktop
Applications
Command
Command

Table
Table of
of Contents
Contents Tab
Tab

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 1-13

Extending ArcGIS Desktop Applications


In some cases, you will want to extend ArcGIS Desktop outside of VBA. You can create
custom objects that plug into ArcGIS Desktop with any programming language that supports
the Microsoft Component Object Model (COM), such as Visual Basic 6.0 or Microsoft Visual
Basic .NET. Custom commands or toolbars created outside VBA are often distributed as
ActiveX DLLs. If you have created custom commands and toolbars, you can distribute these
as ActiveX DLLs and easily add these objects to ArcMap or ArcCatalog. This will put the
code into a binary version of the object so the end user will never see the source code.
Components can be broadly categorized into two areas of customization: those that reside at
the application level, such as custom buttons, toolbars, windows and extensions, and those that
reside at the geodatabase level, such as custom feature class extensions and custom features.
Some of these more advanced customizations cannot be accomplished through the VBA
environment.
The information on this subject matter is discussed in the Extending the ArcGIS Desktop
Applications instructor-led course.

Introduction to Programming ArcObjects with VBA Introduction 1-13


What can ArcObjects do?
‹ Use the ArcGIS Engine Developer Kit to build custom
applications
‹ Developing Applications with ArcGIS Engine
Windows
Example

Java Example

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 1-14

The ArcGIS Engine Developer Kit


The ArcGIS Engine Developer Kit allows developers to create custom applications that can be
deployed to machines that do not currently have ArcGIS Desktop installed. It 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 including COM, .NET, JAVA,
and C++, which allows applications to be deployed on different platforms.
The information on this subject matter is discussed in the Developing Applications with
ArcGIS Engine instructor-led course.

Introduction to Programming ArcObjects with VBA Introduction 1-14


What can ArcObjects do?
‹ Use ArcGIS Server to build custom Web-based
applications
‹ Developing Applications with ArcGIS Server
Geodatabase Editing

Network Tracing
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming 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.

Introduction to Programming ArcObjects with VBA Introduction 1-15


Exercise options
‹ Exercise shortcut

‹ Full exercise steps

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 1-16

Exercise shortcut
Appearing at the beginning of an exercise, the exercise 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.

Full exercise steps


The main exercise steps provide detail on how to complete each task. If you are new to the
software, follow the full exercise steps.

Introduction to Programming ArcObjects with VBA Introduction 1-16


Exercise typographic conventions
Descriptive
Action text

9
9 Control
Note name

Keyboard
input
Warning

Question with hint

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.

Introduction to Programming ArcObjects with VBA Introduction 1-17


Note
Paragraphs prefaced with Note: provide inconsequential information, such as an optional way
to perform an action or platform-specific syntax for a script.

Warning
The large exclamation point symbol and bold text signals critical 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.

Question with hint


Questions require you to record answers in your course book. Questions are renumbered
within each exercise and may be followed by a hint.
Sometimes the answer to one question depends on your answer to a previous one. Courses that
use this teaching technique extensively will include an exercise worksheet as an appendix in
your lecture course book, enabling you to record all answers on the worksheet for easier
cross-referencing.
Answers to questions immediately follow each exercise.

Introduction to Programming ArcObjects with VBA Introduction 1-18


Exercise 1 overview
‹ Install the class data

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 1-19

Introduction to Programming ArcObjects with VBA Introduction 1-19


Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 1-20

Introduction to Programming ArcObjects with VBA Introduction 1-20


The VBA development
Introduction to Programming ArcObjects with VBA

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

‹ Visual Basic statements

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

Visual Basic Editor

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 2-3

The VBA development environment consists of two parts: the Customize dialog box for
modifying the user interface and the Visual Basic Editor for writing code.
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.

Customize dialog box


The Customize dialog box is a powerful tool that allows you to customize ArcMap and
ArcCatalog without writing a single line of code. You can create, add, move, and
remove toolbars and commands, and even add tools others have created.

Visual Basic Editor


The Visual Basic Editor provides an interface for creating forms and writing code. It
also provides several utilities for debugging and getting help that will be discussed
throughout this course.

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

‹ Drag commands onto toolbars or menus

Command Categories

Commands

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 2-8

As mentioned earlier, the Customize dialog box contains all ArcMap or ArcCatalog
commands. These commands are available on the Commands tab and are organized 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

Creating new commands (user interface controls)


The Customize dialog box contains controls you develop yourself in a category called
UIControls. You can add these commands to the user interface by dragging them onto a
toolbar or menu, just as you would any ArcGIS command. To create a new UIControl, click
New UIControl and choose one of the four types described below.
• UIButtonControl: a simple button or menu choice.
• UIToolControl: use to create a tool. Differs from a button in that the developer has access
to mouse and keyboard input while the tool is selected.
• UIEditBoxControl: a text line (on a toolbar or menu) that allows the user to type some
input.
• UIComboBoxControl: a pulldown list that allows the user to choose existing items (text)
or to type his or her own.
Once you have created one of these controls, the next step would be to write the Visual Basic
code behind the control user events (button clicks, mouse, keyboard, etc.) that make it work.

Adding custom commands from file


Custom commands are ActiveX controls or libraries stored as OLB, TLB, EXE, OCX, and
DLL files. You can add these custom commands from the Customize dialog box by clicking
Add From File. Once you add a custom control from file, it will be placed in the appropriate
category in the Customize dialog box (sometimes a new category is created). Just like the other
controls in the dialog, you must then drag the command to the desired location on the interface.
Note: These controls would have been developed in a standalone programming environment
such as Visual Basic or C++, and cannot be created in VBA.

Introduction to Programming ArcObjects with VBA The VBA development environment 2-9
Setting control properties
‹ Customize dialog box must be open
‹ Right-click a control to view and change properties
‹ Characteristics that define appearance
‹ Name

‹ Image

‹ Display text or image


‹ Begin a group

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 2-10

Command properties
While the Customize dialog is open, the user interface is in design mode. To access command
properties, simply right-click on a command and 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.

Text and image


There are three ways in which a command can be displayed on a toolbar: Text only (see
the Name property described above), Image only, or both Image and Text. Menu
commands (choices) may be displayed as Text or Image and Text; you may not use the
Image only choice for menu choices.

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

Affects all documents Normal Template

Affects all documents


Base Template
using this template

Affects this document This Document

‹ ArcCatalog only uses the Normal template

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 2-11

Templates
In ArcMap, there are three levels at which you can store your 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

‹ Current map overrides any templates


‹ For example, controls can be added or removed

Save in: Normal.mxt

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

Control source code


The code behind a command is called the source code or sometimes simply the source. By
right-clicking on a custom control (UIControl or Macro) and choosing View Source, you can
view (and edit) its source code. Because the existing ArcGIS commands have been compiled
as DLLs (and were written in C++ anyway), you cannot view or edit an existing command’s
source code.

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

Demonstration: Using the Customize dialog box


Your instructor will now use the Customize dialog box to perform some of the simple user
interface customizations discussed in this lecture.

Introduction to Programming ArcObjects with VBA The VBA development environment 2-15
Overview
‹ The VBA development environment
‹ Customize dialog box
‹ Create new toolbars and commands
‹ Add, delete, and move commands
‹ Set control properties
‹ Storing and distributing customizations
‹ Visual Basic Editor
‹ Code storage
‹ Modules

‹ Procedures

‹ Visual Basic statements

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

Code Modules Procedures


Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 2-17

Working with the Visual Basic Editor


The Visual Basic Editor is where you will write code and design user forms. There are several
utilities here for writing, testing, and debugging your VB programs. Before looking at VB
editing utilities, let’s examine how code is organized in the Editor.

Project Explorer
The Visual 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

Components of ArcGIS VBA code storage


All code written for an ArcMap document or for ArcCatalog can be accessed from the Visual
Basic Editor’s Project Explorer window. The Project Explorer organizes all projects that might
contain Visual Basic code, and these projects are analogous to the levels of customization
discussed earlier (Normal template, base template, map document). By using the Project
Explorer, you can access existing code documents (or modules) stored with the document or
application, or create new ones.
Visual Basic code always lives inside a module, which is nothing more than a document for
writing code. Modules, in turn, consist of procedures, which are VB programs (macros). The
smallest unit of Visual Basic code that can be executed is the statement. Statements are simply
lines of code.

Compact disk analogy


The code organized in the Visual Basic Editor is like your music collection. The Project
Explorer is the rack that contains all your compact disks. To access any of your music, you
must start at the CD rack. Just as the Project Explorer may have several Projects, your music
rack may have several sets of CDs: your CDs and your spouse’s, for example. Each CD in turn
contains several songs, just like a code module may contain several procedures. Individual
songs are composed of lines of lyrics, just as procedures are built from lines of code.

Introduction to Programming ArcObjects with VBA The VBA development environment 2-19
Writing Visual Basic statements
‹ Carry out actions
‹ Written inside procedures
‹ May have arguments
‹ Multiple arguments are separated with commas
‹ Some arguments are optional
Private Sub ShowMsgBox()
Beep
MsgBox "ESRI"
End Sub

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 2-20

Statements
The smallest unit of Visual Basic code that can be executed is a 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?"

I don’t want to argue


You will often hear the terms argument and parameter used interchangeably, but they are not
exactly the same thing. As a programmer using a function or sub procedure, you specify
arguments. As a programmer writing a sub or function, you define parameters. In other words,
they are called arguments when they are passed and parameters when they are received.
'Argument (intDollarAmount) …
intTotalTax = CalcTax (intDollarAmount)
'Parameter (Amount) …
Public Function CalcTax (Amount As Integer) As Integer
CalcTax = Amount * 0.07
End Function

Introduction to Programming ArcObjects with VBA The VBA development environment 2-20
Some common Visual Basic functions
‹ InputBox to get information
InputBox "Enter the new Landuse Code: "

‹ MsgBox to report a message


MsgBox "ArcMap is Great!"

‹ Combine (concatenate) strings with & …


‹ Get the Date or Time …
MsgBox "The date is " & Date

MsgBox "The time is " & Time

MsgBox "The date and time is " & Now

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 2-21

Visual Basic functions


There are several predefined Visual Basic functions that you can use to do things like get the
current date and time from the operating system, display several types of message and input
boxes, concatenate strings, and convert data types. Open the Visual Basic help topic Visual
Basic Language Reference > Functions for an alphabetical listing of VB functions.

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

Date and Time functions


Visual Basic has functions that return the current date, time, or both from the operating system.
These functions have no arguments (required or optional) and return values of the variant data
type.
Date: returns the current calendar date (e.g., 6/14/04)
Time: returns the current system time (e.g., 3:08:47 PM)
Now: returns both the current date and time (e.g., 6/14/04 3:08:47 PM)

Introduction to Programming ArcObjects with VBA The VBA development environment 2-22
Procedure types
‹ Event procedures
‹ Have an associated object (e.g., control)
‹ Code runs when the corresponding event occurs (e.g., click)

‹ Subroutine and function procedures


‹ No associated object
‹ Must be called
‹ Functions return a value

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 2-23

Procedures
All procedures are blocks of Visual Basic code and are simply a group of VB statements that
are executed sequentially. There are some important 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

‹ When an event is fired, the associated code executes

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 2-24

Controls respond to events


All controls have a predefined set of events that they can respond to. A control responds to an
event by running the associated event procedure—this does not mean you need to write code
for every event that a control supports, however, only those required to make your control
work. A UIButtonControl, for example, has five events that can be coded, but it is quite typical
to write code only for the Click event.
Each control type will have different available events available to code. A UIEditBoxControl,
for example, has a Change and a KeyDown event for responding to user keyboard input, while
a UIToolControl has events, such as MouseDown, MouseUp, and MouseMove, to capture user
input from the mouse.

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!"

Wrapper lines Write code to run when


are added UIButtonControl1 is clicked
automatically
A
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 2-25

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)

‹ Customize at any level

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 2-26

How many documents do I have?


As the name implies, the ThisDocument code module is associated with a document. You may
become confused, however, on opening an ArcMap document to find three ThisDocument
code modules. When you think of templates as documents, however, it makes perfect sense.
Each level of ArcMap customization is represented by a document: Global customizations are
stored in the Normal.mxt template, customizations applied to a set of map documents may be
stored in a base (intermediate) template, and customizations meant for a single map document
are stored in that map document itself. By writing code in the appropriate ThisDocument
module, you are controlling the scope for your programs.

What kind of code goes into a ThisDocument module?


You may write any macros you want in ThisDocument, but perhaps most importantly, all code
powering your UIControls will be written in one of the ThisDocument code modules.
Remember that before adding a UIControl to the ArcMap interface, you must indicate (in the
Customize dialog) where you want to store the new control (normal template, base template, or
in the current document). Once you have made your choice, the code you write for the control
will be in the corresponding ThisDocument module.
For example, you create a new UIButtonControl, and save it in Normal. When you right-click
the new interface control and choose View Source, you will find yourself writing code for the
control in the ThisDocument code module under the Normal project heading.

Introduction to Programming ArcObjects with VBA The VBA development environment 2-26
Creating a new module
‹ Module (standard module): Contains standalone code
‹ Class module: Contains a 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

Creating a new code module


New code modules can be added to your Visual Basic project by using the Insert menu on the
Editor interface or by choosing Insert from the Project Explorer context menu (as shown
above). When adding a new code module, be especially aware of where you are placing it
(Normal, Base template, Current document). There are three types of modules you may add,
which are described below.

Module (standard module)


Standard modules are used to write standalone procedures that you might want to call from
other Visual Basic programs. The most common use of standard modules is to contain code
that you use a lot. Instead of having to constantly rewrite the code to add a layer to a map, for
example, you could place the code in a standard module in your Normal.mxt, then reference
the procedure whenever it is needed.

Class module
Class modules are used to 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

Creating a new procedure


To add a new procedure to a code module, you can choose Procedure from the Visual Basic
Editor’s Insert menu, or you can simply type the procedure definition directly into the module.
When defining a new procedure, you need to provide the following information.

Scope
Scope defines how widely a procedure may be used and can be defined as either Public or
Private. A 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.

Sub versus Function


The two basic types of procedures are Subs (sub procedures) and Functions. If you only need
to perform some action and do not need to return a value, define your procedure as a sub.
Functions can also carry out some action but also have the ability to return a value. For
example, you could write a sub to add a layer to a map. The sub could simply take a pathname
from the user and add that data as a new layer. By writing the same procedure as a function,
you could add the data as a new layer, then also return a Boolean (true or false) value that
describes whether the operation was successful or not.

Parameters
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.

Running a procedure as a macro


The following slides will describe how you can run your procedures as macros. In order to see
your macros listed in the macros dialog (Tools > Macros > Macros) or in the Customize dialog
box (Macros category), you need to make sure they have a public scope. Procedures defined as
private will not appear (and therefore cannot be run) as a macro.

Introduction to Programming ArcObjects with VBA The VBA development environment 2-30
Running a subroutine or function procedure
‹ No event to cause code execution
‹ Must call the procedure
‹ Macro menu: Interface
‹ Call statement: Code

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 2-31

Running a procedure
Unlike event procedures, there is no object event to signal a subroutine or function procedure
to execute. In fact, these procedures will 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 the interface


To execute a procedure from the interface, choose Macros from the Tools menu. On the
Macros submenu, again choose Macros. In the dialog that is launched, select the procedure
you want to execute, then click Run.

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

'Simply call it using its name


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.

Adding a tool tip to a macro on a toolbar


Unlike UIControls, macros added to the interface do not have events such as Enabled,
ToolTip, and Message for you to code. However, there are ways to get at some of these
properties programmatically. The VBA Sub below changes the tool tip and message for a
macro called Project.NewMacros.Test.
Private Sub ChangeToolTip( )
Dim pItem As ICommandItem
Set pItem = _
ThisDocument.CommandBars.Find("Project.NewMacros.Test")
pItem.ToolTip = "My ToolTip"
pItem.Message = "My Message for the status bar."
End Sub

Introduction to Programming ArcObjects with VBA The VBA development environment 2-32
Getting help
‹ F1 key for context-sensitive help
‹ ArcObjects Developer Help
‹ 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.

ArcGIS Developer Help


When you install ArcGIS, you have the option of also installing the ArcGIS Developer Help. If
you installed the Developer Help, you can access it from the Windows Start menu > Programs
> ArcGIS > Developer Help > VB6 Help. In addition to help on individual ArcObjects classes,
the ArcGIS Developer Help has plenty of sample code that you can borrow and modify for your
own applications.

ArcGIS Developer Online


An online version of the ArcObjects Help is available from the ESRI Web site. ArcGIS
Developer Online contains updated code samples and documentation. You will find ArcGIS
Developer Online at the URL listed below:
http://arcgisdeveloperonline.esri.com
Visit this site frequently as it will be updated often with new samples and detailed explanations.
For versions earlier than ArcGIS 9 (8.x), this information can be found at ArcObjects Online:
http://arcobjectsonline.esri.com.

Introduction to Programming ArcObjects with VBA The VBA development environment 2-33
Exercise 2 overview
‹ Explore the Visual Basic Editor
‹ Navigate event procedures
‹ Add a new code module
‹ Run procedures
‹ Export code to a file on disk

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 2-34

Exercise 2: Design a user form


In this exercise you will do the following:
• Explore the Visual Basic Editor.
• Write simple VB statements in the Immediate window.
• Add a new control to the interface.
• Write code in various project modules.
• Run a macro from the interface.
• Run a macro from code.
• Export code.

Introduction to Programming ArcObjects with VBA The VBA development environment 2-34
Visual Basic code:
Introduction to Programming ArcObjects with VBA

How, where, and when?

Lesson overview 3-2


Object-oriented programming
Example: Object-oriented terms
How: Visual Basic syntax
contents
3-3
3-4
3-5
Preset ArcObjects variables 3-7
Automatic code completion 3-9
Where: Controls, documents,
and forms 3-11
Working with forms 3-13
Setting properties at design time 3-14
Writing code for a form 3-16
Using control properties at
run time 3-17
When: Form and control events 3-18
When: Map document events 3-20
Saving your work 3-22
Exercise 3 overview 3-23
Visual Basic code:
How, where, and
when?

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA

Introduction to Programming ArcObjects with VBA Visual Basic code: How, where, and when? 3-1
Lesson overview
‹ How?
‹ Object-oriented programming
‹ Visual Basic syntax
‹ Application and ThisDocument 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, …

‹ Manipulate objects to carry out tasks


‹ Properties: Characteristics of an object
‹ Methods: Things an object knows how to do
‹ Events: Actions that an object can respond to

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 3-3

Treat them like objects


The (perhaps over-used) term object-oriented programming simply means that your programs
work by using objects. Objects are basically anything you use in your Visual Basic code,
whether visible or not. Things like maps, layers, symbols, and spatial references are all
examples of ArcGIS objects, while UserForms, CommandButtons, and ComboBoxes are
examples of Visual Basic objects.
In object-oriented programming, you can work with existing objects (e.g., get the current map
the user is working in), or you can create new objects (e.g., make a new layer to add to the
map). Once you have referenced or created the objects you want to work with, you can
manipulate them by using their properties, methods, and events.
• Properties: A property is a characteristic (noun) of an object that, as a programmer, you will
be able to read (get) or write (set). As an everyday example, a computer might have
properties such as RAM, disk space, and monitor size.
• Methods: A method is an action (verb) that an object can carry out. A computer might have
methods such as boot up, log in, or crash.
• Events: Like methods, events are actions (verbs). Instead of actions that an object carries
out, however, events are actions that an object responds to (usually actions triggered by the
user). Events that a computer might have: type, move mouse, click mouse.

Introduction to Programming ArcObjects with VBA Visual Basic code: How, where, and when? 3-3
Example: Object-oriented terms

Car Map

Property Horsepower MapUnits

Method Accelerate AddLayer

Event Brakes are pressed SelectionChanged

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 3-4

Object-oriented programming terms


Part of learning anything new, of course, is learning new terminology. Some common terms that
you will hear throughout this course for describing object-oriented concepts are listed here.
The objects you work with in your Visual Basic code are, in reality, nothing like real-world
objects; they are simply blocks of code that are held in memory. Conceptually, however, they
are very much like everyday objects in that they have characteristics (properties), actions they
can perform (methods), and actions that they can respond to (events). The syntax for working
with object properties and methods is described on the following page.

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

‹ Assign a value to a property with Object.Property = value


myMap.Name = "Zaire"

‹ Call methods with Object.Method arg1, .., argN


myMap.AddLayer CityLayer
myMap.SelectFeature CityLayer, KahembaPoint
myMap.ClearSelection

‹ ArcObject events will be covered in Lesson 16

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 3-5

Visual Basic syntax


Regardless of the object with which you are working, the VB syntax is basically always the
same: the name of the object variable, followed by a dot ( . ), followed by one of the object’s
methods or properties.

Properties
Follow the syntax below to set (assign) a new value to an object property.
myObjectVariable.SomeProperty = ANewValue
To get (read) an object property, use this simple syntax.
myObjectVariable.SomeProperty
Keep in mind that you may not be able to set (assign a new value to) all 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

‹ A Starting point for your code


‹ More about variables in the next lesson
MsgBox "You are currently working in " & Application.Name
MsgBox "The current map is " & ThisDocument.Title

Object
Object Property
Property

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 3-7

Where to begin?
In ArcMap and ArcCatalog, you have two preset variables that 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

‹ Press Tab, Enter, or Space to select the method or


property

PressTab,
Press Tab,
Enter, or
Enter, or
Space
Space

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 3-9

Those who finish with the fewest keystrokes win


One of the best ways to avoid getting errors in your Visual Basic code is to be lazy. The Visual
Basic Editor has several utilities that help you write code by providing timely help, helping you
navigate through code, and even completing some of your code for you. When you let Visual
Basic automatically complete such code as variable names, methods, and properties, you avoid
the possibility of making simple typographical errors that may cause run-time errors in your
code.

Auto Quick Info


Auto Quick Info is a feature that was discussed briefly in the last lecture. As you type a
statement that Visual Basic recognizes, a box (that looks like a tool tip) will pop up with the
proper syntax required. You will be able to see all arguments required for the statement, as well
as any optional ones (shown in square brackets). If the statement you are typing returns a value,
you will also see the return data type (e.g., As Integer).

Automatic code completion


Upon typing an object variable that Visual Basic recognizes, followed by a dot, a list of all
methods and properties available for that object will appear. You can then scroll through the list
manually or type the first few letters to choose the method or property you want to use. Upon
pressing Tab, Enter, or Space, the highlighted method or property will be added to your code.
This automatic code completion feature is good not only because it saves you some typing, but
also because it helps catch errors. If the code completion list does not appear when it should, it
means that Visual Basic does not recognize the object variable you typed, and it’s likely that
you made a mistake earlier in your code.

Introduction to Programming ArcObjects with VBA Visual Basic code: How, where, and when? 3-9
Automatic completion of variable names
In addition to the automatic code 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

Where to write code


The previous lesson discussed using the Visual Basic Editor to write standalone procedures
(macros) and how to use the customize dialog to add macros or UIControls to the ArcMap or
ArcCatalog interface. Another place you may want to write code is inside of a form module.
Forms are nothing more than windows (dialogs) that contain a set of controls. Forms are ideal
for certain types of user interaction, especially where a lot of data input may be required.
Instead of having to pop up several message boxes or input boxes in your code, you can simply
launch a single form to prompt for many pieces of information at once. Forms are also much
more intuitive for a user to work with: There are various types of controls you can place on a
form, each designed for a particular type of data input. Some common form controls are listed
below (there are many others).
• TextBox: Displays or allows the entry of text. Use TextBoxes to display information or
more commonly, to allow a user to type some input. In the example above, TextBoxes are
used to accept latitude and longitude values from the user.
• OptionButton: Allows one selection to be made from a group of possible choices.
OptionButtons are sometimes referred to as RadioButtons, as they function like the station
preset buttons on old car radios: Upon selecting one OptionButton, all others automatically
become unselected. In the example above, OptionButtons are used to indicate latitude
(North, South) and longitude (East, West). Only one from each group may be selected at a
given time.
• CheckBox: Displays the selected state of an item (checked=selected,
unchecked=unselected). Use CheckBoxes to have the user answer yes/no questions.

Introduction to Programming ArcObjects with VBA Visual Basic code: How, where, and when? 3-11
• CommandButton: Begins execution of an action or series of actions. The code 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

Visual Basic forms


When you add a UserForm module to your Visual Basic project, you are really adding two
things: a form designer, in which you can add and position controls for the form, and a form
code module that stores all the code required to make the form work.

Adding a new form module


To add a new form to the Visual Basic project, click the Insert menu on the editor interface or
right-click in the Project Explorer window and choose Insert > UserForm from the context
menu. When adding a form to an ArcMap document, be sure to add it to the proper project (e.g.,
normal.mxt or the current mxd) by highlighting the desired level of storage in the project
explorer. All forms you add to an ArcCatalog project will be stored in the normal template
(normal.gxt).

Designing a form
Remember that a form consists of a design window and a code module. A new user form will
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.

Writing code for a form


After the desired controls have been added to the form, positioned so they are intuitive for the
user to work with, and their desired properties set, the next step is to write code to power them.
Every control on a form will have a set of events for which you may provide code, as will the
form itself. By providing code in the appropriate control event procedures, you can prepare the
form for the anticipated user interaction.

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

Setting form and control properties


The Properties window displays design time properties for the selected object (control or form)
in the form designer. Upon selecting an object (by clicking it on the form designer or by
choosing it from the Properties window dropdown list), you can set any of its design time
properties by clicking in the Properties window. To set a common property for several controls
at once, you can hold down the shift key or click and drag a box to select several controls.
When more than one control is selected in the form designer, you will only see those properties
common to all selected controls in the Properties window.
Varying with the type of property, there are several ways in which they are set. Properties such
as Name and Caption, for example, are set by simply typing in a new text value. Font, on the
other hand, is set by launching the Font Properties dialog and defining font style, font size, bold,
italic, and so forth. Some properties will toggle between true and false (e.g., Enabled), some will
require numbers (e.g., Height and Width), and others will allow you to choose from a finite list
of possible values (e.g., BackStyle).

Naming controls
One property that is common to all controls (and to the form itself) is the Name 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.

Object Prefix Example


Command button cmd cmdApply
Form frm frmConvertCelsius
Label lbl lblFahrenheit
Text box txt txtCelsius
List box lbo lboAttributes
Combo box cbo cboGeometryType
Check box chk chkWriteLogFile
Option button opt optLegendType

See the Microsoft Web site listed below for a comprehensive list of recommended naming
conventions:
http://msdn.microsoft.com/library/default.asp?url=/library/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

Writing code for a form and controls


Each form has a code module that stores its associated code. All code that powers a form
(including each form control) is stored in the form code module. After using the form designer,
the form toolbox, and the Properties window to design your form, the next step is to write the
code required to make the form work. Just as each type of control has a different set of design
time properties for you to set, they also have a unique set of events for which you can write
code. As a programmer, you do not need to write code for every control event, only the ones
that are required to make your form work.
There are several ways to access a form’s code module. The easiest way is to simply double-
click a control in the form designer, which opens the form’s code module and places your
cursor in the default event for that control (e.g., the Click event for a CommandButton).
Optionally, you can toggle between the form designer and its code module by choosing Code or
Object from the Visual Basic Editor’s View menu (as shown above). The Project Explorer
window also has controls (at the top) for switching between these two components of your
form.

Introduction to Programming ArcObjects with VBA Visual Basic code: How, where, and when? 3-16
Using control properties at run time
‹ Get/Set properties with code while the form is running
‹ Syntax: Object.Property
‹ Controls are objects

Private Sub cmdApply_Click()

strFTemp = ( txtCelsius.Text * 9 / 5 ) + 32
lblFahrenheit.Caption = "Fahrenheit: "& strFTemp

End Sub

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 3-17

Getting and setting control properties at run time


The properties you set in the form designer are used primarily to control the appearance of a
form when it is first launched. When a user begins to interact with your form, however, it may
also become necessary to get and set control and form properties during run time.

Syntax for getting and setting control properties


Remember that controls are Visual Basic objects, and the syntax for working with object
properties is Object.Property.
In the example above (when the form’s Apply button is clicked), the Celsius temperature
entered by the user is referenced using the TextBox control’s Text property (txtCelsius.Text).
A temperature in Fahrenheit is calculated and then placed on one of the form’s labels by setting
the Label control’s Caption property (lblFahrenheit.Caption = "Fahrenheit: " & strFTemp).

Run-time versus design time properties


Most control properties can be set either at design time or at run time. Indeed, you will often
provide an initial value at design time, only to change it in your code at run time. There are,
however, some properties that may only be set at design time. Although you can get these
properties at run time, you will receive an error if you try to set a new value at run time. Perhaps
the best example of this is the Name property that each control has. If you provide a name at
design time, you cannot change the name at run time. Controls that are added at run time,
however, can also have their name set at run time.
Consult the Visual Basic Help for control properties that are read-only at run time.

Introduction to Programming ArcObjects with VBA Visual Basic code: How, where, and when? 3-17
When: Form and control events
‹ Code runs when an event fires
‹ Different controls have different sets of events
‹ Form events

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 3-18

Control events
Every Visual Basic control has a set of events to which it can 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)

‹ Event procedures for the MxDocument object


‹ Open, close, new, change, etc.

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).

Scope of ArcMap document events


The three documents for which events can be coded in ArcMap represent different levels of
customization. By writing your event code for the appropriate document, you can control the
scope of ArcMap customization, as described below.
Document event code in ArcMap’s Normal template will execute for all maps when the
corresponding event occurs; this is a global customization. For example, you may want to
display a custom splash screen with your company logo each time a map document is opened.
To accomplish this, you would supply code in normal.mxt’s OpenDocument event.
Document event code in an ArcMap base template (*.mxt) will execute only for map documents
that were based on that particular template. You may have several parcel maps, for example,
that will be produced from a template called ParcelMap.mxt. When a user of a parcel map
changes to PageLayout view, you may want to display a custom toolbar. You would write such
code in the ParcelMap.mxt ActiveViewChanged event procedure, thus providing this behavior
for all future maps that are created from the template.
For document event code that is specific to a single map, you can provide document event code
in the map document itself (*.mxd). If you have one map that contains restricted information,
for example, you could code the map’s OpenDocument event procedure to require a password
before opening it. No other maps would exhibit this behavior.

Introduction to Programming ArcObjects with VBA Visual Basic code: How, where, and when? 3-20
ArcMap document event run order
Potentially, you can have code for a document 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

Saving maps and templates


The primary difference between VBA and regular Visual Basic is that code in VBA must
always be stored in a document. Unlike a programmer using standalone Visual Basic, a VBA
programmer has no way of compiling his or her code into a DLL or EXE, for example.
Therefore, in ArcMap and ArcCatalog (or any other application that uses the VBA development
environment), all code is saved with a document of some sort.
In ArcCatalog, all customizations are stored in a single document: Normal.gxt (in the user’s
profiles). In ArcMap, remember that customizations (including code) can be stored at three
different levels and with various types of documents. Whenever you write code in ArcCatalog
or ArcMap, you are storing that code in some document on disk, whether you realize it or not.
All ArcGIS code is stored in either a normal template (normal.gxt, normal.mxt), a base template
(*.mxt), or a map document (*.mxd). When programming in ArcMap, you need to be especially
careful where you place your code, as this will affect the scope of your customizations.

Exporting code modules


In addition to storing your code in one of the documents listed above, you also have the option
of exporting code to a separate file on disk. To export a code module (user form, standard, or
class module), right-click the desired module in the Project Explorer and choose ‘Export …’
from the context menu that appears. You will be prompted for a name and a location on disk for
the exported file. When exported, a module’s extension will indicate whether it is a user form
(*.frm), a standard module (*.bas), or a class module (*.cls). These files can then be imported
into other projects such as another ArcMap document, ArcCatalog, or even a standalone Visual
Basic project. Note that although you can easily export your code modules to disk, the code
cannot be executed except in the context of an application such as ArcMap or ArcCatalog.

Introduction to Programming ArcObjects with VBA Visual Basic code: How, where, and when? 3-22
Exercise 3 overview
‹ Create a form
‹ Set initial control properties
‹ Write code to convert to decimal degrees
‹ Test and debug the form
‹ Work with preset variables
‹ Application

‹ ThisDocument

‹ Save your work

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 3-23

Exercise 3: Design a user form


In this exercise you will:
• Create a new user form.
• Add controls to the form.
• Set control properties at design time.
• Write code to convert degrees/minutes/seconds values on the form to decimal degrees.
• Test your form with actual latitude and longitude values.
• Write code using the preset Application and ThisDocument variables.
• Export your form to its own file on disk.
• Save your map.

Introduction to Programming ArcObjects with VBA Visual Basic code: How, where, and when? 3-23
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 3-24

Introduction to Programming ArcObjects with VBA Visual Basic code: How, where, and when? 3-24
Using variables
Introduction to Programming ArcObjects with VBA

Lesson overview 4-2


Variables
Working with variables
Dim (dimension) statement
contents
4-3
4-4
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
Controlling If Then 4-15
Decision making: The Select
Case statement 4-17
Levels of variable scope 4-19
Procedure-level variables 4-21
Module-level variables 4-22
Public-level variables 4-23
Static variables 4-24
Exercise 4 overview 4-25
Using variables

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA

Introduction to Programming ArcObjects with VBA Using variables 4-1


Lesson overview
‹ Variables defined
‹ Working with variables: Declaring, assigning values,
evaluating
‹ Passing and returning values
‹ Function procedures

‹ Comparing values
‹ Branching: Making decisions in your code
‹ Variable scope

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 4-2

Overview
This lesson will cover the use of variables in your Visual Basic code.

Basics of working with variables


• Declaring
• Setting
• Evaluating

Storing values in a variable


• What kinds of data can be stored in a variable?
• Using variables to pass and return values.
• Using relational operators with variables.

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.

Introduction to Programming ArcObjects with VBA Using variables 4-2


Variables
‹ An empty box for storing values
‹ Of a specific type (integer, date, string, etc.)
‹ The value stored can change

'the VB version of: a² + b² = c², is …


dblCSquare = (dblA * dblA) + (dblB * dblB)

'convert Celsius temperature …


intTempCelsius = InputBox ("Enter temperature (C): ")
intTempFahrenheit = (intTempCelsius * 1.8) + 32

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 4-3

Remember 7th grade algebra?


Variables are simply containers (like an empty box) that can contain a value, and if you have
done any type of programming before you probably had to work with variables. The values
stored by a variable may be numeric (bytes, integers, double-precision floating point
decimals, etc.), text (string), dates, or even objects (such as forms, controls, maps, and
layers). Variables (as the name implies) can change their value. For example, a variable
called ‘myAge’ might have a value of 33 at one point and then be changed to store the value
43 shortly thereafter.

According to the Visual Basic help, a variable is …


“ … a named storage location that can contain data that can be modified during program
execution. Each variable has a name that uniquely identifies it within its scope. A data type
can be specified or not.”

Uses for variables in a Visual Basic program


Storing a value returned by a function or calculation
datThreeWeeksFromToday = Date + 21
'Date is a Visual Basic function that returns the current date from
the OS
Looping a specified number of times (covered in Lesson 7)
For intCount = 0 To 200
Storing an object property
intLayerCount = theParcelMap.LayerCount
Storing user input
theAnswer = MsgBox ("Format your hard drive?", vbYesNo)
'Using parentheses forces a return value.
Representing constant values
PI = 3.1415926535897932

Introduction to Programming ArcObjects with VBA Using variables 4-3


Working with variables
‹ Declaring: Create a variable
strDog
strDog
Dim strDog As String

‹ Setting: Store a value


strDog = "Sparky"

‹ Evaluating: Get the value


Sparky strDog
strDog
MsgBox strDog

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).

Storing a value in a variable


To store a (simple data type) value in a variable, use the equal sign ( = ). Whatever is
evaluated on the right side of the equal sign will be stored in the variable.
The example above is a simple assignment statement; the text Sparky is stored in the variable
called strDog.
Here are some more examples of assigning a value to a variable.
strName = InputBox ("What’s your name?") 'The text typed from the
user is stored in strName
intMySistersAge = intMyAge – 2 'Whatever my age is, my
sister will always be 2 years younger
strApplicationName = Application.Name 'ArcMap or ArcCatalog?

Introduction to Programming ArcObjects with VBA Using variables 4-4


Retrieving a value from a variable
To get a value from a variable, you can simply refer to the variable itself. If I have a variable
called intPrice, for example, and it stores the value 30000, I can calculate sales tax with a
statement like: intTax = intPrice * 0.0825.
The example on the slide above displays the text stored in the variable strDog in a message
box. Notice that the string ‘strDog’ doesn’t appear in the message box—rather, the value
stored in the variable is displayed.

AML and Avenue comparison


In AML, all variables are treated as gigantic strings (regardless of size), and all are put into
the same refrigerator-sized box. Although AML makes it easy to work with variables, it does
so at the expense of storage space. Visual Basic lets you choose the right kind of variable for
the task.
Likewise, in Avenue, a programmer does not need to declare variables, which makes the
code more succinct but makes debugging much more difficult.

Introduction to Programming ArcObjects with VBA Using variables 4-5


Dim (dimension) statement
‹ Declares a variable for future use
‹ Defines the variable as a particular type
'Declare variables
Dim strFilePathName As String
Dim datSparkysBirthday As Date
Dim intCount As Integer

'Other ways to declare variables (to be discussed later)..


Private strFilePathName As String
Public datSparkysBirthday As Date
Static intCount As Integer

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 4-6

Dim statement
To declare a variable in Visual Basic, it is common to use the Dim keyword. Dim is short for
Dimension (although using the word Dimension would 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.

Type (bytes) Sample value


String (10+length) Elm Street
Boolean (2) True or False
Date (8) 1/1/100 to 12/31/9999
Byte (1) 0 to 255
Integer (2) -32768 to 32767
Long Integer (4) -2,147,483,648 to 2,147,483,647
Single (4) 1.401298E-45 to 3.402823E38 positive
Double (8) 1.79769313486232E308 maximum
Variant (>16) Any type

Introduction to Programming ArcObjects with VBA Using variables 4-6


Variable naming rules
Must begin with a letter
Cannot contain periods
Cannot contain data type characters (@, $, %, &, #)
Can contain an underscore ( _ )
No more than 254 characters
Reserved words cause errors (For, And, Loop)
Should have unique names within the same scope (more about scope later)

Variable naming conventions


Using standard variable naming is important for making code easier to follow (especially by
someone other than the author of the code) and to avoid ambiguity. The standard developed
by Microsoft, and used by most programmers, is to use lowercase and uppercase in variable
names and to name the variable with a three-letter prefix indicating the data type. If you
follow such a naming convention, other programmers will find it easier to understand your
code.
Below is a sample of the Microsoft naming convention (commonly referred to as Hungarian
notation).

Type Prefix Example


Boolean bln blnStatus
Byte byt bytAge
Date dat datBirth
Double dbl dblLatitude
Integer int intDistance
String str strAddress
Variant var varLongitude

Introduction to Programming ArcObjects with VBA Using variables 4-7


Assigning a value to a variable
‹ Assign a value directly or with a return value
‹ Use parentheses to return a value from a function

'Assign values directly


intCount = 23

'Assign a function return value


!
strFilePathName = InputBox("File to open: ")

'Assign an object property


strMapName = ThisDocument.Title

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 4-8

To assign a value to a variable, use the equal sign. Whatever appears or is 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.

Fun with variables


It is safe to say that most pitfalls encountered when debugging an application can be directly
attributed to variables. Below are illustrated some common problems.
Order of evaluation is always left to right. Use parentheses to change this order.
dblAnswer = 2 * 4 + 8 / 4 – 1 'This evaluates to 9.0000
dblAnswer = (2 * 4) + 8 / (4 – 1) 'This evaluates to 10.6667
Storing a decimal number in an integer variable will not give an error; instead, the number
will be rounded behind your back.
Dim intAnswer As Integer
intAnswer = 3 / 4 'intAnswer now contains the value 1
A value will not be returned from a function unless you place parentheses around the
argument list.
intAnswer = MsgBox "Will you marry me?", vbYesNo, "A Proposal"
'This will give an error
intAnswer = MsgBox ("Will you marry me?", vbYesNo, "A Proposal")
'This works.

Introduction to Programming ArcObjects with VBA Using variables 4-8


Avenue comparison
In Avenue, there are several requests for changing values between strings (AsString) and
numbers (AsNumber). This step is not required in Visual Basic, as the software will
automatically treat your variable as a string or as a number depending on the context in
which it appears. Below is an example of code that would not work in Avenue but will in
Visual Basic.
Dim strAge As String
Dim intNextYearsAge As Integer
strAge = "32"
intNextYearsAge = strAge + 1 'ÅHere strAge is treated like a
number.
MsgBox "Next year you will be " & intNextYearsAge " Years old"
'ÅHere intNextYearsAge is treated as a string.

Introduction to Programming ArcObjects with VBA Using variables 4-9


Function procedures
‹ Functions return a value
‹… by assigning a value to the function name
‹ Syntax for calling a function: Value = Function ( arguments )

'Call the TotalPrice function


Private Sub Purchase()
dblPrice = InputBox ("Enter price before tax:")
dblTotal = TotalPrice(dblPrice)
MsgBox "Here is the price including tax: " & dblTotal
End Sub

'The function procedure TotalPrice


Private Function TotalPrice(Price As Double) As Double
TotalPrice = Price * 1.0775
End Function

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).

Returning a value from a function


As a programmer writing a function procedure, you have the ability to return a single value
or object (however, this single object could be a Collection object that contains several
objects). In the function definition, the programmer specifies the type of object or value to be
returned, as well as any required inputs (parameters). Inside the function, the programmer
can refer to values passed to the function by the names listed in the function definition. In the
code above, for example, Price is listed as a required function parameter (as a double). Inside
the function procedure, the variable Price will refer to whatever was passed in when the
function was called, regardless of what this variable may have been named in the calling
procedure.
To pass a value back from a function, the programmer simply sets the name of the function
equal to the value he or she wants to return.

Introduction to Programming ArcObjects with VBA Using variables 4-10


Capturing a function’s return value
It is possible to call a function without capturing the return value. Some functions, for
example, are used primarily to perform some action (such as deleting a file from disk) and
return a value simply to indicate the success of the operation (e.g., True or False). If you are
confident that such a function will work (or you simply do not care), you would not
necessarily require the return value.
To store the result of a function in a variable, you need to place parentheses around the
argument list when calling the function (if there are no required function parameters, you can
return a value with or without using empty parentheses). In the example above, the
TotalPrice function is called from the Purchase sub procedure, with the one required
parameter surrounded in parentheses. This ensures that the return value will be stored in the
dblTotal variable.

Introduction to Programming ArcObjects with VBA Using variables 4-11


Comparing values
‹ Use relational operators ( <, >, <>, = )
‹ Return a Boolean result (true/false)
intAnswer = MsgBox ("Delete File?", vbYesNo)
MsgBox intAnswer = vbYes

‹ Functions MsgBox "Number? " & IsNumeric(VagueVariable)


‹ IsDate

‹ 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

Boolean expressions evaluate to True or False


In order to make decisions in your code at run time, you might need to evaluate certain
conditions. Common decision making in Visual Basic uses a Boolean value (True or False)
in order to run corresponding sets of code. To evaluate a variable and return a True or False
result, you can use familiar relational operators such as < (less than), > (greater than), =
(equal to), and <> (not equal to).

Visual Basic MsgBox constants


The Visual Basic message box function does not return a Boolean result. Instead, it returns a
numeric value that can be referred to by a constant name. The Visual Basic MgBox constants
are: vbYes, vbNo, vbCancel, vbAbort, vbIgnore, vbRetry, and vbOK. If you need a Boolean
value, you can compare the message box result with a particular constant (as shown in the
first example above).

Connectors
In order 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.

Introduction to Programming ArcObjects with VBA Using variables 4-12


Below are some examples of simple Boolean expressions and their results.

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

Functions for evaluating variables


Visual Basic has some functions for evaluating variables. There are three functions for
checking the type of value stored in a variable: IsDate, IsNumeric, and IsNull. These
functions return a Boolean value that indicates whether the variable contains a value that can
be used as a date or a number or whether the value is Null. The Visual Basic TypeName
function returns a string that describes the data type of a specified variable.
Below is an example of how the IsNumeric function might be used.
Dim strSalary As String
strSalary = InputBox ("Enter your salary" ) 'Å strSalary is a
string variable

Dim blnIsNumber As Boolean


blnIsNumber = IsNumeric (strSalary) 'ÅIf any non-numeric
characters were entered, this will be False (e.g., dollar signs
'or commas)
MsgBox "Did you type only numeric characters? " & blnIsNumber

Introduction to Programming ArcObjects with VBA Using variables 4-13


Decision making: The If Then statement
‹ Branch based on a condition
‹ Use a Boolean expression
‹ Make decisions

'Syntax example:
If a condition is true Then ?
'do something...
End If

If intLayerCount < 1 Then


MsgBox "There are no layers in your map!", vbExclaimation
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

Introduction to Programming ArcObjects with VBA Using variables 4-14


Controlling If Then
‹ Exit Sub: Exits procedure before completion
‹ ElseIf: Check another condition
‹ Else: Code for a False condition
Private Sub WelcomeUser()
If strUser = "Mark" Then
MsgBox "Welcome Mark"
ElseIf strUser = "Dana" Then
MsgBox "Welcome Dana"
Else
MsgBox "You are not an authorized user!"
Exit Sub
End If
'Code here to add layers to the map …
'Code here to start an edit session …
End Sub

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 4-15

Controlling the flow of an If Then statement


If Then statements in Visual Basic can be more complex that those that simply evaluate a
single condition. If needed, a programmer can evaluate numerous conditions in a single If
Then block by using keywords such as ElseIf and Else. Inside an If Then block, execution of
the entire procedure may also be terminated early by using Exit Sub.

Exit Sub
When 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

Introduction to Programming ArcObjects with VBA Using variables 4-15


ElseIf and Else
To check more than one condition in an If Then block, a programmer can use the ElseIf
keyword. ElseIf requires another Boolean condition to evaluate. Using ElseIf, it is possible to
evaluate a (potentially) infinite number of conditions. To provide code for a false condition
in an If Then statement, use the Else keyword. Else does not require another expression, as it
provides the code that will run when none of the other conditions in the If Then … ElseIf
block are true.
theAnswer = MsgBox ("Save edits?", vbYesNoCancel)
If theAnswer = vbYes Then
'Code here to save edits, stop editing
ElseIf theAnswer = vbNo Then
'Code here to stop editing without saving
Else 'User pressed Cancel
Exit Sub
End If
MsgBox "Edit session is complete"

Introduction to Programming ArcObjects with VBA Using variables 4-16


Decision making: The Select Case statement
‹ Branches based on a value
‹ May use a range or list of values
‹ Case sensitive

‹ Alternative to several If Then Else statements


Select Case someVariable
Case Is = someValue
'Do this
Case someValueA, someValueB, someValueX
'Do that
Case startValue To endValue
'Do the other
Case Else
MsgBox "Invalid entry!"
End Select

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 4-17

Select Case
In addition to the If Then branching construct, a Visual Basic 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

Introduction to Programming ArcObjects with VBA Using variables 4-17


In the example above, the Select Case statement evaluates a numeric input (any type of
variable, however, can be used in a Select Case statement). Once a case is found that fits the
variable’s value, no other cases are evaluated. This means that even if more than one of the
cases fits, only the first one encountered will execute for a given variable. If none of the
cases fit the variable’s value, the Case Else block of code will execute. If a Select Case
statement does not have a Case Else, no code within the block will execute unless the
variable’s value fits one of the cases.
The End Select statement must be used to terminate a Select Case statement.

Introduction to Programming ArcObjects with VBA Using variables 4-18


Levels of variable scope
‹ Procedure-level: Local to a single procedure
‹ Module-level: Local (private) to a single module
‹ Public-level: Available to all project modules

Module-level

Public-level
Procedure-level

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 4-19

Variable scope
The term scope, when referring to a variable, describes the 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.

House pets analogy


You can think of variables as house pets, each one with a different scope, or range of
territory.
Procedure-level variables: Procedure-level variables are local to a single procedure (sub or
function). Like the goldfish in the slide above, they are restricted to a single goldfish bowl
(procedure), outside of which they cannot live.
Module-level variables: Module-level variables are variables that can work within a single
module. Like the housecat above, these variables can roam within a single house (module)
and can visit each goldfish bowl (procedure) inside the house. The housecat is not allowed
outside of the house, however, as she will instantly be hit by a garbage truck.
Public-level variables: Public-level variables have the widest scope; they are global to an
entire Visual Basic project. Public-level variables are like the dog in the slide above. They
can freely roam the neighborhood (project) and are welcomed in every house (module) they
come to (OK, so they are not exactly like dogs). Public-level variables are not destroyed until
the project closes.

Introduction to Programming ArcObjects with VBA Using variables 4-19


Variable naming conventions II
In addition to some of the variable naming conventions described earlier, it is common for
some programmers (and a good practice) to name variables with an additional prefix
describing their scope, as shown below.
Public-level: prefix with ‘g_’ (for global)
Module-level: prefix with ‘m_’
Procedure-level: no prefix

Introduction to Programming ArcObjects with VBA Using variables 4-20


Procedure-level variables
‹ Declared within a procedure
‹ Not recognized outside its procedure
‹ Destroyed when procedure ends

'Procedure1
Private Sub cmdSet_Click()
Dim intNumber As Integer 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.

Introduction to Programming ArcObjects with VBA Using variables 4-21


Module-level variables
‹ Declared with Dim or Private in a module’s General
Declarations section
‹ Must initialize (assign a value) within a procedure
‹ Available to all procedures in a module

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.

Module-level variables in a User Form


It is quite common to use module-level variables in a form module. Remember that module-
level variables are declared in General Declarations but cannot have values assigned there.
When using module-level variables in a form module, therefore, the best (and therefore most
common) place to initialize module-level variables is in the UserForm_Initialize event
procedure. Because Initialize is the first event procedure to fire for a form, all later event
procedures (button clicks, etc.) will have access to the module-level variable values.

Introduction to Programming ArcObjects with VBA Using variables 4-22


Public-level variables
‹ Declared with Public in the General Declarations section
of a module
‹ If declared in a form, other modules must reference form
MsgBox “Hello ” & GetName(frmHello.g_intID)

‹ Available anywhere in the project


frmHello Module1
Public g_intID As Integer Public Function GetName()as String
Select Case frmHello.g_intID
Private Sub SetID() Case 0
Randomize GetName = “Hercules”
g_intID = Int(11 * Rnd) Case 1
'more code here 'more code here
End Sub End Sub

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.

Tips for using public-level variables


As a general rule, the use of public-level variables should be avoided whenever possible.
Public variables will remain in memory for as long as your application is running, unless you
explicitly destroy them. This can take up valuable memory resources and may be difficult to
manage. If you need to use public variables, it is best to declare them in their own standard
module. This way, you can easily keep track of the variables that you have defined with a
public scope. You should be careful when declaring public-level variables in a form module
because even though they are public-level in scope, these variables will be destroyed when
the associated form is unloaded from memory. When referring to a public-level variable that
was declared in a form module, you must preface the variable name with the name of the
form, as shown in the slide above.

Introduction to Programming ArcObjects with VBA Using variables 4-23


Static variables
‹ Initialize first time their procedure runs
‹ Does not reinitialize variables (Dim does)

‹ Preserve the value between procedure executions


‹ Used for procedure-level variables only

Private Sub cmdSet_Click()


Static intNumber As Integer
intNumber = intNumber + 1
1
lblNumber.Caption = intNumber
End Sub

'Click Set a second time: 2


'Click Set a third time:
3

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).

Introduction to Programming ArcObjects with VBA Using variables 4-24


Exercise 4 overview
‹ 4A: Review variable scope
‹ 4B: Create a guessing game
‹ Generate a random number
‹ Pass the number to a function that selects a state
‹ Get the user’s guess from an inputbox
‹ Compare each guess to the selected state’s name
‹ Keep track of the number of guesses the user makes
‹ Write code to give hints about the selected state

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 4-25

Exercise 4A: Work with variable scope


In this exercise, you will explore variables of different scope by typing variables and
declaration statements into a predefined form.

Exercise 4B: Create a guessing game


In this exercise, you will explore variables of different scope and data types by creating a
guessing game. The application will randomly select one of the states in the United States,
zoom in to it, then ask the user to guess which state they are looking at. You will also write
code to keep track of how many guesses the user has made, as well as how many states he or
she has guessed correctly. The scope of variables used is an important factor in the design of
this application. It also illustrates some common uses of variables such as storing an object’s
property (state name), storing a value returned from a function (the Visual Basic Rnd
function), passing values to functions or subs (passing a random number to a procedure that
chooses a state), and incrementing a count (number of guesses).

Introduction to Programming ArcObjects with VBA Using variables 4-25


Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 4-26

Introduction to Programming ArcObjects with VBA Using variables 4-26


Programming with
Introduction to Programming ArcObjects with VBA

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

Introduction to Programming ArcObjects with VBA Programming with class 5-1


Lesson overview
‹ Understanding objects and classes
‹ Class libraries
‹ Instantiating objects
‹ Declaring and setting object variables
‹ Creating your own classes
‹ Distributing classes

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 5-2

Overview
This lecture will discuss some of the more important concepts of object-oriented programming.

Classes defined
The difference between an object and a class

Where classes come from


Class libraries
Referencing additional class libraries

How to work with existing classes


Using the Visual Basic Object Browser
Instantiating objects
Working with object variables

How to write your own class


Client versus server code

How to share your classes with other users


Exporting code modules

Introduction to Programming ArcObjects with VBA Programming with class 5-2


Class
‹ A blueprint for creating objects
‹ Defines the properties and methods of an object
‹ Some objects can be created new

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.

Introduction to Programming ArcObjects with VBA Programming with class 5-3


Classes and objects
Color: Red Color: Blue
Ferrari class Engine: V12 Engine: V12
Color Year: 1997 Year: 1998
Engine Convertible: False Convertible: True
Year
Convertible

Objects of the Ferrari class

Map class
Label
Extent
Layers
Scale
Projection

Objects of the Map class

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming 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.

Car analogy continued


To continue with the car analogy, the Ferrari factory (Class) will create new Ferraris (Objects)
that have identical designs (methods, properties, events). Each Ferrari object that is produced,
however, can have different values for its predefined properties. For example, one Ferrari
might have the value Blue for its Color property, while the next has the value Red for this same
property.
Although the Ferrari factory knows how to create new cars, you could not put a key in the
factory, start it up, and drive off. Likewise, you could not ask a Ferrari object to make a new
Ferrari.

An ArcObjects example
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.

Introduction to Programming ArcObjects with VBA Programming with class 5-4


Class libraries
‹ Libraries contain class definitions
‹ Stored in files (DLL, OLB, TLB, EXE, OCX)
‹ ArcObjects are stored in many class libraries

‹ Can reference additional libraries


‹ ArcMap/ArcCatalog references all the ArcObjects class
libraries

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 5-5

A class library is simply a collection of several classes that are contained 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.

Referencing a class library


As a programmer, you have the ability to control which class libraries you work with in a given
project. You can bring in additional libraries or remove existing ones from your Visual Basic
project by choosing References from the Tools menu on the Visual Basic Editor toolbar. The
References dialog (shown above) allows you to browse available class libraries, remove
libraries that are currently referenced, or check libraries to bring them into the project. By
referencing additional libraries, you give yourself access to more objects, and you may be
surprised by the number of class libraries available on your machine. If you have Internet
Explorer, Crystal Reports, or Visio, for example, you can reference and use the classes
available in those applications in your own application.
Note that when programming an application with VBA, you will always have a default set of
class libraries referenced. In ArcMap and ArcCatalog, for example, you will always have a
reference to the ArcObjects libraries, as well as the VBA and the Microsoft Forms library. All
classes defined in these libraries will be available in your project as soon as you start the
application. You only need to make a reference to a class library if you want to bring in classes
that are not defined in one of these default libraries.

Introduction to Programming ArcObjects with VBA Programming with class 5-5


ArcObjects Class Libraries
‹ ArcObjects contained in many class libraries
‹ Logically grouped based on functionality
‹ Geodatabase

‹ Geometry

‹ Cartography

‹ VBA references all class


libraries for you by default
‹ Developer Help contains
information on which
library an object belongs to

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 5-6

At ArcGIS 9.x, the ArcObjects have been placed into many different class 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.

Introduction to Programming ArcObjects with VBA Programming with class 5-6


Exploring class libraries with the Object Browser

Library
Library
list
list
Search
Search
string
string

Search
Search
matches
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

The Visual Basic Object Browser


The Visual Basic Editor comes with a utility for browsing the contents of class libraries called
the Object Browser (remember that object and class are often used interchangeably, so it would
be more accurate to call this a class browser). This utility can be very helpful for writing your
Visual Basic code. It provides a quick reference for which classes are available, as well as what
they can do for you. In later lessons, you will explore some other utilities that give you
information about classes, such as the ESRI Object Browser and the ArcObjects object model
diagrams.

Using the Object Browser


The Object Browser can be launched by pressing the button shown above or by choosing
‘Object Browser …’ from the View menu.
At the top of the Object Browser is a pulldown list for choosing a class library to search. You
will see all referenced class libraries listed here (including the current project and the
Normal.mxt file, which are also considered libraries). By default, the Object Browser will
search all referenced libraries.
Below the library list is a text box for typing a search keyword. After providing a keyword and
pressing enter (or clicking the search button to the right), the Object Browser will display all
matches for the string (whether it appears in a class name, property, method, etc.).
By selecting a match in the search results list or a class in the class list, a list of members will
be displayed in the Object Browser. Members are basically methods and properties but could
also include events. To get more information about a member, highlight it in the member list
and a description of its syntax (e.g., required arguments) will be displayed at the bottom of the
browser.

Introduction to Programming ArcObjects with VBA Programming with class 5-7


‘I’ is for interface
Many of the classes that you will see in the Object Browser begin with the letter ‘I’, which
stands for interface. Interfaces will be covered in great detail in a later lesson. For now, you
only need to know that interfaces are special classes that organize a set of properties and
methods. It is through an interface that a programmer communicates with an object. For
example, the IMap interface has methods such as AddLayer and DeleteLayer and properties
such as Extent and Scale. The Map class uses this interface, which gives programmers access
to these properties and methods.

Introduction to Programming ArcObjects with VBA Programming with class 5-8


Object Browser icons

Property
Method
Event
Module
Class

Others …

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 5-9

The Object Browser uses many different symbols to represent items found in a 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.

Introduction to Programming ArcObjects with VBA Programming with class 5-9


Creating objects at design time
‹ ArcMap: Customize dialog box
‹ VBA: UserForm Toolbox

Objects
Objects
Class
Class

Class
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.

Creating objects at design time


Whether you realized it or not, you have already created objects in this course. At design time
when you add a new UIControl to the ArcMap or ArcCatalog interface, you are creating a new
object. When you create a new user form or add new controls to a user form, you are also
creating new objects. These objects have been defined in one of the available class libraries,
and by placing them on the interface or on a form, you are producing an instance (or object)
from that class.

The example: classes and objects revisited


In the slide above, you can think of the Toolbox as a visual representation of a class library. It
contains all the possible controls you can place on a form. Each of the controls on the Toolbox
is like a class; they define the methods, properties, and events for each type of control.
If you click one of the controls in the Toolbox, does it do anything? Can you change the
properties of one of these controls? No—the controls in the Toolbox simply provide the
template for actual controls. Once you drag a control from the Toolbox to the form, however,
you have created an object (an instance of that particular class of control). Now, working with
the object, you can change its properties. You can resize it, change its name and its color, and
write code for its click event. If you add another control of the same type (class), it will have
the exact same set of methods, properties, and events, but you may choose to use them
differently.

Introduction to Programming ArcObjects with VBA Programming with class 5-10


Instantiating an object in code
1. Declare an object variable (As Class)
2. Use Set when assigning an object to a variable
‹ Use New to create

3. Use methods and properties

Dim myDog As Dog DOG


Set myDog = New Dog
myDog.Bark Bark Name
Growl Color

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.

Declaring an object variable


Working with objects in code is similar to working with intrinsic data values (such as numbers
and strings) in that the first step is to declare a variable. Object variables are declared the same
way as variables that store standard data types: by using the Dim, Static, Private, or Public
keyword and specifying an object type to store. Just as you would declare a variable as Integer,
String, or Date, you can declare a variable as CommandButton, Collection, or IPageLayout
(more about interfaces later). Once you have declared a variable as a particular type of object,
it will only be able to store that type of object.

Instantiating or creating an object variable


Setting an object variable equal to a new or existing object is called instantiating an object.
Making an object brand new is referred to as creating an object. As you will learn in more
detail later, not all classes allow you to create their objects new. Whenever you instantiate any
object variable (unlike intrinsic data variables), you must use the Set keyword. As with intrinsic
data variables, whatever is evaluated on the right side of the equal sign is stored in the object
variable. For classes that allow objects to be created new, use the Visual Basic New keyword.
Below are examples of instantiating an object variable with an existing object (a layer in the
map) and creating an object with the New keyword (a new Visual Basic Collection object).

Introduction to Programming ArcObjects with VBA Programming with class 5-11


'Existing instance of a layer
Dim pLayer As ILayer
Set pLayer = pDoc.SelectedLayer

'New instance of a collection


Dim myList As Collection
Set myList = New Collection

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.

Introduction to Programming ArcObjects with VBA Programming with class 5-12


To Set or not to Set?
'Using VB objects
Dim myButton As CommandButton
Set myButton = frmMain.cmdApply

'Using ArcGIS objects


Dim pMap As IMap
Set pMap = New Map

'Using variables of "intrinsic" data types


Dim x As Integer
x = 1234 ' Å------ No SET keyword

‹ p = pointer to an object variable


‹ Naming convention used for COM object variables

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 5-13

When to use Set


One of the most common pitfalls for new Visual Basic programmers is knowing when—and
when not—to use the Set keyword with variables. The answer is really quite simple, although it
may take a little practice before it sticks. You must use Set when you are instantiating an object
variable of any kind. You must not use Set when you are assigning a value to a variable of a
standard data type (strings, numbers, dates, etc.).

Can you write it down?


A quick way to remember the rule for using Set is to keep in mind that anything you can write
down on a piece of paper is an intrinsic (standard) data type. Anything you cannot write down
on a piece of paper (drawing pictures does not count) will require the use of the Set keyword.
Variable Type Write It? Use Set?
datBirthday Date 2/28/67 No
intAge Integer 33 No
blnMarried Boolean False No
strName String Wendy No
pMap Object ? Yes
Set pMap = New Map
Variable naming conventions continued
There is one more convention to add to your list of naming standards. In much of the code you
encounter (and a lot of it in this course), you will notice that object variables are named with a
preceding lowercase ‘p’. This stands for pointer, as object variables do not really contain the
object (the way an integer variable contains an integer); instead, they simply point to the
referenced object.

Introduction to Programming ArcObjects with VBA Programming with class 5-13


Coding a class with Visual Basic
‹ Class module
‹ Define methods
‹ Define properties

‹ Use the class


‹ Set properties
‹ Get properties
‹ Call methods

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 5-14

Class module: Methods


The general procedures of the Dog class module define the class’s methods. In the example, the
Bark procedure contains code that will run when any Dog instance calls its Bark method.

Class module: Properties


A class module also contains property procedures that can store and return values. For
example, the Get and Let property procedures below set up storage and retrieval for Dog’s
Name property.
'This is server code.
Private m_pDogName as string
Public Property Get Name() As String
Name = m_pDogName
End Property
Public Property Let Name(ByVal vNewName As String)
m_pDogName = vNewName
End Property
Instantiate a dog and set its Name property:
'This is client code.
Dim pDog as Dog
Set pDog = New Dog
pDog.Name = "Rex"

Introduction to Programming ArcObjects with VBA Programming with class 5-14


Client and server environment
‹ Classes are server code
‹ Class modules, class libraries (e.g., ArcObjects)

‹ Client code uses these predefined classes

Server
Server 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

Client and server relationships


In COM there is a relationship between client code and server classes. The server provides
functionality that a client uses. COM facilitates the communication between components.
In a COM system, the client, or user of functionality, is completely isolated from the server, or
provider of that functionality. All the client needs to know is that the functionality is available.
With that knowledge, the client can make calls to the server and expect the server to honor
them. In this way COM acts as a contract between client and server. If the server breaks that
contract, the system may not respond as expected. In this way COM development is based on
trust between the implementer and the user of functionality. A developer using ArcObjects can
assume all these properties and methods have been fully implemented and are there to use if
they are present on the object diagrams.

Server storage: EXEs and DLLs


The client and its servers can exist in the same process or in a different process space. In
process servers are packaged in DLL form and loaded into the client’s address space when the
client first accesses the server. Out of process servers are packaged in EXEs and run in their
own address spaces. There are diametrically opposed pros and cons to each packaging method.
DLLs load into memory faster, and DLL functions are faster to call. Executables, on the other
hand, provide a more robust solution (if the server fails, the client will not crash) and better
security because the server has its own security context. In a distributed system, EXEs are more
flexible, and it does not matter if the sever has a different byte ordering to the client.

Introduction to Programming ArcObjects with VBA Programming with class 5-15


Distributing your classes
‹ Save the class in a map or template
‹ Save the class module in its own file
‹ Export to create a CLS file
‹ Others can load CLS file into their project

‹ Create a DLL, OCX, or EXE file


‹ Cannot do this with VBA
‹ Use Visual Basic 6, C++, or similar program

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 5-16

Export a class file


You can share your class with others by exporting your class (CLS) file. Anyone with Visual
Basic can import the file. If your file is dependent on any libraries, anyone importing the class
file will also need those libraries.

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.

Introduction to Programming ArcObjects with VBA Programming with class 5-16


Demonstration: Creating a simple class
‹ Create a class module to define a Dog
‹ Define some simple properties (public variables)
‹ Define a Bark method (function)
‹ Define a RespondToCall method (sub)
‹ Use the class in a form’s code

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 5-17

Instructor demonstration
Your instructor will now demonstrate how to create your own class using Visual Basic for
Applications.

Introduction to Programming ArcObjects with VBA Programming with class 5-17


Exercise 5 overview
‹ Write client side code to create NEW Country object
‹ Set properties and call methods
‹ Instantiate NEW City object

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 5-18

Exercise 5: Create your own class


In this exercise, you will:
Create a new class module.
Write code to represent a country object.
Use a country object in some client code.

Introduction to Programming ArcObjects with VBA Programming with class 5-18


COM before the
Introduction to Programming ArcObjects with VBA

storm
Lesson overview 6-2
Introducing COM
COM classes have interfaces
Working with ArcObjects
contents
6-3
6-4

COM classes 6-5


More on interfaces … 6-6
Polymorphism 6-7
ArcObjects polymorphism 6-8
Using methods and properties 6-9
Getting other interfaces 6-10
Testing an object reference 6-12
COM class code 6-14
Using library names 6-16
Using the ESRI Object Browser 6-17
Demonstration: Creating a
COM class 6-18
Exercise 6 overview 6-19
COM before
the storm

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA

Introduction to Programming ArcObjects with VBA COM before the storm 6-1
Lesson overview
‹ COM: Component Object Model
‹ Working with COM classes
‹ Interfaces

‹ Polymorphism

‹ QueryInterface

‹ Testing an object reference


‹ Is it nothing?
‹ What type of object is it?

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 6-2

Components
For GIS, an object-oriented approach is more flexible compared to the object approach (e.g.,
ArcView GIS 3.x) because it adds a framework for anyone to extend the data model, and end
users or third party developers are not 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

‹ All ArcObjects are COM classes


‹ Technologies based on COM
‹ Object Linking and Embedding (OLE)
‹ OLE DB
‹ ActiveX is any technology built on COM
‹ DCOM and COM+

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 6-3

COM is a standard that specifies how classes should be programmed, not a 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

‹ p = pointer to an object variable


‹ Naming convention used for COM object variables

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 6-5

Interface programming
When programming with ArcObjects, you are programming with objects. More importantly,
however, you are communicating with the objects 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

Dim pBBox As ITape


Set pBBox = New BoomBox
pBBox.FM = True

IRadio
ITape
ICD

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 6-6

The Boom Box analogy


An ArcObject that you work with in your code can be compared to a boom box like the one
shown above. Although it is a single entity (a particular Map, FeatureLayer, Symbol, etc.), the
characteristics of the object, as well as the things it’s able to do, are organized on different
interfaces. In order to get to the desired characteristics or functionality, you need to make sure
you have tapped into the correct interface.
If, for example, you wanted to hear the radio, you would have to make sure the switch on the
boom box was set to the Radio setting. Does this mean that you cannot play a tape? No … you
would simply need to change interfaces and move the switch to the proper setting (Tape).
Many of the ArcObjects you program with will have functionality that is spread among several
interfaces. Just remember that the key to accessing an object’s functionality is using variables
that point to the appropriate interface.

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

As an ArcGIS programmer, you will encounter several examples of polymorphism in


ArcObjects. Remember that the advantage of polymorphism is that several classes can use the
same interface (with the exact same methods and properties available), but each class can
implement methods and properties differently. This can be convenient for a programmer.

ILayer
All layers that can be brought into ArcMap 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

‹ Only use methods and properties for the declared


interface
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 6-9

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

'**pDrive and pRace point to the same object**

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

‹ What TypeOf object is it?


If TypeOf pLayer Is IFeatureLayer Then
MsgBox "You selected a Feature Layer. "
Else
MsgBox "This layer is not a Feature Layer."
End If

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 6-12

As an ArcObjects programmer, you will often find it necessary to test the object variables you
are using. The most common tools for testing an object reference are to see if it is Nothing or to
see what TypeOf object it is.

Nothing
If an 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

COM classes under the hood


The class (Country) that you used in the last exercise consisted of a single class module that
defined methods and properties. ArcObjects COM classes are also written class modules, but
are organized quite differently. To rewrite your Country class as a COM class, you would need
to also write at least one interface for the class to implement (ICountry, for example).
Interfaces are also written in a class module and are nothing more than definitions for methods
and properties a class should implement.

Interfaces
To create an 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

'Create a new point and line from the esriGeometry library


Dim pPoint As esriGeometry.IPoint
Dim pLine As esriGeometry.ILine
Set pPoint = New esriGeometry.Point
Set pLine = New esriGeometry.Line

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 6-16

To be more specific with the objects and interfaces you are using in your code, you may choose
to preface class and interface names with the name of the library from which they are coming.
This is particularly important if there are 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

The ESRI Object Browser


The ESRI Object Browser is a utility for browsing object libraries. The browser displays details
of the coclasses, interfaces, properties, methods, enumerations, and structures contained in one
or more object library. You can load type library information contained in TLB, OLB, DLL,
OCX and EXE files. You can browse all of the objects contained in the loaded object libraries,
or you can use a search string and search criteria to find specific objects. For example, you can
perform a search to find all the coclasses that use a particular interface.

To run the ESRI Object Browser


1) Click Start Button > Programs > ArcGIS > Developer Tools > Object Browser.
2) File > Object Library References.
3) Click on Add.
4) Select the second radio button that states – Select from registry.
5) Reference the class library you would like to browse.
6) Click on Ok.

See the ArcGIS Developer Help for further details.

Introduction to Programming ArcObjects with VBA COM before the storm 6-17
Demonstration: Creating a COM class
‹ Design an interface
‹ Create a class that uses (implements) the interface
‹ Work 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

Exercise 6: Work with COM objects


In this exercise you will create COM classes with interfaces, instantiate your classes, and use
QueryInterface to get other interfaces on an existing object.
First, you will design an interface for use on a Country class. You will define a logical set of
methods and properties on the interface. Next, you will rewrite the Country class you made in
the last exercise as a COM class that implements your interface.
Finally, you will use the Country COM class in some client code.

Introduction to Programming ArcObjects with VBA COM before the storm 6-19
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 6-20

Introduction to Programming ArcObjects with VBA COM before the storm 6-20
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

Object model diagrams


The ArcGIS Developer’s Help includes several object model diagrams that describe how the
ArcObject libraries are put together. As a programmer, these diagrams are invaluable tools that
help you plan how to write your code. Specifically, they indicate how to work with certain
classes (can objects be created brand new or must they be obtained from an existing object, for
example), and how each class is related to others (a Map is composed of several Layers, for
example).
This lesson will introduce you to the ArcObject object model diagrams. You will learn the
symbology used to describe ArcObject classes and class relationships. Code examples based on
the diagrams will illustrate the importance of understanding these diagrams in order to work
with the ArcObjects.

Introduction to Programming ArcObjects with VBA Understanding object model diagrams 7-2
ArcObject object model diagrams
‹ OMDs help you write code
‹ Show interfaces, methods, and properties for each class
‹ Show relationships between classes

‹ Over 2,700 classes on several diagrams


‹ Over 3,000 interfaces

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 7-3

Conceptually, there is only one ArcObject object model. All of the ArcObject 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

Object model diagram symbology


In many ways, an object model diagram is like a map. Symbols are used to represent different types of
features (i.e., classes) found on the diagram, as well as to show how the classes are related. Just like
reading a map, in order to understand an object model diagram, you need to consult the legend. Each
diagram has a legend that indicates which types of classes and relationships the symbols in the diagram
represent. Below is a short description of the most common symbols found on the object model
diagrams.
•U Inheritance—In the example above, a chicken Is a type of bird. This is a superclass–subclass
relationship. As a programmer, this relationship is important because it indicates that anything a Bird can
do, the Chicken can do. In other words, all methods and properties defined for a superclass will be
available for each of its subtypes.
•¡ Composition—The chicken diagrammed above Is composed of exactly two wings and several
feathers. If the chicken is destroyed, these other objects are also destroyed. If there is an exact cardinality
in the relationship the number will be listed on the diagram, a one-to-one relationship is described with a
simple line, while an indefinite multiplicity relationship (0 to infinity) is described with the asterisk (*).
•---X Creation—The arrow in the diagram above indicates that a Chicken object can be used to create an
Egg object. This can be an important relationship for a programmer, because some objects can only be
created from other objects.
•* Multiplicity—An asterisk is used to indicate potential multiplicity in a relationship. The Chicken class
above, for example, is composed of several Feather objects. The asterisk indicates that there could be
anywhere from 0 to an infinite number of Feathers on a Chicken. Some relationships have a range of
possible values, in which case the range will be indicated like this: 0 .. 3.
•— Association—A plain line connecting two classes indicates a simple relationship. In this kind of
relationship, each object could exist individually. In the example above a Chicken is associated with a
Nest, but if the Chicken was deleted, the Nest would still exist. Contrast this relationship with the
composition relationship, in which case the lifetime of an object is controlled by the object to which it is
related.

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

‹ Instantiable: Obtain from other objects


Dim pMap As IMap
Set pMap = pMxDocument.FocusMap

‹ OMD symbol: Shaded 3D rectangle

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 7-6

CoClass
CoClasses are the only type of class from which instances can be created with the New
keyword. Logically, it makes sense that many objects you work with should be created only
from other objects (Classes), while others should be 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

‹ OMD Symbol: 3D Rectangle with no shade


Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 7-7

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

‹ OMD symbol: 2D shaded rectangle

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

Dim pFC As IFeatureClass

Set pFC = pSomeObj.FeatureClass


'No need to QI to IObjectClass
MsgBox pFC.AliasName

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 7-9

There are two ways interfaces can be inherited to other objects:

Type of 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

Symbols for properties, methods, and events


Although the object model diagrams show all the interfaces that each class supports, they do not
show the methods and properties for every interface (there simply is not enough room). They
do, however, show a complete listing of methods, properties, and events for some of the more
common interfaces on each class.
• Property: Properties are illustrated on the object model diagrams with a box symbol. For
each property on the diagram, a programmer may have the ability to assign (write) a value
to the property, or to get (read) the property’s current value. A box on the right means a
programmer can set the property, a box on the left means he or she can get the property.
Therefore, a programmer can use an object model diagram to determine whether some of
the more common properties are read-only, write-only, or neither.
• Method: Methods are symbolized on the diagrams with a solid (black) arrow. In addition to
the name of the method, any required arguments from the method, return values from the
method, or both will be specified as part of the diagram listing.

Introduction to Programming ArcObjects with VBA Understanding object model diagrams 7-10
Getting properties
‹ Return a value
‹ Name: String

‹ Return an object reference


‹ Document: IDocument
‹ StatusBar: IStatusBar
Dim strName As String
strName = Application.Name 'Value
MsgBox strName

Dim pDoc As IDocument


Set pDoc = Application.Document 'Object
MsgBox pDoc.Title

Dim pBar As IStatusBar


Set pBar = Application.StatusBar 'Object
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 7-11

Getting property values


In addition to indicating whether a property can be read or written, the object model diagrams
also list the type of value or object used for each property. Reading the property listing from left
to right, you will first find the barbell symbol for the property, followed by the name of the
property, and finally (on the right of the colon), the value to expect when getting the property
value (or the type of value to use when setting it). It is important to know what type of value to
expect from a property so you can declare your variables appropriately. If you do not declare
your variable as the proper return type, you may receive a type mismatch error.
If an interface name is listed as the return value, the property returns a reference to the object
through this interface. However, any other interface the object supports can be used when
retrieving the property, if desired.
In the example above, three variables are declared: one as a string, one as a pointer to the
IDocument interface, and another to the IStatusBar interface. These are the documented return
types for the Name, Document, and StatusBar properties.

Introduction to Programming ArcObjects with VBA Understanding object model diagrams 7-11
Setting properties
‹ Property Put: Most ArcObjects properties
‹ Property holds a value or a copy of an object
‹ Do not use Set keyword

pLayer.Name = "Port Moresby" 'No Set keyword

‹ Property Put by Reference: Some ArcObjects properties


‹ Property holds a reference to an object
‹ Must use the Set keyword

Set pLayer.FeatureClass = pMoresbyData 'Must use Set!

‹ If the referenced object changes, property is affected (dynamic)

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming 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

‹ Start using printed ArcObject OMDs

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 7-15

Exercise 7A
In this exercise, you will begin by working with a fictitious object model diagram. You will
interpret this (Country) diagram to answer questions 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

Object model diagrams


The ArcGIS Developer Help includes several object model diagrams that describe how the
ArcObject libraries are put together. As a programmer, these diagrams are invaluable tools that
help you plan how to write your code. Specifically, they indicate how to work with certain
classes (can objects be created brand new or must they be obtained from an existing object, for
example), and how each class is related to others (a Map is composed of several Layers, for
example).
This lesson will introduce you to the ArcObject object model diagrams. You will learn the
symbology used to describe ArcObject classes and class relationships. Code examples based on
the diagrams will illustrate the importance of understanding these diagrams in order to work
with the ArcObjects.

Introduction to Programming ArcObjects with VBA Understanding object model diagrams 7-16
Finding object model diagrams
‹ Large paper diagrams are included with this course
‹ Start > Programs > ArcGIS > 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

Finding ArcObject object model diagrams


You will find several (over 50) object model diagrams (OMDs) in the ArcGIS Developer Kit.
The diagrams are organized according to logical groups of objects, such as Map Layers, Output
(printing and exporting), IMS, and Labeling and Annotation, to name a few. Diagrams are
available in Adobe Acrobat (PDF) format in the ArcGIS installation directory C:\Program
Files\ArcGIS\DeveloperKit\Diagrams). Within this directory, you will see two subdirectories of
Object Model Diagrams (Desktop and Engine). The Engine folder contains all OMDs that
compose the ArcGIS Engine Runtime, which is needed for products of the ArcGIS Engine
Developer Kit product. The Desktop folder contains all OMDs specific to working with ArcGIS
Desktop. You will be using OMDs from both of these directories.
To download the (free) Adobe Acrobat viewer, visit the Adobe Web site at:
http://www.adobe.com/products/acrobat/readstep.html

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).

Other useful information in the ArcGIS Developer Help


The ArcGIS Developer Help also provides a vast resource to find out information about all the
classes, interfaces, properties and methods that ArcObjects is composed of. You will also find
Developer Guides and Samples here as well.

Introduction to Programming ArcObjects with VBA Understanding object model diagrams 7-17
Finding the right OMD: Step 1
‹ Use Index/Search tabs to find any Class or Interface

Type in Class
or Interface
name

Name of
OMD/library:
Click on this
link for Step 2

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 7-18

The Index tab


The Index tab is an excellent resource for an ArcObjects Developer. The Index tab provides an
Alphabetical listing of virtually all the contents contained within the ArcGIS Developer Help.
This listing also includes all classes, interfaces, properties and methods. In the example above,
the MxDocument CoClass was found using the Index tab. The help panel provides a
comprehensive overview of what the class is used for, as well as all the interfaces MxDocument
implements.
If you would like to find the Object Model Diagram a particular class is contained on, the next
few slides will step you through, using MxDocument as an example. The next step is to click
on the name of the Library, which in this example is esriArcMapUI.
As a developer, you will find the help as being a great resource for finding more information
about the classes you want to work with. The help however, does not show the explicit
relationships between classes as the Object Model Diagrams do.

Introduction to Programming ArcObjects with VBA Understanding object model diagrams 7-18
Finding the right OMD: Step 2
‹ Library will show all interfaces available for all classes

Click Contents
tab for Step 3

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 7-19

Libraries
Remember, all ArcObjects classes (and their interfaces, properties, 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

Open OMD for


Step 4

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 7-20

The Contents Tab


The Contents Tab will list everything in the ArcGIS Developer Help in logical groupings. This
slide portrays the Library Reference contents. This gives a listing of all the libraries that store
all the ArcObjects that compose ArcGIS Desktop. Expanding any library (esriArcMapUI on this
slide) will give you: an overview of the library; the contents of the library (as seen on the help
panel on this slide; and the Object Model Diagram(s) for that particular library.
Clicking on the Library Object Model Diagram will allow you to open the Object Model
Diagram(s) for that particular library in .pdf format.

Introduction to Programming ArcObjects with VBA Understanding object model diagrams 7-20
Finding the right OMD: Step 4
‹ Open the OMD in Adobe Acrobat Reader
MxDocument Name of
Class from Step 1 OMD/Library

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 7-21

Using Adobe Acrobat Reader


Once you have opened the OMD in Adobe, you will see the name on the diagram, as
ArcMapUI Object Model is highlights on this slide. Some libraries contain many ArcObjects
and are composed of multiple Object Model Diagrams. The MxDocument class, which the
original search was for in Step 1, is highlighted in red. Once you have found the appropriate
Object Model Diagram, you can easily find the relationships to other classes.

Introduction to Programming ArcObjects with VBA Understanding object model diagrams 7-21
Where to begin? Getting into the OMD
‹ Special preset variables
‹ Application: IApplication interface of the Application object
‹ ThisDocument: IDocument interface of the MxDocument object

‹ Your entry point to ArcMap or ArcCatalog


ArcMap OMD

Application
ArcMapUI OMD

ThisDocument

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 7-22

You have to start somewhere


In Visual Basic for Applications, you will generally have preset global variables that allow you
to easily access the current application or document. You will find that it is fairly standard for
applications that use the VBA development environment to use a preset variable called
Application. As the name of this variable implies, it points to the current application in which
you are programming. When programming in ArcMap, for example, Application will point to
ArcMap. In ArcCatalog, it will point to ArcCatalog. In Microsoft Word, it will point to … you
guessed it, Word. In any of the above applications, a programmer could also use a preset
variable called ThisDocument that points to the document that is currently being customized.
Although you have already programmed with these preset variables, you probably did not
realize that they point to a specific interface on the objects they represent. The Application
preset variable points to the IApplication interface, while the ThisDocument variable points to
the IDocument interface. It will be common in your code to use QueryInterface (QI) on these
variables to access other interfaces supported by the Application or MxDocument objects.

Introduction to Programming ArcObjects with VBA Understanding object model diagrams 7-22
Example: MxDocument > Map > layer
‹ Get the FocusMap (active data frame) from MxDocument
‹ MxDocument may have several Maps ( * )
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)

'Is pLayer a FeatureLayer?


If TypeOf pLayer Is IFeatureLayer Then
FeatureLayer
MsgBox "Yes!, it’s a feature layer"
End If
Others

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 7-23

OMD code example: Maps and layers


In the example above, the object model diagram can be used as a guide for writing code.
Your starting point for writing code in ArcMap is generally the ThisDocument preset variable.
By consulting the ArcMapUI object model diagram, you would find that the IMxDocument
interface on MxDocument (rather than the default IDocument interface to which ThisDocument
points) has properties for accessing Maps (data frames).
Because of the composed of relationship () shown in the diagram, and the multiplicity (*), you
know that an MxDocument could potentially have several associated Maps. To insure that you
get the Map that your user is currently working in, you use the FocusMap property.
Looking at the diagram again, you notice that a Map is composed of () potentially several (*)
Layers. From the Map, you can retrieve a Layer at a given index position (you are accessing the
2nd Layer in the code above).
Finally, because Layer is an abstract class that has several subtypes (U), you would want to test
to see what kind of Layer you have. The TypeOf statement can be used to see if a particular
object supports a given interface.

Introduction to Programming ArcObjects with VBA Understanding object model diagrams 7-23
Exercise 7B overview
‹ Interpret the ArcObject object model diagrams
‹ Write your first code accessing ArcObjects
‹ Write code to change the ArcMap 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

Lesson overview 8-2


Loop review
Object model overview
Accessing maps
contents
8-3
8-4
8-5
Looping through a collection
of maps 8-6
Managing flow in a loop 8-7
Accessing layers 8-8
Working with a map’s layers 8-9
Looping through layers 8-10
Working with layer properties 8-11
Adding a new layer to a map 8-12
Setting a FeatureLayer’s
data source 8-13
Exercise 8 overview 8-14
Maps and layers

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA

Introduction to Programming ArcObjects with VBA Maps and layers 8-1


Lesson overview
‹ Looping Review
‹ Accessing maps and layers
‹ Looping through maps and layers
‹ Collections

‹ Enumerations

‹ Working with layer properties


‹ Creating new layers
‹ Setting a layer’s data source

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 8-2

Maps and layers


In this lesson, you will learn the basics of working with maps and layers in an ArcMap
document. Because an ArcMap document can contain several maps (i.e., Data Frames), you
may need to loop through the entire map collection. A Map, in turn, is composed of several
map layers. You will also learn methods for looping through a set of map layers.
Accessing a document’s Maps
Focused map
Map collection
Layers
Accessing layers
Creating a new layer
Layer properties
Specifying a data source for a layer
Looping
Collections: For Next loop
Enumerations: Do While/Do Until loops

Introduction to Programming ArcObjects with VBA Maps and layers 8-2


Loop review
‹ Loop a specified number of times
‹ For Next

‹ Loop based on condition


‹ Do While
‹ Do Until

‹ Beware of endless loops


'Here is an Endless Loop
Do While Not MsgBox("Add a Record?") = vbYes
'Code here to add a record to a table
MsgBox "Record Added"
Loop

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 8-3

When it is known how many times a loop must iterate, For Next is most often used. For Next
loops use an index variable (usually an integer) to control the 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).

Introduction to Programming ArcObjects with VBA Maps and layers 8-3


Object model overview

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.

Introduction to Programming ArcObjects with VBA Maps and layers 8-4


Accessing maps
‹ Access maps from MxDocument
‹ Get the active map
Dim pMxDoc As IMxDocument
Set pMxDoc = ThisDocument
Dim pMap As IMap
Set pMap = pMxDoc.FocusMap

‹ Get all maps (IMaps)


‹A collection of Maps
Dim pAllMaps As IMaps
Set pAllMaps = pMxDoc.Maps

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 8-5

Accessing maps in the document


Remember that what are called Data Frames by someone using the ArcMap interface are
called Maps by an ArcObjects programmer. An ArcMap document (MxDocument) is
composed of (potentially) several Maps. Each map in a document can have a different set of
layers, a different extent, and even a different spatial reference.
Maps can be accessed from the document or MxDocument object. All the properties used to
access Maps are on the IMxDocument interface, so it is necessary to first QueryInterface to
this interface (see the first two lines in the example above).
Depending on the purpose of your code, you might want to get a particular map (the first one,
for example), or the focused map (i.e., the active data frame), or you might want to access and
work with all maps in the document. To get all maps, use the Maps property, which will
return a collection object (IMaps interface) that contains all the document’s maps. Once you
have accessed the map collection, you can retrieve a particular map according to its index
position (counting from top to bottom, starting at 0). The focused map can be referenced by
using the FocusMap property on the IMxDocument interface.

Introduction to Programming ArcObjects with VBA Maps and layers 8-5


Looping through a collection of maps
‹ Collections are ordered
00
‹ Reference items by position (index)
‹ First item is at position 0 11
'' Syntax
Syntax Example
Example
For
For <index
<index == start>
start> To
To <end>
<end>
'' process
process each item ……
each item
Next
Next <index>
<index>
' Map collection example …
Dim intIndex As Integer
Dim pMaps As IMaps 22
Set pMaps = pMxDoc.Maps

For intIndex = 0 To pMaps.Count - 1


MsgBox pMaps.Item(intIndex).Name
Next intIndex

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 8-6

For Next loops


To loop through any kind of collection, you will use a For Next looping structure. For Next
loops are used whenever you know how many times the loop should execute. This type of
loop requires the use of an index variable to control loop iterations. This variable is generally
an integer, although it does not have to be. The syntax for a For Next loop is
For index = startNumber To endNumber
Next index
Once the endNumber has been reached, the loop finishes execution. By default, the index
variable is incremented by 1 after each iteration. Optionally, however, you can specify a step
value to change the increment value. The example below will increment by a value of 2 after
each iteration of the loop.
For index = startNumber To endNumber Step 2

Looping on a map collection


Because the maps collection has a Count property, you can use this to dictate how many times
a loop should execute in order to access each map. Remember that the collection of maps is
zero-based (the first item is at position 0); therefore, a loop on the collection should execute
Count–1 times or an error will occur.

Introduction to Programming ArcObjects with VBA Maps and layers 8-6


Managing flow in a loop
‹ Exit a loop prematurely when a condition is true
‹ For Next loops: Exit For
‹ Do While and Do Until loops: Exit Do

Dim pCityMap As IMap


Dim X As Integer
For X = 0 To pMaps.Count - 1
If pMaps.Item(X).Name = "Cities" Then
Set pCityMap = pMaps.Item(X)
Exit For
End If
Next X

MsgBox "All Done", vbInformation

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 8-7

Ending a loop
Most loops terminate when a condition is no longer true, when a 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

Introduction to Programming ArcObjects with VBA Maps and layers 8-7


Accessing layers
‹ Access layers from Map or MxDocument
‹ Get the selected layer (IMxDocument)
Dim pLayer As ILayer
Set pLayer = pMxDoc.SelectedLayer
‹ Get a specific layer (IMap)
Dim pLayer As ILayer
Set pMap = pMxDoc.FocusMap
Set pLayer = pMap.Layer(3)

‹ Get all layers (IMap)


‹ An enumeration of layers
Dim pAllLayers As IEnumLayer
Set pAllLayers = pMap.Layers

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 8-8

Accessing layers from a map


A Map is basically a collection of layers, and once you have referenced a particular map, you
will find properties (on the IMap interface) for referencing the layers it contains. As with
accessing a map from the document, it is possible to either access a particular layer or retrieve
all layers in a map. Unlike the Maps property, however, which returns a collection of maps,
the Layers property (on IMap) returns an object known as an enumeration (or enum).
An individual layer can also be obtained directly from the MxDocument (IMxDocument
interface) by using the SelectedLayer property. Getting the SelectedLayer will return
whichever layer is highlighted in the ArcMap Table of Contents (similar to the idea of an
active theme in ArcView GIS 3.x).

Enumerations (Enums)
An enumeration, usually called an enum for short, is a package of objects 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).

Introduction to Programming ArcObjects with VBA Maps and layers 8-8


Working with a map’s layers
‹ IMap’s Layers property returns IEnumLayers
‹ Like a collection with fewer methods and properties
‹ Next returns ILayer
‹ Reset moves to top of Enum
Dim pLayer As ILayer
Dim pLayers As IEnumLayer
Set pLayers = pMap.Layers IEnumLayer
Top
Set pLayer = pLayers.Next

Set pLayer = pLayers.Next


pLayers.Reset
Set pLayer = pLayers.Next

Set pLayer = pLayers.Next


Nothing

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 8-9

Working with an enumeration of layers


An enum is like a collection in that it stores a group of items in a single object. It is much
different in how you work with it, however. When an enumeration is first initialized, a pointer
(which is managed by the enum) is pointing above the first item in the enum. As items are
taken out of the enum, this pointer is updated to point to each successive position in the enum.
You will find that all enumeration objects have basically the same methods for working with
items stored within. Although there are several enumeration interfaces, each named for the
type of object they contain (e.g., IEnumLayer, IEnumGxObject, IEnumElement), they
generally all have the same two methods (and no properties).
The Next method returns the next item in the enum, then moves the pointer to the next item.
Each time Next is called, this pointer is automatically moved down in the enum.
The Reset method returns the pointer above the first item in the enum.

Plates analogy
Working with any enum is like taking 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.

Introduction to Programming ArcObjects with VBA Maps and layers 8-9


Looping through layers
‹ Do While or Do Until
‹ Loop based on a Condition (Boolean)
'' Syntax
Syntax Example
Example
Do
Do Until/While
Until/While <a
<a condition
condition is
is true>
true>
'Run
'Run this
this code
code
Loop
Loop
' Layer enum example
Dim pLayer As ILayer
Dim pMapLayers As IEnumLayer
Set pMapLayers = pMap.Layers

Set pLayer = pMapLayers.Next


Do Until pLayer Is Nothing
MsgBox pLayer.Name Nothing
! Set pLayer = pMapLayers.Next
Loop

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 8-10

Looping based on a condition


Looping based on a condition is probably the most common and useful method of looping.
There are two methods that allow for looping based on a condition and two variations of each.
Do While Loops execute while the condition in the logical expression evaluates to true. Do
While Loops check the logical expression at the top of the loop and, if the initial condition is
false, may never loop at all.
Under special circumstances, the developer may want to force at least one evaluation of the
loop, in which case the expression can be placed at the bottom in a Do Loop While. Do Until
Loops or Do Loop Until work identically to the While loops, except execution terminates
when a condition becomes true.

Looping through map layers


Conditional loops are used for looping through layers because there is no way to (easily) get a
count from an enum object (IEnumLayer), which is required for the For Next loops described
earlier. It is much more efficient to write a loop such as the one shown above. This loop pulls
layers out of the enum one at a time and stores them in a variable (pLayer). The item pulled
from the enum is evaluated, and when it becomes Nothing (i.e., the bottom of the enum is
reached), the loop terminates.

Introduction to Programming ArcObjects with VBA Maps and layers 8-10


Working with layer properties
‹ All layers inherit interfaces defined on the Layer class
‹ Properties on ILayer
‹ Name, Visible, ShowTips, MaximumScale, MinimumScale, etc.

‹ Properties on IGeoDataset
‹ Extent, SpatialReference
'This code will work for ANY type of layer
'Access the document’s selected layer
Dim pLayer As ILayer
Set pLayer = pMxDoc.SelectedLayer
'Set basic layer 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

Basic Layer properties


The layer properties that are available in the Layer Properties dialog from the ArcMap
interface are the same ones you will find available as a programmer. Because all Layers in
ArcMap inherit from the generic Layer abstract class, they can all use the ILayer and
IGeoDataset interfaces. These interfaces allow access to basic layer properties such as Name,
MaximumScale, MinimumScale, Visible, Extent, and SpatialReference.

Feature Layer properties


One of the most common layer types you will work with is the feature layer. Feature layers
are layers based on vector data (such as shapefiles, coverages, and geodatabase data). Feature
layers have properties such as FeatureRenderer, which controls how the layer is displayed
(symbols, colors, classification, etc.), FeatureClass, which accesses or sets the dataset
displayed by the layer, and DefinitionExpression, which can be used to restrict the features
shown in the layer by using attribute criteria.

Introduction to Programming ArcObjects with VBA Maps and layers 8-11


Adding a new layer to a map
‹ Layer is an abstract class: Not creatable
‹ Creatable subclasses: TinLayer, FeatureLayer, RasterLayer, etc.
'Make a New FeatureLayer
Dim pFLayer As ILayer
Set pFLayer = New FeatureLayer

'Add a layer to MxDocument or Map


Dim pMxDoc As IMxDocument
Dim pMap As IMap
Set pMxDoc = ThisDocument
Set pMap = pMxDoc.FocusMap

pMap.AddLayer pFLayer

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 8-12

Layer is an abstract class that has several creatable subtypes. As a programmer, you can
create several kinds of layers brand-new by using the New keyword. 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.

Introduction to Programming ArcObjects with VBA Maps and layers 8-12


Setting a FeatureLayer’s data source
‹ FeatureClass property (IFeatureLayer)
‹ Specifies the data source to display
‹ Set by reference (must use the Set keyword)

‹ More about accessing data in the next lesson


'Make a new FeatureLayer
Dim pFLayer As IFeatureLayer
Set pFLayer = New FeatureLayer

'Get another layer’s FeatureClass


Dim pFClass As IFeatureClass
Set pFClass = pSomeOtherLayer.FeatureClass

'Set the new layer’s FeatureClass property


Set pFLayer.FeatureClass = pFClass

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 8-13

Working with a FeatureLayer’s FeatureClass property


Feature layers are based on a type of dataset known as a FeatureClass. FeatureClasses are
datasets that have a single feature type (point, line, polygon), a common set of attributes, and
a common spatial reference. FeatureClasses are basically just a collection of features and their
associated attributes. Examples of FeatureClasses are Shapefiles, Coverages, and
Geodatabase datasets.
To access a FeatureLayer’s dataset, use the FeatureClass property on IFeatureLayer. This is a
read–write property, so in addition to simply getting a FeatureLayer’s data source, you can
also set it. FeatureClass is a property put by reference, which means you must use the Set
keyword when setting this property (see the example above).

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

Set pFLayer.FeatureClass = pSomeOtherLayer.FeatureClass

Introduction to Programming ArcObjects with VBA Maps and layers 8-13


Exercise 8 overview
‹ Loop
‹ Maps in a document
‹ Layers in a map

‹ Optional steps (choose one: 3, 4, or 5)


‹ Fields in a layer table
‹ Determining object reference
‹ Add a layer to a map
Š Set basic properties
Š Set the data source

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 8-14

In this exercise, you will write code to manage maps in the current document, layers in the
maps, and fields in each attribute table. You will also write code that adds a layer to the map.

Introduction to Programming ArcObjects with VBA Maps and layers 8-14


Programming ArcInfo with Visual Basic for Applications

Data access and


ModuleTitle

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

Getting a FeatureDataset 9-8


Getting FeatureClasses 9-9
Pseudocode: Adding a data layer 9-10
GxDialog 9-11
Example: GxDialog 9-12
Exercise 9A overview 9-13
Working with Name objects 9-14
Creating a new Workspace 9-15
Creating a new Table or
FeatureClass 9-17
Field and Fields classes 9-18
IField and IFieldEdit 9-19
Creating a Fields collection 9-20
Creating a Table or FeatureClass 9-21
Data access and
creation

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA

Introduction to Programming ArcObjects with VBA Data creation 9-1


Lesson overview
‹ Data creation objects
‹ Workspace Workspace
Workspace FeatureDataset
FeatureDataset
‹ FeatureDataset
FeatureClasses
FeatureClasses
‹ FeatureClass

‹ Working with fields and field collections


‹ Creating Tables and FeatureClasses
‹ Adding rows
‹ Editing table values

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 9-2

Overview
This lesson will discuss how to access existing data on disk as well as how to create new
data. You will learn how to create and define new fields for a table or feature class, how to
add records (rows or features), and how to add new values.
Specifically, the following objects related to working with data will be examined:
WorkspaceFactory
Workspace
FeatureDataset
Table
FeatureClass
Fields/Field
Name
Row
Feature

Introduction to Programming ArcObjects with VBA Data creation 9-2


Data creation objects
Workspace * Dataset
WorkspaceFactory
WorkspaceFactory

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

Object Model overview


Notice that a lot of the objects used to access or create data are Classes, which means they
cannot be created with the New keyword. These objects (such as Workspace, Table, and
Row) must be created from another class.
The first step in working with data on disk is to reference a Workspace object. A Workspace
is simply a folder that contains data (shapefiles, coverages, geodatabase, tables, etc.). Once
you have a Workspace, you can get to all the datasets contained within.

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).

Introduction to Programming ArcObjects with VBA Data creation 9-3


Dataset
According to the diagram above, a Workspace is associated with several (*) datasets. A
dataset is an abstract class that represents both geographic and nongeographic data
collections such as tables, feature datasets, grids, and images. Datasets are accessed through
the Workspace that contains them. If you look at the detailed Geodatabase diagram, you will
notice a lot of subclasses that inherit from the abstract dataset class (such as Table,
ObjectClass, FeatureClass, GeoDataset, etc.).

Introduction to Programming ArcObjects with VBA Data creation 9-4


Opening an existing Workspace
‹ Use IWorkspaceFactory to return a Workspace object
‹ Generic interface for all sub-types of WorkspaceFactory
‹ OpenFromFile: Access an existing folder on disk
‹ Open: Connect to an existing database (e.g., ArcSDE)

Dim
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.

Introduction to Programming ArcObjects with VBA Data creation 9-5


PropertySet
A PropertySet is a collection of name–value pairs. PropertySets support methods to find
properties by name. Property Values are represented as Variants. This allows a Property
Value to hold either a common type, such as a string or a number, or a COM object.
PropertySets are used to represent the metadata available for any dataset. PropertySets can
also be used to represent the set of properties for an individual feature in the database.
For example, a PropertySet used to store connection information for an ArcSDE Workspace
may contain username, instance, and password properties.

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.

Introduction to Programming ArcObjects with VBA Data creation 9-6


Connecting to an ArcSDE database
‹ Use SDEWorkspaceFactory

Use IWorkspaceFactory to
retrieve a workspace

‹ Set connection properties with IPropertySet

Use SetProperties method


to set Database Connection
properties (Server,
Instance, etc)

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 9-7

Use the SDEWorkspaceFactory to retrieve a Workspace object, just as you would if you want
to connect to a folder containing shape. The last slide shows the 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

Dim pPropSet As IPropertySet


Dim pSdeFact As IWorkspaceFactory
Set pPropSet = New PropertySet
With pPropSet
.SetProperty "SERVER", Server
.SetProperty "INSTANCE", Instance
.SetProperty "DATABASE", Dbse
.SetProperty "USER", User
.SetProperty "PASSWORD", Pswd
.SetProperty "VERSION", version
End With
Set pSdeFact = New SdeWorkspaceFactory
Set openSDEWorkspace = pSdeFact.Open(pPropSet, 0)
End Function

Introduction to Programming ArcObjects with VBA Data creation 9-7


Getting a FeatureDataset
‹ IFeatureWorkspace interface on Workspace
‹ OpenFeatureDataset method
Dim pFWorkspace As IFeatureWorkspace
Set pFWorkspace = pWorkspace 'QI for IFeatureWorkspace

Dim pCover As IFeatureDataset


Set pCover = pFWorkspace.OpenFeatureDataset("streets")

Workspace
Workspace FeatureDataset
FeatureDataset

FeatureClasses
FeatureClasses

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 9-8

FeatureDatasets
A FeatureDataset is simply a collection of FeatureClasses. 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.

Introduction to Programming ArcObjects with VBA Data creation 9-8


Getting FeatureClasses
‹ Use IFeatureClassContainer to get existing
FeatureClasses from a FeatureDataset

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.

Introduction to Programming ArcObjects with VBA Data creation 9-9


Pseudocode: Adding a data layer

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?

Introduction to Programming ArcObjects with VBA Data creation 9-10


GxDialog
‹ ArcCatalog type dialog box for browsing directories
‹ User-friendly identification of input/output files
‹ Can open modally for saving or opening a file

‹ Properties that define appearance and behavior


‹ StartingLocation

‹ Title

‹ ObjectFilter

‹ AllowMultiSelect

‹ FinalLocation

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 9-11

GxDialog provides the developer with an easy way to let the user specify input 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.

Introduction to Programming ArcObjects with VBA Data creation 9-11


Example: GxDialog
Dim pGxDialog As IGxDialog
Dim pGxObjEnum As IEnumGxObject
Set pGxDialog = New GxDialog

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

If pGxObject Is Nothing Then Exit Sub


If you wanted to read through the selected files and delete certain types (e.g., shapefiles),
you might use code such as the following to loop through the enumeration.
Dim pGxObjEdit As IGxObjectEdit
Set pGxObj = pGxObjEnum.Next
Do Until pGxObj Is Nothing
If pGxObj.Category = "Shapefile" Then
Set pGxObjEdit = pGxObj
pGxObjEdit.Delete
End If
Set pGxObj = pGxObjEnum.Next
Loop

Introduction to Programming ArcObjects with VBA Data creation 9-12


Exercise 9A overview
‹ Add a layer to a map
‹ Set a shapefile data source

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 9-13

Introduction to Programming ArcObjects with VBA Data creation 9-13


Working with Name objects
‹ A lightweight version of the object it represents
‹ Use Open on IName to return the object

‹ Several creatable subtypes

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 9-14

A Workspace by any other name …


A Name object identifies and locates a geodatabase object (such as a dataset or a Workspace)
or a map object (such as a layer). Although a Name object is simply a surrogate for the object
it represents, it supports an Open method that a programmer can use to instantiate the actual
object represented.
The Open method lets you instantiate the actual object from the Name object.
The example below uses QueryInterface to get the IName interface on a feature class name
then instantiates the corresponding feature class using the Open method.
Dim pName as IName
Set pName = pFeatureClassName
Set pFeatureClass = pName.Open

IUnknown Pointer
If you look at the Open method (on IName) on the Geodatabase 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.

Introduction to Programming ArcObjects with VBA Data creation 9-14


Creating a new Workspace
‹ Use IWorkspaceFactory to get a WorkspaceName
‹ Create method

‹ Use IName to get a Workspace


‹ Open method

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 9-15

Using the Create method


New Workspaces, as you may have guessed, are created from a WorkspaceFactory. The
IWorkspaceFactory interface, which is supported by the creatable (coclass) subtypes of the
WorkspaceFactory class, uses the Create method not to produce new Workspaces, but to
produce new WorkspaceName objects.
WorkspaceName objects, as described on the previous slide, are simply lightweight versions
of a Workspace and not the Workspace itself. In order to instantiate the actual Workspace
object from the WorkspaceName, use the Open method on the IName interface, as shown
below.
'Use Create to return a WorkspaceName.
'Parameters are 1) the parent folder, 2) the name, 3) a
PropertySet, and 4) an hWnd
Dim pWorkName As IWorkspaceName
Set pWorkName = pShapeFileWSFactory.Create ("C:\Data", "MyFiles",
Nothing, 0)

Dim pName As IName


Set pName = pWorkName 'ÅQueryInterface to get the IName
interface

Dim pShapeWSpace As IWorkspace


Set pShapeWSpace = pName.Open 'ÅOpen on any Name returns the
object

Introduction to Programming ArcObjects with VBA Data creation 9-15


PropertySet
A PropertySet is a collection of name–value pairs. PropertySets support methods to find
properties by name. Property Values are represented as Variants. This allows a Property
Value to hold either a common type, such as a string or a number or a COM object.
PropertySets are used to represent the metadata available for any dataset. PropertySets can
also be used to represent the set of properties for an individual feature in the database.
For example, a PropertySet used to store connection information for an ArcSDE Workspace
may contain username, instance, and password properties.
If you do not require a PropertySet to open or create a Workspace, you can use the Nothing
keyword (as in the example above) to ignore this parameter.

Introduction to Programming ArcObjects with VBA Data creation 9-16


Creating a new Table or FeatureClass
‹ Use IFeatureWorkspace interface on Workspace
‹ CreateTable and CreateFeatureClass methods

‹ Requires a Fields collection

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 9-17

Creating a new dataset


Once you have referenced a Workspace object (new or existing), you can create new datasets
inside the Workspace by using one of the methods on the IFeatureWorkspace interface listed
below.

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).

CreateTable and CreateFeatureClass


The CreateTable and CreateFeatureClass methods on IFeatureWorkspace are very similar in
their syntax. This is not surprising because a FeatureClass is simply a table that has
coordinate geometry. Both methods require a string to specify the name of the dataset, UIDs
for specifying custom behavior DLLs, a string for an ArcSDE configuration keyword, and a
collection of fields. CreateFeatureClass has additional parameters related to geometry such as
FeatureType and ShapeFieldName.
Before calling the CreateTable or CreateFeatureClass methods, a programmer would have to
produce a collection of fields to satisfy the Fields parameter.

Introduction to Programming ArcObjects with VBA Data creation 9-17


Field and Fields classes
‹ Tables and FeatureClasses have an associated Fields
‹A Fields is a Collection

‹ A Fields object has Field objects


‹ One or several (1..*)

‹ Creatable

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 9-18

Field and Fields


Before creating a new FeatureClass or Table, you need to produce a collection of fields for
the new dataset. Individual Field objects can be created with the New keyword (they are
coclasses). After creating each Field that you want in the dataset, you need to add them to a
Fields object. Fields is an object that manages a set of individual Field objects. Simply put, it
is a collection of Fields. Like the Field class, Fields is a coclass and can therefore also be
created New.
The fields of an existing dataset can also be accessed. Tables and FeatureClasses have a
Fields property that returns the dataset’s associated Fields object. From this Fields object, you
can access individual Field objects according to index position (as with any collection
object).

Caution
Do not use a dataset’s Fields collection to add a Field to an existing dataset. This method is
only appropriate when creating a new dataset. To add a Field to an existing Table or
FeatureClass, use the AddField method on the dataset itself.

Introduction to Programming ArcObjects with VBA Data creation 9-18


IField and IFieldEdit
‹ Get field properties with IField
‹ Read-only

‹ Set field properties with IFieldEdit


‹ Write-only

Dim pNameField As IFieldEdit


Set pNameField = New Field
With pNameField
.Name = "StreetName"
.Type = esriFieldTypeString
.Length = 16
End With

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 9-19

What a difference an ‘s’ makes


Both the Field and Fields classes support interfaces for reading properties and another for
writing properties. These interfaces are named IField (IFields) for read-only access and
IFieldEdit (IFieldsEdit) for write-only access. When declaring variables to work with field
objects and field collections, take care to use the proper interface. A common mistake is to
inadvertently add or forget an ‘s’ when dimensioning one of these variables, which leaves the
programmer working with a collection instead of a single field object or vice versa.
When creating new Field objects or a new Fields collection, you need to use the editing
interfaces. From the IFieldEdit interface, for example, you can set properties for the new
field such as its name, the type of data it will contain, and it length. Likewise, you can only
add new Field objects to a Fields collection if you are using the IFieldsEdit interface.

The OID field


The OID field is an internal identification field and is basically a record number (object
identifier). The values stored by the OID field are integers that uniquely identify each record
(starting from one and incrementing from top to bottom). These values are managed
internally and do not need to be explicitly set by the user. When creating a table with code,
make sure to create an OID field for your dataset (also make sure to define only one Field as
type OID).

Introduction to Programming ArcObjects with VBA Data creation 9-19


Creating a Fields collection
‹ Use the IFieldsEdit interface
‹ AddField method: Puts a field in the collection
Dim pFieldsEdit As IFieldsEdit
Set pFieldsEdit = New Fields 'Field = Fields !

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).

Introduction to Programming ArcObjects with VBA Data creation 9-20


Creating a Table or FeatureClass
‹ Use IFeatureWorkspace interface on Workspace
‹ CreateTable and CreateFeatureClass methods

Dim pTable As ITable


Set pTable = pFeatureWorkspace.CreateTable _
("Store55", pFieldsEdit, Nothing, Nothing, "")

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.

Introduction to Programming ArcObjects with VBA Data creation 9-21


Additional parameters for creating a FeatureClass
Because a FeatureClass stores coordinate geometry, there are additional FeatureType and
ShapeFieldName parameters required for the CreateFeatureClass method.
FeatureType: satisfied with a constant (esriFeatureType) such as esriFTSimple,
esriFTComplexEdge, and esriFTAnnotation
ShapeFieldName: a string that identifies the field in the Fields collection that will store
coordinate geometry

Introduction to Programming ArcObjects with VBA Data creation 9-22


Work with fields in a table
‹ IFields interface
‹ FieldCount returns the total number of fields
‹ FindField (also on ITable) returns a field’s index number
‹ Field returns a field given the index number
For intLoop = 1 To pFClass.Fields.FieldCount – 1
MsgBox pFClass.Fields.Field(intLoop).Name
Next intLoop

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

Working with fields


In addition to creating a collection of fields for creating a new dataset, the Fields collection
can be returned from any existing Table or FeatureClass as well. Once a reference to the
Fields collection is made, a programmer can use the IFields interface to work with individual
Field objects.

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") )

Introduction to Programming ArcObjects with VBA Data creation 9-23


Adding rows and values to a table
‹ CreateRow on ITable returns a Row
‹ CreateFeature on IFeatureClass returns a Feature

‹ Value property Row Table


‹ Get or set cell values
‹ Specify the field index Feature FeatureClass
Dim pRow As IRow
Set pRow = pTable.CreateRow
pRow.Value(1) = "Jesse White" 'Name
pRow.Value(pTable.FindField("Age")) = 35 'Age
pRow.Store Store
Store commits
commits the
the new
new row
row

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

Adding Rows to a Table


If you look at the simplified object model diagram above, you will notice that Row is a Class,
which means it must be instantiated from another object (and not with the New keyword).
Also shown by the diagram above is the fact that a Table object can instantiate a Row
(dashed arrow means creates a). As a programmer working with Tables and Rows, this
makes perfect sense. Creating a Row with the New keyword would mean that the Row would
exist outside the context of a Table.
By having the Table create the Row, you are assured that the Row is created inside a Table
and that it has all the fields that are defined in that Table. Calling the CreateRow method on
ITable opens an empty record in the parent table. Obviously, it is important to store the Row
that is returned by the CreateRow method in a variable so it can be referenced later in your
code.
The IRow interface on the Row class has a Value property. This property is read–write,
which means you can both access values from an existing Row and provide new values for a
new (or existing) Row. To use the Value property, you need to specify the index position of a
Field you want to provide a value for.
Once all values have been written to a Row, make sure to use the Store method to commit the
new Row to the Table. If you do not use Store, your Row will not actually be added to the
Table.

Introduction to Programming ArcObjects with VBA Data creation 9-24


Features in a FeatureClass
Just as a Table object contains Rows, a FeatureClass contains Features. Features are like
Rows in that they are simply records in a dataset. They differ, however, in the fact that they
store geometry. The methods for assigning values (attributes) described above also apply to
Features in a FeatureClass, with the exception of setting the geometry. You can directly
access geometry for a Feature by using the Shape property defined on the IFeature interface.
As with Rows, make sure to use Store to commit the Feature to the FeatureClass. Below is an
example of storing a new Feature.
Dim pFeature As Ifeature
Set pFeature = pFeatureClass.CreateFeature

Set pFeature.Shape = pPolygon


pFeature.Value(3) = "Hyrum"
pFeature.Value(pFeature.FindField(PropertyValue)) = 160000
pFeature.Value(pFeatureClass.FindField("Owner")) = "Chuck and Joslin Werstak"

pFeature.Store

Introduction to Programming ArcObjects with VBA Data creation 9-25


Exercise 9B overview
‹ Make a new personal geodatabase (workspace)
‹ Create a new table
‹ Add records
‹ Edit values

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 9-26

Exercise 9 overview
In this exercise, you will write code to:
Add a shapefile 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.

Introduction to Programming ArcObjects with VBA Data creation 9-26


Geometry and
Introduction to Programming ArcObjects with VBA

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

Introduction to Programming ArcObjects with VBA Working with geometry 10-1


Lesson overview
‹ Geometry 101
‹ Operators: Working with feature geometry
‹ Drawing geometry
‹ Geoprocessing

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

Introduction to Programming ArcObjects with VBA Working with geometry 10-2


Geometry objects

Geometry * Geometry
collection

Curve Envelope Point * MultiPoint

Polycurve

Segment * Path * Polyline Polygon

Line CircularArc BezierCurve Ring *

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 10-3

Geometry object model diagram


The last slide showed how certain types of geometry can be built by aggregating other types
of geometry. For example, segments can be produced from points and paths can be produced
from segments. This is illustrated in the object model diagram by the fact that the
IGeometryCollection interface is supported by the Polycurve class (inherited by Polygon and
Polyline). A GeometryCollection object is a set of geometries of the same type. It may be a
collection of paths that describe a line, a collection of segments that describe a path, or even a
collection of points that describe a polygon.
Notice that the Path class has an ISegmentCollection and an IPointCollection interface
(inherited by Ring); therefore, there is no hierarchy for building geometry. You do not have to
aggregate points to segments, segments to paths, and paths to rings in order to make a Polygon
feature.
All geometry has an envelope. An envelope is the minimum bounding rectangle that
surrounds a piece of geometry. As the name implies, it is a rectangular geometry with
properties such as LowerLeft, UpperRight, Width, and Height. True to the object model, even
though points do not have area, they do have an (empty) envelope. Being a type of geometry,
even envelopes have an Envelope property. Does an envelope’s envelope have an envelope?

Introduction to Programming ArcObjects with VBA Working with geometry 10-3


Feature geometry
Points Multipoints Polylines Polygons

1 Line 1 Poly

‹ Segments have start and end


with curve in between
‹ Aggregate to paths/rings 2 Paths 3 Rings
(closed paths)
‹ Aggregate to lines/polygons
‹ Edit at any level Bezier Line Circular
curve arc
Segments
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 10-4

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.

Introduction to Programming ArcObjects with VBA Working with geometry 10-4


Points and multipoints
‹ Points are zero dimensional
‹ Defined with x- and y-coordinates
‹ May have Z and M properties

‹ Multipoints are collections of points


Dim pPoint As IPoint

Point Set pPoint = New Point


pPoint.X = 300
pPoint.Y = 450

Multipoint with
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.

Introduction to Programming ArcObjects with VBA Working with geometry 10-5


Segments
‹ Consist of two points (From and To) and a function
defining the curve between them
From To From

To

‹ Subclasses: Line, BezierCurve, CircularArc


‹ Segments used to create other geometry
‹ Paths, polylines, rings, and polygons
Dim pLine As ILine
Set pLine = New Line
pSegment.FromPoint = pPointA
pSegment.ToPoint = pPointB

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 10-6

Segments, lines, and curves


The Segment class is an abstract class, meaning the programmer cannot create a Segment
object with the New keyword. Instead, specific types of segments may be created including
Lines, CircularArcs, EllipticArcs, and BezierCurves. Segment is a subclass of another abstract
class called Curve. All of the above-mentioned classes inherit some of their most basic
properties and methods from the Curve class. For example, FromPoint and ToPoint define the
start and end for any type of curve.

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

Introduction to Programming ArcObjects with VBA Working with geometry 10-6


Polylines and polygons
‹ Polylines
‹ Collections of connected or unconnected paths

‹ Polygons
‹ Composed of one or several rings

1 Polyline with
four segments
1 Polygon with
seven rings

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 10-7

Example: Building a ring from a Segment collection, making a polygon from a


ring
Dim pSegColl As ISegmentCollection
Dim pSegColl As ISegmentCollection
Set pSegColl = New Ring
'pSegmentA and pSegmentB are Lines built earlier
pSegColl.AddSegment pSegmentA
pSegColl.AddSegment pSegmentB

Dim pRing As IRing


Set pRing = pSegColl 'QueryInterface
pRing.Close

Dim pPolygon As IGeometryCollection


Set pPolygon = New Polygon
pPolygon.AddGeometry pRing

Introduction to Programming ArcObjects with VBA Working with geometry 10-7


Envelopes
‹ Define a feature’s spatial extent
‹ Minimum bounding rectangle

‹ All geometry has an envelope


‹ Get or set with IGeometry :: Envelope
Dim pEnvelope As IEnvelope
Set pEnvelope = pLine.Envelope

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 10-8

Envelope
Envelopes are a rectangular geometry. Every geometry has an envelope, 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.

Example: Setting the extent of the active view to a feature’s envelope


'ActiveView’s Extent property is set with an Envelope
'Get the Envelope from a feature’s shape, use it to set map’s
extent
pMxDoc.ActiveView.Extent = pFeature.Shape.Envelope

Introduction to Programming ArcObjects with VBA Working with geometry 10-8


Zooming in to a Feature
‹ Get the extent using a shape’s Envelope property
‹ On the IGeometry interface
‹ Set the ActiveView Extent property with an Envelope

pMxDoc.ActiveView.Extent
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"

Dim pFCursor As IFeatureCursor


Set pFCursor = pFClass.Search(pQFilter, False)
'Å All roads longer than 100000 meters are placed in the
FeatureCursor

Dim pFeature As IFeature


Dim Counter As Integer
Set pFeature = pFCursor.NextFeature
'Å Get the first feature
Do Until pFeature Is Nothing
Counter = Counter + 1
pMxDoc.ActiveView.Extent = pFeature.Shape.Envelope
'Å Get the shape and zoom in
pMxDoc.ActiveView.Refresh
'Å Refresh after each zoom
Set pFeature = pFCursor.NextFeature
'Å Keep pulling out features
Loop
MsgBox "There are " & Counter & " roads longer than 100 km"
End Sub

Introduction to Programming ArcObjects with VBA Working with geometry 10-9


Displaying features
‹ Several Draw methods on IScreenDisplay interface
‹ StartDrawing: Prepare display for drawing
‹ DrawPoint, DrawMultipoint, DrawPolyline, DrawPolygon
‹ FinishDrawing: Flush caches to screen

‹ Quick draw of geometry and symbol


Dim pDisplay As IScreenDisplay
Set pDisplay = pMxApplication.Display
pDisplay.StartDrawing pDisplay.HDC, esriNoScreenCache
pDisplay.SetSymbol pSym
pDisplay.DrawPolygon pPolygon
pDisplay.FinishDrawing

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 10-10

To draw geometry, use the IScreenDisplay interface of the MxApplication’s 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

Introduction to Programming ArcObjects with VBA Working with geometry 10-10


Geometry spatial operator interfaces
‹ Interfaces supported by subtypes of Geometry
‹ ITopologicalOperator

‹ IProximityOperator

‹ IRelationalOperator

‹ Use to …
‹ Perform familiar spatial operations such as buffer, cut, and clip
‹ Measure 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.

Introduction to Programming ArcObjects with VBA Working with geometry 10-11


ITopologicalOperator
‹ Provides methods for working with geometry
‹ Supported by Point, Multipoint, Polyline, and Polygon
Intersect
Union
Buffer

Cut Clip

Dim pTopoOp As ITopologicalOperator


Dim pBuffPoly As IPolygon
Set pTopoOp = pFeature.Shape
Set pBuffPoly = pTopoOp.Buffer (intBufferDistance)

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.

Introduction to Programming ArcObjects with VBA Working with geometry 10-12


IRelationalOperator
‹ Methods for examining spatial relationships (return
Boolean)
‹ Equals: Are input geometries structurally equivalent?
‹ Touches: Do input geometry boundaries intersect?
‹ Contains: Is one geometry contained by the other?
‹ Disjoint: Are input geometries spatially distinct?
‹ Several others
Dim pRelationOp As IRelationalOperator
Dim booTouches As Boolean
Set pRelationOp = pPoly
booTouches = pRelationOp.Touches (pAnotherPoly)

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 10-13

IRelationalOperator interface
IRelationalOperator is supported by the Envelope 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.

Introduction to Programming ArcObjects with VBA Working with geometry 10-13


IProximityOperator
‹ Methods for examining proximity relationships between
features
‹ ReturnDistance: Returns the minimum distance between
features (double)
‹ ReturnNearestPoint: Finds and returns the nearest point on the
specified feature (point)

Dim pProxOp As IProximityOperator


Dim dblDistance As Double
?
Set pProxOp = pLine
dblDistance = pProxOp.ReturnDistance (pSomeOtherLine)

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 10-14

IProximityOperator interface
Unlike the ITopologicalOperator and 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.

Introduction to Programming ArcObjects with VBA Working with geometry 10-14


Area and length
‹ Each feature is a type of Geometry
‹ QueryInterface to Curve (Line features) or Polygon
Dim pArea As IArea Curve
ICurve ICurve: IGeometry
Set pArea = pPoly ‘QI FromPoint: IPoint
IsClosed: Boolean
Msgbox pArea.Area Length: Double
ToPont: IPoint

Polygon
IPolygon
Dim pCurve As ICurve
IPolygon: IPolycurve

IArea ExteriorRingCount: Long Set pCurve = pLine ‘QI


InteriorRingCount(exteriorRing: IRong): Long
Close Msgbox pCurve.Length
FindExteriorRing(interiorRing: IRing): IRing
QueryExteriorRings(ExteriorRings: IRing)
QueryInteriorRings(exteriorRings: IRing,
interiorRings: IRing)
SimplifyPreserveFromTo

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.

Introduction to Programming ArcObjects with VBA Working with geometry 10-15


Spatial reference
‹ All geometry inherits from IGeometry
‹ Use the SpatialReference property to obtain projection
information
‹ Use the Spatial Reference OMD for further parameters

Dim pPoint As IPoint


Set pPoint = mypoint
MsgBox pPoint.SpatialReference.Name

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 10-16

Every piece of geometry has a SpatialReference property, which returns a pointer to


ISpatialReference. ISpatialReference can be found on the Geometry Spatial Reference OMD.
With the SpatialReference property, you can obtain many of the parameters associated with
the projection assigned to the geometry, or simply the name of the projection. Notice that the
SpatialReference property is put by reference (hollow box). Thus, if the projection changes for
a feature class, it will automatically be changed for all of the associated features.

Introduction to Programming ArcObjects with VBA Working with geometry 10-16


Spatial reference OMD
‹ All Geometry has a Spatial reference
‹ Use ISpatialReferenceFactory to create Projected
Coordinate Systems to apply to geometry or feature
class
‹ Make your own or choose from one of ESRI predefined
projections
ISpatialReference SpatialReference

Unknown

Geographic Coordinate- Projected Coordinate-


System System

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 10-17

Spatial reference continued


Geographic data will often times be projected into a different coordinate system to
accommodate the needs of different organizations. The classes on the Geometry Spatial
Reference OMD allow you to reproject your data programmatically. The previous slide
demonstrates how all geometry will have a Spatial Reference Property. The Spatial Reference
property will return either a Geographic Coordinate System, a Projected Coordinate System,
or Unknown (a projection was not assigned).
If you want to reproject your data, you can use the ISpatialReferenceFactory to create a
projected coordinate system that you want your data to be reprojected to. The
ISpatialReferenceFactory Interface is similar to the IWorkspaceFactory Interface used in the
last lecture. It is an abstract class that contains only methods that will return a projection, or a
parameter associated with a projection. Often times you will choose from one of ESRI’s
predefined projection types to project your data to.
If you would like to assign a projection to an entire feature class, use the IGeoDataset
interface on the FeatureClass Class to obtain the SpatialReference property.

Introduction to Programming ArcObjects with VBA Working with geometry 10-17


Exercise 10 overview
‹ Create point features from coordinates
‹ Store point features
‹ Assign feature attributes
‹ Create a polygon from a Point collection
‹ Challenge: Calculate the area from the polygon you
created

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 10-18

Exercise 10: Use coordinate input to draw features


In this exercise, you will draw point and polygon geometry and store it as a feature in a
Feature Class table.

Introduction to Programming ArcObjects with VBA Working with geometry 10-18


Introduction to Programming ArcObjects with VBA

Working with subsets


ModuleTitle

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

‹ Getting a subset of records


‹ Cursor

‹ FeatureCursor

‹ QueryFilters and SpatialFilters

‹ Three types of cursors: Search, Update, and Insert


‹ Looping through cursor records
‹ Displaying a subset of layer features

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 11-2

Overview
There are a variety of ways to work with selections and subsets of 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

Row Cursor Table

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

Object model diagram


You will find the objects discussed in this lesson on the Geodatabase object model diagram.
Notice that, with one exception, all of the classes shown above are Classes and must be
instantiated from another class. The only CoClasses shown above are QueryFilter and its
subtype SpatialFilter. These are the only ones that can be created with the New keyword.
The diamond symbol shown above may be new to you. This symbol indicates that an object is
created (dashed arrow) by two classes working together. Therefore, according to the diagram
above, a Table working in conjunction with a QueryFilter can create a Cursor or a SelectionSet
object. Likewise, a FeatureCursor (which is a type of Cursor) is also created from a
FeatureClass (a type of Table) and a QueryFilter.
Remember that the dashed arrow symbol indicates a creates a relationship. A Row object can
be created from a Table or from a Cursor object. A Feature (which is a type of Row) can be
created either from a FeatureClass (type of Table) or FeatureCursor (type of Cursor).

Introduction to Programming ArcObjects with VBA Working with subsets and selections 11-3
SelectionSet
‹ Get the currently selected records (Rows or Features)
‹ IFeatureSelection :: SelectionSet (FeatureLayer)
‹ ITableWindow :: SelectionSet (TableWindow)

Public Sub GetLayerSelection()


Dim pMxDoc As IMxDocument
Dim pFSel As IFeatureSelection
Dim pSelSet As ISelectionSet

Set pMxDoc = ThisDocument

Set pFSel = pMxDoc.SelectedLayer 'QueryInterface


Set pSelSet = pFSel.SelectionSet

MsgBox pSelSet.Count & " selected features"


End Sub

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.

Public Sub GetTableSelection()


Dim pMxDoc As IMxDocument
Set pMxDoc = ThisDocument
'Use the ITableCollection interface on the Map to get at all tables in the
current data frame
Dim pTableCollection As ITableCollection
Set pTableCollection = pMxDoc.FocusMap
If pTableCollection.TableCount < 1 Then
MsgBox "There are no tables in the active data frame",
vbExclamation
Exit Sub
End If
'Get the first table from the collection
Dim pTable As ITable
Set pTable = pTableCollection.Table(0)

Dim pTabWin As ITableWindow


Dim pOldWin As ITableWindow
Set pTabWin = New TableWindow
'Check to see if the table window is already open
Set pOldWin = pTabWin.FindViaTable(pTable, False)
If Not pOldWin Is Nothing Then
Set pTabWin = pOldWin
Else
Set pTabWin.Table = pTable
Set pTabWin.Application = Application
'Allow one selected row
pTabWin.TableSelectionAction = esriSelectCurrentRow
pTabWin.Show True
End If
'Get the SelectionSet
Dim pSelSet As ISelectionSet
Set pSelSet = pTabWin.SelectionSet 'Å Use the SelectionSet
property on ITableWin to get the selected records

'Show the count of selected records in a message box


MsgBox "The table has " & pSelSet.Count & " selected records"
End Sub

Introduction to Programming ArcObjects with VBA Working with subsets and selections 11-5
Cursors and FeatureCursors
‹ Manages a subset of records as a single object
‹ Not visible to the user (e.g., 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

Using a QueryFilter to return a Search cursor


After creating a QueryFilter (or a SpatialFilter, discussed on the following slide) to define the
criteria to produce a Cursor, you can use the Search method on ITable (Table) or on
IFeatureClass (FeatureClass) to produce a Cursor or FeatureCursor, respectively. Notice that
the Search method has two arguments: the first is the QueryFilter, and the second is a Boolean
that describes how memory should be managed by the Cursor (described in more detail
below).
There are three kinds of Cursors that may be produced from a Table or FeatureClass. Each
type of Cursor is used for a different purpose and is defined by the method used to create it.
The example above creates a Search Cursor by using the Search method on IFeatureClass.
Search Cursors are used to return a subset of records for some type of read-only purpose such
as calculating a statistic or getting a count of records. The two other types of Cursors that may
be created are Update and Insert and will be discussed shortly.

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

The SpatialFilter class is a subclass of QueryFilter. Like QueryFilter, SpatialFilter is a coclass


and can therefore be created with the New keyword. As the name implies, a SpatialFilter is
used to produce a subset of records based on spatial criteria. Because a SpatialFilter uses
spatial relationships (geometry), it is only appropriate to use it with a FeatureClass in order to
create a FeatureCursor.
Instead of using a WhereClause property as the QueryFilter does, a SpatialFilter uses a
Geometry property and a SpatialRel property to define the search criteria.
Geometry: After creating a new SpatialFilter, set this property with some geometry that will be
the basis of the spatial relationship. This property can be set with any type of geometry (i.e.,
any class that supports the IGeometry interface).
SpatialRel: Use one of the predefined esriSpatialRelEnum constants to define the type of
spatial relationship to be used in the search criteria. These constants are listed below.
esriSpatialRelContains
esriSpatialRelCrosses
esriSpatialRelEnvelopeIntersects
esriSpatialRelIndexIntersects
esriSpatialRelIntersects
esriSpatialRelOverlaps
esriSpatialRelTouches
esriSpatialRelUndefined
esriSpatialRelWithin

Introduction to Programming ArcObjects with VBA Working with subsets and selections 11-10
The example
The code in the example above will locate all features that are 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)

‹ Use for read-only analysis of a record subset

‹ Update cursor Dim


Dim myCursor
myCursor As
As IFeatureCursor
IFeatureCursor
‹ Update method Set
Set myCursor
myCursor == pFClass.Update(pQFilter,
pFClass.Update(pQFilter, False)
False)

‹ Use to update or delete records in the database

‹ Insert cursor Dim


Dim myCursor
myCursor As
As IFeatureCursor
IFeatureCursor
‹ Insert method Set
Set myCursor
myCursor == pFClass.Insert(True)
pFClass.Insert(True)

‹ Use to insert new records into the database

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 11-12

Types of cursors
There are three types of cursor objects that can be obtained 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)

Dim myCursor As ICursor


Set myCursor = pTable.Search(pQFilter, False)

myCursor
myCursor initializes
initializes here
here

Set myRow = myCursor.NextRow Cursor


Cursor
Set myRow = myCursor.NextRow
Set myRow = myCursor.NextRow

Set myRow = myCursor.NextRow

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

Set pFeature = pFCursor.NextFeature


Do Until pFeature Is Nothing
intLength = intLength + pFeature.Value(9)
Set pFeature = pFCursor.NextFeature
Loop
MsgBox pFClass.FeatureCount(pQFilter) & _
" roads longer than 100 km." & _
" The total length is " & intLength

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 11-15

Example: Accessing records in a cursor


To access all records inside a cursor, you need to use a Do While or a Do Until loop.
Remember that these loops are based on a condition, rather than on a fixed number of
iterations.
Before entering the loop, the first feature is pulled out of the FeatureCursor
(pFCursor.NextFeature) and stored in a variable (pFeature). The loop will then check to see if
pFeature is Nothing, and until it is, the loop will continue to execute. If, at this point, your
FeatureCursor had no records (i.e., nothing met the search criteria), the first object retrieved
from the cursor would be Nothing, and therefore the body of the loop would never be
executed.
A variable intLength is declared in the code above to summarize the attribute values for the
length field. The field index is specified by the value property (pFeature.Value(9)). For each
record that the cursor finds, intLength is incremented to keep track of all the attributes that
meet the criteria of the Feature Cursor.
After the length is incremented, it is very important to pull another feature from the cursor by
again calling the NextFeature method. This moves the pointer and returns the next object in the
cursor, which is again tested to see if it is Nothing. Without this line of code, you would have
an infinite loop.
The IFeatureClass interface has a FeatureCount property that requires a QueryFilter. This will
return the total number of features that meet the criteria set by the QueryFilter.

Introduction to Programming ArcObjects with VBA Working with subsets and selections 11-15
Review: Features and geometry
‹ Every feature has geometry (shape)
‹ All geometry has an envelope
‹A bounding rectangle
‹ Use an Envelope to set the ArcMap extent

'Zoom
'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

Public Sub ZoomToRoads ()


Dim pQFilter As IQueryFilter
Set pQFilter = New QueryFilter
pQFilter.WhereClause = "LENGTH > 100000"

Dim pFCursor As IFeatureCursor


Set pFCursor = pFClass.Search(pQFilter, False) 'Å All roads
'longer than 100000 meters are placed in the FeatureCursor

Dim pFeature As IFeature


Dim Counter As Integer
Set pFeature = pFCursor.NextFeature 'Å Get the first feature
Do Until pFeature Is Nothing
Counter = Counter + 1
pMxDoc.ActiveView.Extent = pFeature.Shape.Envelope 'Å Get the shape and
'zoom in
pMxDoc.ActiveView.Refresh 'Å Refresh after each zoom
Set pFeature = pFCursor.NextFeature 'Å Keep pulling out features
Loop
MsgBox "There are " & Counter & " roads longer than 100 km“

End Sub

Introduction to Programming ArcObjects with VBA Working with subsets and selections 11-17
Displaying a subset of features
‹ Use IFeatureLayerDefinition :: DefinitionExpression
‹ Creates temporary subset of features for analysis and display

Public Sub MakeLayerDefinition()


Dim pMxDoc As IMxDocument
Dim pFDefine As IFeatureLayerDefinition

Set pMxDoc = ThisDocument


Set pFDefine = pMxDoc.SelectedLayer 'QueryInterface
pFDefine.DefinitionExpression = "Pop > 3000000"
pMxDoc.ActiveView.Refresh 'Refresh the display
End Sub

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 11-18

Displaying a subset of features in a feature layer


There may be times when you need to define an attribute expression, not to produce a subset of
records in a cursor but to restrict the features being displayed in a feature layer in the map. The
easiest way to accomplish this is by using the DefinitionExpression property on the
IFeatureLayerDefinition interface.
IFeatureLayerDefinition is an interface supported by the FeatureLayer class. By using an
attribute expression for a QueryFilter’s WhereClause, you can define a subset of features to be
displayed in the map (and in the attribute table for the layer). To clear a subset definition and
return to viewing the entire set of features, set the definition expression equal to an empty
string (“”).

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

‹ Calculate statistics for a subset of features


‹ IQueryFilter :: WhereClause
‹ FeatureCursors

‹ Produce a cursor based on attribute and spatial criteria


‹ SpatialFilter

‹ SelectionSet

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 11-19

In this exercise, you will work with some of the ArcObjects related to making 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

Introduction to Programming ArcObjects with VBA Layer rendering 12-1


Lesson overview
‹ Overview of symbology objects
‹ Symbol objects
‹ Color objects
‹ Color ramps

‹ Adding simple graphics to the map


‹ Changing layer display with FeatureRenderers
‹ Managing layer symbology with layer files (*.lyr)

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 12-2

Overview
This lesson will introduce you to some of the ArcObjects required to 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.

Introduction to Programming ArcObjects with VBA Layer rendering 12-2


Subclasses of Symbol
ISymbol Symbol *

MarkerSymbol LineSymbol FillSymbol

SimpleMarkerSymbol SimpleLineSymbol SimpleFillSymbol

CharacterMarkerSymbol PictureLineSymbol LineFillSymbol

PictureMarkerSymbol HashLineSymbol MarkerFillSymbol

* Several additional types of symbols are listed on the Display OMD, including 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.

Example: Creating a simple (dashed) line symbol


Dim pSLineSymbol As ISimpleLineSymbol
Set pSLineSymbol = New SimpleLineSymbol
pSLineSymbol.Style = esriSLSDash 'esriSimpleLineStyle

Example: Creating a simple (diagonal-hatched) fill symbol


Dim pSFillSymbol As ISimpleFillSymbol
Set pSFillSymbol = New SimpleFillSymbol
pSFillSymbol.Style = esriSFSForwardDiagonal 'esriSimpleFillStyle

Introduction to Programming ArcObjects with VBA Layer rendering 12-3


Using color
‹ Five creatable subclasses IColor Color

‹ RgbColor

‹ CmykColor
RgbColor HlsColor

‹ HsvColor

‹ HlsColor CmykColor HsvColor

‹ GrayColor
GrayColor
‹ Properties for defining color
‹ Red, Green, Blue values (0–255)
‹ Grayscale (0=white – 255=black)
‹ Cyan, Magenta, Yellow, Black

‹ Use a color object to assign a symbol’s color property


Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 12-4

Add some color to your code


Because the five subclasses of color are coclasses, they can each be created with the New
keyword. As a programmer, you can choose Color objects and interfaces according to how you
would like to define a particular color. To specify individual values for red, green, and blue for
example, you would use the IRgbColor interface on the RgbColor class.
Below are brief descriptions of how color is defined for each of the five color interfaces.
• IRgbColor: Red, green, and blue (0–255)
• ICmykColor: Cyan, magenta, yellow, and black (0–255)
• IHsvColor: Hue (0–360), saturation, and value (0–100)
• IHlsColor: Hue, lightness, and saturation (0–100)
• IGrayColor: Level 0 (white) to 255 (black)
Visual Basic functions for defining color
Visual Basic has some built in ways to specify color values. One of the most powerful is the
RGB function. The RGB function takes three integer arguments that indicate the amount of red,
green, and blue respectively. Here’s an example of using the RGB function to make a cyan
color:
Dim myColor As IRGBColor
Set myColor = New RGBColor
myColor.RGB = RGB(0,255,255) '*Red,Green,Blue: 0-255
Visual Basic also contains color constants that can be used to define a handful of basic colors.
These constants are: vbBlack, vbBlue, vbCyan, vbGreen, vbMagenta, vbRed, vbWhite, and
vbYellow

Introduction to Programming ArcObjects with VBA Layer rendering 12-4


ColorRamps
‹ Four subclasses IColorRamp ColorRamp

‹ AlgorithmicColorRamp

‹ RandomColorRamp AlgorithmicColorRamp PresetColorRamp

‹ PresetColorRamp

‹ MultiPartColorRamp MultiPartColorRamp RandomColorRamp

‹ Color ramps can also be referenced from the StyleGallery

Accessing items in the StyleGallery


will be covered in Lesson 13

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 12-5

The four subclasses of ColorRamp are coclasses. Therefore, the programmer can 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.

Example: Create a new random color ramp


Public Function GetRandomRamp (NumColors As Integer) As IEnumColors
Dim pRandomColorRamp As IColorRamp
Set pRandomColorRamp = New RandomColorRamp

pRandomColorRamp.Size = NumColors ' *Passed into the function


Dim blnOK As Boolean
pRandomColorRamp.CreateRamp blnOK '* Make it so!
If Not blnOK Then Exit Function '* Exit if there was an error

Set GetRandomRamp = pRandomColorRamp '*Pass back the ramp


End Function

Introduction to Programming ArcObjects with VBA Layer rendering 12-5


Creating simple graphic elements
‹ Several creatable classes
‹ Graphic elements IElement Element Geometry

‹ Line, polygon, marker


‹ Text and pictures FrameElement GraphicElement

‹ FrameElements TextElement LineElement

‹ 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 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.

Introduction to Programming ArcObjects with VBA Layer rendering 12-6


Example: Make a new element, set its symbol
Dim pMarkerElem As IMarkerElement
Set pMarkerElem = New MarkerElement 'Make a new element

Dim pMarkerSym As ISimpleMarkerSymbol


Set pMarkerSym = New SimpleMarkerSymbol 'Make a new symbol
pMarkerSym.Style = esriSMSCircle 'Specify the symbol style

Dim pColor As IRgbColor


Set pColor = New RgbColor 'Make a new color
pColor.RGB = RGB(255,0,0) 'Make it red (RGB is a VB function)

pMarkerSym.Color = pColor 'Assign color to the symbol

pMarkerElem.Symbol = pMarkerSym ' Assign the symbol


'to the element

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 12-7

The color’s connected to the … sym-bol. The symbol’s connected to the …


mar-ker.
Follow the same general process illustrated in the example above for any graphic element you
want to create.
1. Create a new graphic element (LineElement, MarkerElement, PolygonElement,
2. Create a new symbol appropriate for the element (LineSymbol, TextSymbol, FillSymbol, etc.).
3. Create a new color object (RgbColor, CmykColor, GrayColor, HlsColor, or HsvColor).
4. Define the color’s value.
5. Assign the color to the symbol.
6. Define the symbol’s style.
7. Assign the symbol to the graphic element.

At this point, the graphic element is completely defined, but does not yet appear on the display.

Introduction to Programming ArcObjects with VBA Layer rendering 12-7


Defining an element’s position
‹ IElement :: Geometry
‹ Supported by all subclasses of Element
‹ Defines a position on the map (or layout page)
‹ Specify with a point, line, or envelope

Dim
Dim 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

Tell that element where to go


All elements support a Geometry property (defined on the IElement interface). Before adding
any element to the display (GraphicsContainer), you must first define where the element is to
appear on the page or map. An element’s Geometry property can be specified with either a
point, a line, or an envelope, depending on which is most appropriate. Marker elements, of
course, should be defined using a point. Text elements, on the other hand, can be positioned
with a point (the center of the text), a line (perhaps a curve that the text should follow), or an
envelope (bounding box).
Geometry can be defined either in page units (for elements added to the page layout) or in map
units (for elements added to the data frame).

Introduction to Programming ArcObjects with VBA Layer rendering 12-8


Adding an element to the map (or layout)
‹ Use IGraphicsContainer :: AddElement
‹ Specify the element and the order
‹ Zero is the first (top) element, increases from top to bottom

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

Refresh the display to show the new element

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 12-9

Adding an element to the graphics container


Both the Map and PageLayout classes support the IGraphicsContainer interface. As the name
implies, this is an interface that allows a programmer to manage graphic elements that appear
either in the data frame or in the page layout. The AddElement method is used to place new
elements on the display.
To add an element to the layout, use IGraphicsContainer on the PageLayout object and make
sure your element’s position (Geometry property) has been defined in page units. An element
added to the data frame should use IGraphicsContainer on the Map object, and have its
geometry defined in map units.
To control which elements are drawn on top of others, a programmer can change the order of
elements using methods such as SendToBack, BringToFront, or PutElementOrder. When
retrieving elements, the GraphicsContainer behaves like an enum. To retrieve elements from
the container, a programmer cannot use the element’s position, but must instead use the Next
method to pull out elements sequentially, and the Reset method to move the pointer back to the
top.

Introduction to Programming ArcObjects with VBA Layer rendering 12-9


Example: Count all the graphic elements on the layout
Public Sub CountLayoutElements ()
Dim pMxDoc As IMxDocument
Dim pGContainer As IGraphicsContainer
Dim pElement As IElement
Dim intGraphicCount As Integer

Set pMxDoc = ThisDocument


Set pGContainer = pMxDoc.PageLayout
pGContainer.Reset '*Make sure the pointer is on the first item
Set pElement = pGContainer.Next '*pull out the first element
Do Until pElement Is Nothing '*Loop thru all elements
If TypeOf pElement Is IGraphicElement Then
intGraphicCount = intGraphicCount + 1 '*increment the count
End If
Set pElement = pGContainer.Next '*pull out the next element
Loop

MsgBox "There are " & intGraphicCount & " graphics on the page"
Exit Sub

Introduction to Programming ArcObjects with VBA Layer rendering 12-10


FeatureRenderers
‹ Renderers define how a layer is displayed

IFeatureRenderer FeatureRenderer FeatureLayer

SimpleRenderer UniqueValueRenderer ClassBreaksRenderer

ChartRenderer ScaleDependentRenderer DotDensityRenderer

There are additional Renderers for displaying RasterLayers and TinLayers

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 12-11

All feature layers have an associated FeatureRenderer that can be set or 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.

Introduction to Programming ArcObjects with VBA Layer rendering 12-11


SimpleRenderer
‹ Default renderer displays features with a single symbol

USA

‹ Properties
‹ Symbol: Color and Style
‹ Label: A string to appear in the legend

‹ Refresh after modifying a layer’s renderer


'Set
'Set aa feature
feature layer’s
layer’s renderer
renderer
Set
Set pFLayer.Renderer
pFLayer.Renderer == pRender
pRender
'Refresh
'Refresh the
the display
display
pMxDoc.ActiveView.Refresh
pMxDoc.ActiveView.Refresh
'Refresh
'Refresh the
the Table
Table of
of Contents
Contents (TOC)
(TOC)
pMxDoc.UpdateContents
pMxDoc.UpdateContents
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 12-12

Example: Create and modify a SimpleRenderer


Private Sub ApplySimpleRenderer(SomeLayer As IGeoFeatureLayer)
Dim pSRenderer As ISimpleRenderer
Set pSRenderer = New SimpleRenderer
Dim pFillSymbol As ISimpleFillSymbol
Set pFillSymbol = New SimpleFillSymbol
pFillSymbol.Style = esriSFSForwardDiagonal
Dim pColor As IRgbColor
Set pColor = New RgbColor
pColor.RGB = vbBlue
pFillSymbol.Color = pColor
'Property put by reference, must use "Set" …
Set pSRenderer.Symbol = pFillSymbol
pSRenderer.Label = "USA"
'Set the layer’s renderer, also property put by reference
Set SomeLayer.Renderer = pSRenderer
Dim pMxDoc As IMxDocument
Set pMxDoc = ThisDocument
pMxDoc.UpdateContents 'Update legend
pMxDoc.ActiveView.Refresh 'Redraw display
End Sub

Introduction to Programming ArcObjects with VBA Layer rendering 12-12


UniqueValueRenderer
‹ Displays features with a symbol for each unique value

‹ Properties
‹ Field(s): The field(s) in the feature class for which unique values
are rendered
‹ Value(s): Unique categories of features (e.g., “Pacific”)
‹ ValueCount: The 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

Example: Create a UniqueValueRenderer to uniquely symbolize each state


Private Sub ApplyUniqueRenderer(SomeLayer As IGeoFeatureLayer)
Dim pUVRenderer As IUniqueValueRenderer
Set pUVRenderer = New UniqueValueRenderer
Dim pColorEnum As IEnumColors
Set pColorEnum = MakeRandomRamp(50) 'Example on pg 12-5
pUVRenderer.FieldCount = 1
pUVRenderer.Field(0) = "STATE_NAME"
Dim pFClass As IFeatureClass
Set pFClass = SomeLayer.FeatureClass
Dim pFCursor As IFeatureCursor
Set pFCursor = pFClass.Search(Nothing, False)
Dim pFeature As IFeature, pSym As ISimpleFillSymbol
Set pFeature = pFCursor.NextFeature
Do Until pFeature Is Nothing
Set pSym = New SimpleFillSymbol
pSym.Color = pColorEnum.Next
pUVRenderer.AddValue _
pFeature.Value(pFClass.FindField("STATE_NAME")), "States", pSym
Set pFeature = pFCursor.NextFeature
Loop
Set SomeLayer.Renderer = pUVRenderer 'Property put by reference
m_pMxDoc.UpdateContents
m_pMxDoc.ActiveView.Refresh
End Sub

Introduction to Programming ArcObjects with VBA Layer rendering 12-13


ClassBreaksRenderer
‹ A symbol for each grouping of numeric values

‹ 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

Those are the Breaks


A ClassBreaksRenderer is used to display classes of a layer’s features based on a numeric attribute.
When creating a ClassBreaksRenderer, you need to specify the number of classes to use, the field on
which the classification is based and whether classes should be sorted lowest to highest (ascending) or
highest to lowest (descending).
The breaks (cut-off points) that define each class also need to be explicitly defined by the programmer,
along with the symbol that will be used to symbolize each class. The numeric values that represent the
break points for each class can be defined arbitrarily (hard-coded) or may be derived from a statistical
method. Assigning classes and symbols to the renderer is usually performed in a looping routine such as
the pseudocode shown below.
For i=0 to the-number-of-classes -1
Make a new symbol
Set symbol properties (e.g., color)
Assign class break i
Assign the symbol for class i
Next i

Introduction to Programming ArcObjects with VBA Layer rendering 12-14


ScaleDependentRenderer
‹ A renderer that contains renderers
‹ Update the rendering of a layer according to scale
‹ More detail at large scales, less detail at small scales

1:75,000,000
1:7,000,000

‹ Properties
‹ Breaks: Cut-off points (scale ranges)
‹ Renderers: Renderers in the ScaleDependentRenderer
‹ RendererCount: Number of renderers contained

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 12-15

A ScaleDependentRenderer is simply a collection of several renderers used to display a single


layer. Particular renderers in the ScaleDependentRenderer are applied to the feature layer (i.e.,
turned on and off) according to the scale at which the data is displayed. This may be useful for
dynamically displaying a layer in more detail when viewed at a larger scale while showing a
general view when viewed at a smaller scale.
When creating a ScaleDependentRenderer, the order in which you add renderers should match
the order in which you define the associated scale breaks. In other words, the first renderer
added will correspond to the first break that is defined. The code below adds two renderers and
sets their scale breaks. Because the renderer represented by pZoomedInRend was added first, it
will be associated with the first break (break 0). This renderer will be used to display the layer at
scales greater than 1:10000000. When the layer is displayed at scales between 1:10000001 and
1:90000000, it will be displayed using the renderer represented by pZoomedOutRend.
Note: If zoomed out beyond the last threshold (scales smaller than 1:90000000 in the example
below) the layer will not be renderered.
pScaleDepRend.AddRenderer pZoomedInRend ' Add the 1st renderer
pScaleDepRend.AddRenderer pZoomedOutRend ' Add the 2nd renderer
' Set scale threshold for 1st renderer (pZoomedInRend)
pScaleDepRend.Break(0) = 10000000
' Set scale threshold for 2nd renderer (pZoomedOutRend)
pScaleDepRend.Break(1) = 90000000
Set pFLayer.Renderer = pScaleDepRend 'Assign the layer’s renderer

Introduction to Programming ArcObjects with VBA Layer rendering 12-15


Storing layers on disk
‹ Layers may be saved as layer (*.lyr) files
‹ Layer files store information about the layer
‹ Path to the data
‹ Symbology

‹ Label preferences
‹ Definition query
‹ Etc.

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 12-16

Layer files
In ArcGIS, a layer object can live in one of two places: saved as 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.

Introduction to Programming ArcObjects with VBA Layer rendering 12-16


GxLayer object
‹ Use to access layer (*.lyr) files
‹A subtype of GxFile
GxFile
‹ IGxFile::Path IGxFile : IUnknown
IGxFile
‹ Defines the path to a file * Path: String

GxCatalog

GxLayer
IGxLayer : IUnknown
IGxLayer
Layer: ILayer

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 12-17

Example: adding a layer to ArcMap using GxLayer

Private Sub GetLayerFromFile ()


'Create a new GxLayer
Dim pGxLayer As IGxLayer
Set pGxLayer = New GxLayer
'QueryInterface to IGxFile, specify the path
Dim pGxFile As IGxFile
Set pGxFile = pGxLayer
pGxFile.Path = "C:\Data\Waynesboro.lyr"
'Get the layer from the file
Dim pLayer As ILayer
Set pLayer = pGxLayer.Layer
'Add the layer to the active data frame
Dim pMxDoc As IMxDocument
Set pMxDoc = ThisDocument
pMxDoc.FocusMap.AddLayer pLayer
End Sub

Introduction to Programming ArcObjects with VBA Layer rendering 12-17


Example: Saving a layer from ArcMap
Public Sub SaveFirstLayer ()
Dim pMxDoc As IMxDocument
Set pMxDoc = ThisDocument
'Create a new GxLayer object
Dim pGxLayer As IGxLayer
Set pGxLayer = New GxLayer 'Coclass: can create new
'QueryInterface for the IGxFile interface
Dim pGxFile As IGxFile
Set pGxFile = pGxLayer
'Define the file’s pathname
pGxFile.Path = "C:\Data\Shelbyville.lyr"
'Assign the first layer in the focus map to the layer file
Set pGxLayer.Layer = pMxDoc.FocusMap.Layer(0)
'Save the file
pGxFile.Save
'Done!
End Sub

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 12-18

Programmatically saving layer files


The GxLayer class is a coclass, so instances can be created using the New keyword. The only
member available on the IGxLayer interface is the Layer property. IGxLayer:: Layer is used to
define or retrieve the layer object stored in the file.
GxLayer is a subclass of GxFile, and therefore supports the IGxFile interface. When saving a new
layer file, you must QueryInterface to IGxFile in order to define the output file name (using the
Path property). The Save method must be called to commit the layer file to disk.

Example: Saving all layers in the active data frame


Public Sub SaveAllLayers ()
Dim pMxDoc As IMxDocument
Set pMxDoc = ThisDocument
Dim pEnumLayer As IEnumLayer, pLayer As ILayer
Set pEnumLayer = pMxDoc.FocusMap.Layers
Set pLayer = pEnumLayer.Next
Do Until pLayer Is Nothing
Dim pGxLayer As IGxLayer
Dim pGxFile As IGxFile
Set pGxLayer = New GxLayer
Set pGxFile = pGxLayer '**QueryInterface
pGxFile.Path = "C:\Data\Layers\" & pLayer.Name & ".lyr"
Set pGxLayer.Layer = pLayer
pGxFile.Save
Set pLayer = pEnumLayer.Next
Loop
End Sub

Introduction to Programming ArcObjects with VBA Layer rendering 12-18


Exercise 12 overview
‹ Create a new fill symbol and color
‹ Render layers in the map
‹ Save a layer in the document to a layer file (*.lyr)
‹ Add layer files to ArcMap
‹ Experiment with scale dependent rendering

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 12-19

Exercise 12: Work with the display, symbols, and renderers


In this exercise, you will:
• Create a new fill symbol and color for rendering a layer.
• Create a new UIButtonControl for saving the selected layer to a layer file.
• Create a control for adding layer files to the focus map.
• Experiment with ScaleDependentRenderers.

Introduction to Programming ArcObjects with VBA Layer rendering 12-19


Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 12-20

Introduction to Programming ArcObjects with VBA Layer rendering 12-20


Working with layout
Introduction to Programming ArcObjects with VBA

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

‹ Accessing items from the StyleGallery


‹ Printing and exporting a layout

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 13-2

Working with Layout Elements


This lesson will discuss many of the objects related to adding graphics to an ArcMap page
layout or map. Graphics, whether they are things such as scalebars, north arrows, markers,
lines, or text, are generically referred to as elements. Each of these elements may be added to
a page layout, or possibly a map. When working with elements, you may also find it
necessary to use related objects such as symbols, colors, and geometry (to define the elements
position on the page or map), all of which will be covered in this lesson.

Lesson overview
• Object model overview
• Working with layout frame elements
• 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

Geometry Element PageLayout


*

*
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.

Graphic and Frame elements


The two direct sub-types of Element are themselves abstract classes and represent the two
fundamental types of elements:
• GraphicElements—text, shape, and picture elements
• FrameElements—MapFrames (i.e., data frames), TableFrames, OLEFrames, and
MapSurroundFrames (e.g., north arrows, legends, and scalebars)
Apart from a handful of abstract classes, all elements are creatable (coclasses). As a
programmer, you can create new text, graphic, or map elements to add to your layout. Most
graphic elements will have a Symbol property that allows you to control the color and style of
the graphics you create.
Frame elements are used as containers in the layout. MapFrames contain a collection of layers
(in other words, a data frame), while a MapSurroundFrame element is used to contain objects
that are related to a particular Map, such as a scalebar, north arrow, or legend. It is important
to make a distinction between a MapSurroundFrame, and the object it contains, a
MapSurround. MapSurrounds, such as a Legend, are related directly to a Map (data frame),
and must be contained within a MapSurroundFrame in order to be represented on the layout.
Other types of FrameElements include TableFrame, for containing a Table object, and an
OLEFrame, for containing another application (such as a Microsoft Word document).

Introduction to Programming ArcObjects with VBA Working with layout elements 13-3
Review: Elements
‹ Several creatable classes
‹ Graphic elements IElement Element Geometry

‹ Line, polygon, marker


‹ Text and pictures FrameElement GraphicElement

‹ FrameElements TextElement LineElement

‹ 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

Example: Count the types of elements on the layout


Public Sub CountElements ()
Dim pMxDoc As IMxDocument
Dim pGC As IGraphicsContainer
Set pMxDoc = ThisDocument
Set pGC = pMxDoc.PageLayout
pGC.Reset

Dim intMapFrames As Integer, intMSFrames As Integer


Dim intTextElements As Integer, intOtherElements As Integer

Dim pElement As IElement


Set pElement = pGC.Next
Do Until pElement Is Nothing
If TypeOf pElement Is IMapFrame Then
intMapFrames = intMapFrames + 1
ElseIf TypeOf pElement Is IMapSurroundFrame Then
intMSFrames = intMSFrames + 1
ElseIf TypeOf pElement Is ITextElement Then
intTextElements = intTextElements + 1
Else
intOtherElements = intOtherElements + 1
End If
Set pElement = pGC.Next
Loop

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
*

GraphicElement FrameElement Map

*
TextElement MapFrame MapSurround

MapSurroundFrame ScaleBar

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 13-5

MapSurrounds and MapSurroundFrames


The terms MapSurround and MapSurroundFrame can be a little confusing. To distinguish these
objects, remember that a MapSurroundFrame is a type of Element, and can be added to a
PageLayout. A MapSurround object, on the other hand, is always contained within a
MapSurroundFrame and has a dynamic relationship with a Map (data frame).

Introduction to Programming ArcObjects with VBA Working with layout elements 13-5
Example: Reference MapFrames on the layout
Dim pMxDoc As IMxDocument
Set pMxDoc = ThisDocument
Dim pGC As IGraphicsContainer
Set pGC = pMxDoc.PageLayout
pGC.Reset 'Like an enum, Reset moves above the 1st item

Dim pElem As IElement


Set pElem = pGC.Next 'Also like an enum, Next gets an element
Do Until pElem Is Nothing
If (TypeOf pElem Is IMapFrame) Then 'Many element types
Dim pMapEnvelope As IEnvelope
Dim intW As Integer, intH As Integer
Set pMapEnvelope = pElem.Geometry.Envelope
intW = pMapEnvelope.Width
intH = pMapEnvelope.Height
MsgBox "Map Frame = " & intW & " by " & intH
End If
Set pElem = pGC.Next 'Retrieve another element
Loop

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 13-6

Retrieving an element from the GraphicsContainer


Elements in a GraphicsContainer are organized like objects contained by an enum. Elements
cannot be referenced directly by their index position inside the GraphicsContainer, but must
be located within a looping routine. If searching for a particular type of element (text, picture,
etc.), use the TypeOf statement to identify the element(s) you want to work with.
The example above uses a Do While loop to iterate through each element in the
GraphicsContainer. Inside the loop, a test is made to determine if the current element is a map
frame (supports the IMapFrame interface). If it is, the element’s dimensions are stored, and
then reported in a message box inside the loop. An ArcMap document always has at least one
map frame, but could potentially have many more. The code above will report the dimensions
of all map frames in the layout.

Finding an element by name


Elements added to the GraphicsContainer can be given a name by using the Name property
on IElementProperties. By assigning a name to an element, it can be easily referenced later by
using code such as that shown below:
Dim pElementProps As IElementProperties
Set pElementProps = pGContainer.Next
Do Until pElementProps Is Nothing '*Loop thru all elements
If pElementProps.Name = "DougherNorth" Then '*Look for this one

Dim pLegendFrame As IMapSurroundFrame
Set pLegendFrame = pElementProps '*QueryInterface (QI)
Exit Do '*Exit the loop once it's found
End If
Set pElementProps = pGContainer.Next
Loop

Introduction to Programming ArcObjects with VBA Working with layout elements 13-6
Review: Subclasses of Symbol
ISymbol Symbol *

MarkerSymbol LineSymbol FillSymbol

SimpleMarkerSymbol SimpleLineSymbol SimpleFillSymbol

CharacterMarkerSymbol PictureLineSymbol LineFillSymbol

PictureMarkerSymbol Has hLineSymbol MarkerFillSymbol

* 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.

Example: Creating a bold Arial text symbol


'*Make a new Font …
Dim pArialFont As New stdole.StdFont
pArialFont.Name = "Arial"
pArialFont.Bold = True
'*Make a new TextSymbol, set its properties (including the font) …
Set pTextSym = New TextSymbol
pTextSym.Angle = 45
pTextSym.Font = pArialFont
pTextSym.Size = 28
'*Assign the TextSymbol to a TextElement …
pTextElem.Symbol = pTextSym

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

‹ Use a color object to assign a symbol’s color property

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 13-8

Add some color to your code


Because the five subclasses of color are coclasses, they can each be created with the New
keyword. As a programmer, you can choose Color objects and interfaces according to how you
would like to define a particular color. To specify individual values for red, green, and blue for
example, you would use the IRgbColor interface on the RgbColor class.

Let the user decide …


Instead of “hard-coding” the value of colors in your program, you may want to let the user
choose a color interactively. ArcObjects gives you access to the same color selection dialog you
find from the ArcGIS user interface. The code below will display the color selection dialog
(shown above), then return the color selected.

Public Function GetUserColor() As IColor


Dim pColorDlg As IColorSelector
Set pColorDlg = New ColorSelector '*Make a new color selection
dialog
Dim bMadeChoice As Boolean
bMadeChoice = pColorDlg.DoModal(Application.hWnd) '*Show the dialog

If Not bMadeChoice Then Exit Function '*If user hit "Cancel", exit

Set GetUserColor = pColorDlg.Color '*Return the selected color


End Function

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

Why reinvent the wheel?


ArcMap comes with an extensive set of symbols and map elements that you can access
through the StyleGallery. The StyleGallery object contains StyleGalleryClasses, such as north
arrows, marker symbols, color ramps, colors, and scale bars (to name but a few). Within each
StyleGalleryClass, you can reference individual StyleGalleryItems. StyleGalleryItems are
objects that represent particular north arrows, marker symbols, colors, or anything else you
might find in the StyleGallery (the “Open Pasture” fill pattern, for example). By referencing
items that are already defined in the StyleGallery, a programmer does not need to explicitly
build each element “from the ground up”.
Each MxDocument is composed of a single StyleGallery object. The StyleGallery can be
accessed by using the StyleGallery property on IMxDocument. From the StyleGallery, a
programmer can access enums of all StyleGalleryItems contained by a particular
StyleGalleryClass (an enum of all color ramps, for example).
Instances of the StyleGallery class can also be created new. This can be useful when building
stand-alone applications (in Visual Basic, for example) that need to reference items stored in
an ArcGIS style.

Introduction to Programming ArcObjects with VBA Working with layout elements 13-9
Getting style items from the gallery
‹ IStyleGallery :: Items
‹ Specify the style class (type)
‹ Returns an enum of style items

'Get
'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

'—OR– get the arrow named "ESRI North 3" …


Dim pNorthItem As IStyleGalleryItem
Set pNorthItem = pEnumNorth.Next
Do Until pNorthItem Is Nothing
If pNorthItem.Name = "ESRI North 3" Then
Exit Do
End If
Set pNorthItem = pEnumNorth.Next
Loop

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 13-11

Find your Style


To locate a particular StyleItem from an enum, use one of the familiar Visual Basic looping
routines. To find an item according to its position (the 23rd color ramp, for example), an
ArcObject programmer can use a For Next loop to call the Next method x number of times.
To find an item by name, use a Do Until or Do While loop, as in the second example above.

Example: Saving an item to the style gallery


Public Sub SaveMarkerSym(aNewSymbol As IMarkerSymbol)
'*Make a new StyleGalleryItem, set its properties ...
Dim pSGItem As IStyleGalleryItem
Set pSGItem = New StyleGalleryItem
pSGItem.Item = aNewSymbol '*assign the marker symbol
pSGItem.Name = "Chanda Marker" '*give it a name
pSGItem.Category = "Custom" '*assign it to a category
Dim pMxDoc As IMxDocument
Set pMxDoc = ThisDocument
Dim pSGalleryStorage As IStyleGalleryStorage
Set pSGalleryStorage = pMxDoc.StyleGallery '*get the style gallery
'*Indicate the target style file for the new marker ...
pSGalleryStorage.TargetFile = "ESRI.style"
Dim pSGallery As IStyleGallery
Set pSGallery = pSGalleryStorage 'QueryInterface
pSGallery.AddItem pSGItem '*add item to the gallery (ESRI.style)
End Sub

Introduction to Programming ArcObjects with VBA Working with layout elements 13-11
Getting the item
‹ A StyleGalleryItem is not the item itself
‹ Use the Item property to return the 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.

I am not anonymous, so why am IUnknown?


The Style object model diagram indicates that the Item property on IStyleGalleryItem returns
a pointer to the IUnknown interface. Why? You might expect it to return, for example,
ISymbol, IMapSurround, or IColor. At first glance this might seem confusing, but when
considering the nature of StyleGalleryItems, it becomes clearer. Because the style gallery
contains a variety of objects, including colors, color ramps, north arrows, text symbols, and
even reference systems, ArcMap cannot anticipate what exactly will be returned from a
particular StyleGalleryItem. The one thing that each of these objects will have in common,
however, is the IUnknown interface, which is implemented by all COM classes.

Introduction to Programming ArcObjects with VBA Working with layout elements 13-12
Basic steps: Adding a map surround
‹ A MapSurround is contained by a MapSurroundFrame
1. 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

You are surrounded


MapSurrounds are things such as north arrows, scale bars, and legends. MapSurrounds are not
simple graphics that you add to a layout, but are directly and dynamically tied to a map (data
frame). When a user zooms in or out on a map, for example, the scale bar that is associated
with that map must dynamically alter itself to represent the new scale. Use the Map property
on IMapSurround (which is a property put by reference) to tie a MapSurround to the
appropriate Map.

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

‹ Send to a printer or to a file

Application Paper

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 13-15

Example: Printing the layout to a postscript file


Private Sub PrintToPSFile(aLayout As IPageLayout, FileName As String)
Dim pMxApp As IMxApplication, pPrinter As IPrinter
Set pMxApp = Application
Set pPrinter = New PsPrinter
Set pPrinter.Paper = pMxApp.Paper
pPrinter.PrintToFile = FileName
Dim pPrintEnv As IEnvelope
Set pPrintEnv = New Envelope
aLayout.Page.GetDeviceBounds pPrinter, 0, 0, pPrinter.Resolution, pPrintEnv
Dim rectOut As tagRECT
rectOut.Left = pPrintEnv.xMin
rectOut.Top = pPrintEnv.yMin
rectOut.Right = pPrintEnv.xMax
rectOut.bottom = pPrintEnv.yMax
Dim pPageBounds As IEnvelope
Set pPageBounds = New Envelope
aLayout.Page.GetPageBounds pPrinter, 0, 0, pPageBounds
Dim hDc As OLE_HANDLE
hDc = pPrinter.StartPrinting(pPrintEnv, 0)
Dim pActiveView As IActiveView
Set pActiveView = aLayout
pActiveView.Output hDc, pPrinter.Resolution, rectOut, pPageBounds, Nothing
pPrinter.FinishPrinting
MsgBox "Layout sent to " & FileName, vbInformation, "Printing complete!"
End Sub

Introduction to Programming ArcObjects with VBA Working with layout elements 13-15
Exporting a layout
‹ Variety of export formats IExporter Exporter

‹ Adobe Acrobat (*.pdf)


‹ JPEG
JpegExporter PdfExporter TiffExporter

‹ ArcPress

IArcPressExporter ArcPres s Exporter Ps Exporter

ArcPres s ExporterJPEG ArcPres s Exporter TIFF

‹ IExporter::StartExporting
‹ Export the FocusMap or the PageLayout

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 13-16

Example: Exporting the layout as a jpeg


Private Sub Export(aLayout As IActiveView, aPath As String, DPI As
Integer)
Dim rectOut As tagRECT
rectOut = aLayout.exportFrame
Dim pExporter As IExporter
Set pExporter = New JpegExporter
Dim pEnv As IEnvelope
Set pEnv = New Envelope
pEnv.PutCoords rectOut.Left, rectOut.Top, rectOut.Right,
rectOut.bottom
pExporter.ExportFileName = aPath
pExporter.PixelBounds = pEnv
pExporter.Resolution = DPI
'Recalc the export frame to handle the increased number of pixels
Set pEnv = pExporter.PixelBounds
Dim xMin As Double, yMin As Double, xMax As Double, yMax As Double
pEnv.QueryCoords xMin, yMin, xMax, yMax
rectOut.Left = xMin
rectOut.Top = yMin
rectOut.Right = xMax
rectOut.bottom = yMax
Dim hDc As Long
hDc = pExporter.StartExporting
aLayout.Output hDc, DPI, rectOut, Nothing, Nothing
pExporter.FinishExporting
MsgBox "Export complete!", vbInformation
End Sub
Introduction to Programming ArcObjects with VBA Working with layout elements 13-16
Exercise 13 overview
‹ Write code that adds an element to the layout
‹ Create a simple text element
‹ Reference StyleGallery items
‹ Add a North Arrow to the layout
‹ Export the layout

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 13-17

Exercise 13: Work with layout elements


In this exercise, you will write a sub procedure that adds an input element at a specified
location on the page. You will also use a function (that has been written for you) to retrieve
an item from the StyleGallery. You will call these functions to 1) reference a north arrow
from the StyleGallery, then 2) add the north arrow and a new text element to the layout page.
As a challenge step, you will work with some of the style and color selector dialogs.

Introduction to Programming ArcObjects with VBA Working with layout elements 13-17
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 13-18

Introduction to Programming ArcObjects with VBA Working with layout elements 13-18
Using tools
Introduction to Programming ArcObjects with VBA

Lesson overview 14-2


Tool events
Getting the user X and Y
Display transformation
contents
14-3
14-4
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
Using tools

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA

Introduction to Programming ArcObjects with VBA Using tools 14-1


Lesson overview
‹ Tool events
‹ IDisplayTransformation
‹ Example tools: Display feedback and rubberbanding
‹ IGraphicsContainer
‹ Refreshing the display
‹ Exercise: Choose a tool to create

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 14-2

Overview
This lesson will discuss the use of UIToolControls in ArcMap. Tool 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.

Introduction to Programming ArcObjects with VBA Using tools 14-2


Tool events
‹ Tools have several event procedures
‹ Events for user interaction
‹ Mouse events: MouseUp, MouseMove, MouseDown, DblClick
‹ Keyboard events: KeyUp, KeyDown

‹ Events for controlling tool behavior


‹ Enabled

‹ CursorID

‹ ToolTip

‹ Message

‹ Close Visual Basic Editor window Built-In


Built-In Cursors
Cursors

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

'Load a file from disk (*.ico or *.cur)


Private Function UIToolControl1_CursorID() As Variant
Set UIToolControl1_CursorID =
LoadPicture("c:\cursors\magnify.cur")
End Function

Introduction to Programming ArcObjects with VBA Using tools 14-3


Getting the user X and Y
‹ Coordinates are passed into a Tool’s mouse events
‹ MouseUp, MouseDown, MouseMove

‹ Returns display units (pixels)

Private
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

Returning the current mouse position


When a user interacts with your tool, the location of their mouse cursor is passed into several of
the tool’s event procedures, such as MouseDown, MouseUp, and MouseMove. These
coordinates are called x and y in the parameter list (see the example above), and indicate the
location of the cursor in display units, called pixels (short for picture elements).
Display coordinates are radically different from the map coordinates used to measure
geographic data. The size of a pixel will vary with the resolution of your monitor, and the value
of y increases as you move down from the origin (0,0), which is in the upper-left of the display.

Introduction to Programming ArcObjects with VBA Using tools 14-4


Display transformation
‹ Transform coordinates between map and display units
‹ ToMapPoint: Convert a display point (pixels) to a map point
‹ FromMapPoint: Convert a map point to a display point
‹ TransformCoords: Return map coordinates from a set of display
coordinates or vice versa

‹ Using mouse input


‹ Mouse clicks are captured in pixels
‹ GIS works in map coordinates

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 14-5

Because you will most often need the location of mouse interaction in map units as opposed to
display units, there are methods on the ArcMap display for 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.

Introduction to Programming ArcObjects with VBA Using tools 14-5


Convert display coordinates to map units
‹ Use IDisplayTransformation::ToMapPoint
‹ Returns a point in map units
Dim pMxApp As IMxApplication
Set pMxApp = Application
Dim pPnt As IPoint

Set pPnt = pMxApp.Display.DisplayTransformation.ToMapPoint(x, y)

MsgBox "Longitude = " & pPnt.x


MsgBox "Latitude = " & pPnt.y

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 14-6

DisplayTransformation
The DisplayTransformation object, which can be accessed 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).

Introduction to Programming ArcObjects with VBA Using tools 14-6


Example: Rubberbanding
‹ Declare module-level variable in General Declaration
Private m_pRubberBand As IRubberBand

‹ Initialize in tool’s Select event


Set m_pRubberBand = New RubberLine
'or RubberPolygon or RubberEnvelope
‹ Implement in tool’s MouseDown event
‹ Store returned geometry in an Object variable
Set pLine = m_pRubberBand.TrackNew (pDisplay, pSymbol)
'or TrackExisting

IDisplayFeedback shows user interaction with geometry (Moving, resizing)

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 14-7

Working with tools


Tool controls can implement several event procedures. To share variables between these
procedures, use module-level variables.
Most often, module-level variables are initialized when the tool is initially selected, the Select
event procedure. While the Visual Basic Editor is open, tool controls are in design time mode.
To properly capture your events and resolve run time errors, completely close the Visual Basic
Editor window and reselect your tool (fire the Select event to re-initialize module-level
variables).

IRubberBand properties and methods


The IRubberBand interface is implemented by several sub-classes of the abstract RubberBand
class, such as: RubberEnvelope, RubberLine, RubberPoint, and RubberPolygon. This common
interface has the following methods for working with a RubberBand object:
• TrackExisting: Call to move or reshape an existing shape
• TrackNew: Call to rubberband a new shape
When tracking a RubberBand object, the geometry corresponding to the particular RubberBand
coclass is returned (a Line from a RubberLine, a Polygon from a RubberPolygon, etc.).

Display Feedback
The DisplayFeedback objects are used to give users an interactive 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.

Introduction to Programming ArcObjects with VBA Using tools 14-7


IGraphicsContainer
‹ Supported by Map and PageLayout
‹ Also returned by IActiveView :: GraphicsContainer

MxDo c ume nt
‹Manage elements
‹AddElement, AddElements,
‹ DeleteElement, DeleteAllElements
Pag e Layo ut
IGraphicsContainer

‹Change display order *


IGraphicsContainer Map
‹BringToFront, BringForward
‹SendToBack, SendBackward
‹PutElementOrder

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

Introduction to Programming ArcObjects with VBA Using tools 14-8


Managing graphics
'Remove
'Remove all
all elements
elements from
from the
the Map
Map –or-
–or- Layout
Layout
Set
Set pMxDoc
pMxDoc == ThisDocument
ThisDocument
pMxDoc.ActiveView.GraphicsContainer.DeleteAllElements
pMxDoc.ActiveView.GraphicsContainer.DeleteAllElements
pMxDoc.ActiveView.Refresh
pMxDoc.ActiveView.Refresh

'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

Adding graphics to a map


The IGraphicsContainer interface adds elements (i.e., graphics) to a PageLayout. The Map
class also supports the IGraphicsContainer interface. Many of the same graphic elements that
you add to a layout (text, markers, polygons, etc.) can also be added directly to a Map.
Adding an element to a Map is the same as adding one to a layout, except the geometry
defining the element’s position should be in map units rather than page units (e.g., inches).

Introduction to Programming ArcObjects with VBA Using tools 14-9


Refreshing the display
‹ IActiveView::Refresh
‹ Redraws entire display (not the Table of Contents)

‹ IScreenDisplay::Invalidate
‹ Redraws a specified rectangle (envelope)

‹ IMxDocument::UpdateContents
‹ Notifies the document that its contents have changed
‹ Refreshes the Table of 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

Introduction to Programming ArcObjects with VBA Using tools 14-10


Partially refresh the display
‹ You may need to refresh only a portion of the display
‹ Area covered by a new graphic element
‹ More efficient than refreshing entire display

‹ 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.

Introduction to Programming ArcObjects with VBA Using tools 14-11


Exercise 14 overview: Choose one
14A – Create a tool to draw simple graphics
‹ Transform a display point to a map point
‹ Add a new point graphic to the display
‹ Change symbol color with a keystroke

14B – Make a Parcel Proximity tool to make a selection


‹ Transform a display point to a map point
‹ Buffer the point (ITopologicalOperator)
‹ Make a selection using spatial criteria (SpatialFilter)
‹ Display the selected parcels

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 14-12

Exercise 14: Create a tool to draw point graphics


In this exercise, you will have a choice of creating one of two tools that allow the user to
interact with the map display.
14A—This exercise has you create a tool for interactively adding point graphics to the display.
You will allow the user to change the color of point symbols by pressing a key on the keyboard
while the tool is active. You will write code for the following UIToolControl event procedures:
• Select
• MouseUp
• MouseDown
• MouseMove
• KeyUp
• KeyDown
14B—This exercise will have you create a tool for making an interactive selection. You will
buffer the user’s mouse click by a specified distance, then use the buffer polygon to select
surrounding features (parcels). Although this exercise does not expose you to as many tool
event procedures, it does get your hands on some new interfaces and objects, such as:
• ITopologicalOperator
• SpatialReference
• ISelectionEnvironment
• ILinearUnit

Introduction to Programming ArcObjects with VBA Using tools 14-12


Data management
Introduction to Programming ArcObjects with VBA

Lesson overview 15-2


Name objects
Object Model overview: Name
classes
contents
15-3

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

Introduction to Programming ArcObjects with VBA Data management 15-1


Lesson overview
‹ Using Name objects
‹ Converting data formats
‹ Editing with cursors
‹ Update

‹ Insert

‹ Adding fields to an existing dataset


‹ Creating and applying domains

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 15-2

Overview
There are a variety of ways to manipulate existing data using 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

Introduction to Programming ArcObjects with VBA Data management 15-2


Name objects
‹ Names are placeholders for the objects they represent
‹A lightweight version
‹ Limited number of methods and properties available
‹ Use IName::Open to instantiate the object represented

‹ Use to represent new or existing datasets, workspaces,


relationship classes, etc.
‹ Used …
‹ For quickly browsing workspace contents
‹ As input arguments for data conversion

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 15-3

Name dropping
An ArcObject Name object is a lightweight representation of an 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.

Introduction to Programming ArcObjects with VBA Data management 15-3


Object Model overview: Name classes

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

Set pWSFactory = New ShapefileWorkspaceFactory


Set pWS = pWSFactory.OpenFromFile("C:\Student\IPAO\Data\Africa", Application.hWnd)
Set pEnumDSNames = pWS.DatasetNames(esriDTFeatureClass)
Set pDSName = pEnumDSNames.Next
Do Until pDSName Is Nothing
If pDSName.Name = "AfricanCities" Then
Dim pName As IName
Set pName = pDSName 'Å--- QueryInterface
Set pCities = pName.Open
Exit Do
End If
Set pDSName = pEnumDSNames.Next
Loop
End Sub

Introduction to Programming ArcObjects with VBA Data management 15-4


Creating a DatasetName
‹ Many creatable CoClasses
‹ Specify the workspace
‹ Use a WorkspaceName object

‹ Specify the filename


‹ New or existing
'Create
'Create aa new
new FeatureClassName
FeatureClassName
Dim
Dim pFCName As
pFCName As IDataSetName
IDataSetName
Set
Set pFCName
pFCName == New
New FeatureClassName
FeatureClassName

'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

Working with DatasetNames


A common use of Name objects is to specify that a new dataset be created on disk. The required
input and output dataset arguments for data conversion, for example, are satisfied using
DatasetName objects rather than full Dataset objects. Because each of the subtypes of
DatasetName are coclasses, they can be created using the New keyword. Once created,
properties of the Name can be set in order to represent a dataset on disk.

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"

Introduction to Programming ArcObjects with VBA Data management 15-5


Data manipulation objects
‹ FeatureDataConverter, ExportOperation
‹ Convert between coverage, shapefile, and geodatabase

‹ ObjectLoader
‹ Appends data to an existing feature class or table

‹ Related objects
‹ FieldChecker: Identifies problems with field names
‹ EnumInvalidObject: An enum of features that were invalid during
conversion or loading

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 15-6

Convert, export, load


FeatureDataConverter is a coclass that can convert feature classes, feature datasets, or tables to
new output datasets. Use a FeatureDataConverter object to convert individual feature classes and
tables, or even entire feature datasets (e.g., ArcInfo coverages). The FeatureDataConverter
object lets you convert data between geodatabases, shapefiles, and coverages. Most types of
feature data are currently supported (except for annotation). FeatureDataConverter is suitable
for loading large amounts of data. When importing to a geodatabase, you can specify an interval
for committing data; you can also specify an ArcSDE configuration keyword to control specific
storage parameters for an ArcSDE geodatabase.
ExportOperation is a coclass that can be used to export a feature class or a table. The
ExportOperation coclass offers similar functionality to the feature data converter but in a
simplified form. It corresponds to the export data function available in ArcMap by right-clicking
on a layer in the Table of Contents.
ObjectLoader is used to append records from one table (or feature class) to another. The
IObjectLoader interface contains a single method, LoadObjects.

Validating fields and records


A FieldChecker object can be used to validate a fields collection. This can be especially useful
when converting data between formats, as some datasets might contain field names that are
illegal in other formats. A FieldChecker will produce a new fields collection with standard fixes
for invalid fields it encounters (by adding an underscore to the field name, for example, UID_).
The FieldChecker will provide standard names for geometry and OID fields when converting to
geodatabase format (Shape and OBJECTID).
When loading or converting features using the ObjectLoader or FeatureDataConverter, an enum
of invalid objects is returned (IEnumInvalidObject). Using this enum, a programmer can easily
see which objects (rows or features) could not be loaded or converted.

Introduction to Programming ArcObjects with VBA Data management 15-6


Converting feature classes
‹ IFeatureDataConverter::ConvertFeatureClass
‹ Converts an input feature class to a new output

‹ Required arguments
‹ Input and output FeatureClassNames
‹ Output FeatureDatasetName
‹A QueryFilter
‹ 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

Using the FeatureDataConverter


The FeatureDataConverter object allows a programmer to export feature classes, tables, or feature datasets to a new
output (of the same or different format). FeatureDataConverter is a coclass, so it can be created with the new
keyword. Using the IFeatureDataConverter interface, you can call one of three methods to convert data:
ConvertFeatureClass, ConvertFeatureDataset, or ConvertTable. Use the IFeatureProgress interface to track the
progress of a conversion.
Below is a description of the required arguments for IFeatureDataConverter :: ConvertFeatureClass.
• InputDatasetName: IFeatureClassName—a Name object that specifies the feature class to be converted.
• InputQueryFilter: IQueryFilter—a QueryFilter object used to define a subset of features to be converted.
• outputFDatasetName: IFeatureDatasetName—a Name object that defines the (new or existing) feature dataset
into which the converted feature class will be written.
• outputFClassName: IFeatureClassName—a Name object that defines the new output feature class.
• OutputGeometryDef: IGeometryDef—a GeometryDef object that defines the spatial reference for the output
feature class. If Nothing is used for this argument, the spatial reference of the output feature dataset or the input
feature class will be used.
• OutputFields: IFields—a fields collection for the output feature class. If simply exporting a feature class to the
same format, the fields collection from the input feature class can be used. If exporting between formats, it is a
good idea to use a FieldChecker object to make sure the fields are valid for the output format.
• configKey: String—a string that specifies an ArcSDE configuration keyword.
• FlushInterval: Long—an integer that specifies the interval for committing features to the new feature class
(when exporting to geodatabase).
• parentHWnd: Long—an integer specifying the application’s window handle (you will usually use
Application.hWnd to satisfy this argument).
IFeatureDataConverter :: ConvertFeatureClass returns IEnumInvalidObject, which is an enum of all features that
could not be converted.

Introduction to Programming ArcObjects with VBA Data management 15-7


Exercise 15A overview
‹ Convert an ArcInfo coverage to a Personal Geodatabase
‹ IFeatureDataConversion :: ConvertFeatureClass

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 15-8

Introduction to Programming ArcObjects with VBA Data management 15-8


Editing with a cursor
‹ Update and Insert Cursors
‹ Faster than using ITable::CreateRow, ITable::Store
‹ Much more efficient for large datasets

‹ Use to add, delete, or modify rows or features


‹ ICursor::InsertRow (IFeatureCursor::InsertFeature)
‹ ICursor::DeleteRow (IFeatureCursor::DeleteFeature)
‹ ICursor::UpdateRow (IFeatureCursor::UpdateFeature)

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 15-9

Using a cursor to edit records


You have already learned to create records (rows or features) using methods such as CreateRow
and CreateFeature. You have learned to change field values by setting properties such as Value
and Shape, and to commit your edits by calling the Store method.
Although the above steps work fine for editing a table or feature class, you may find it much
more efficient to use a cursor or feature cursor, particularly when editing a large number of
records; you can expect a cursor to perform the edits as much as 2,000 times faster.

Introduction to Programming ArcObjects with VBA Data management 15-9


Editing cursors
‹ Determined by the method used to return the cursor
‹ Update cursor Dim
Dim pCursor
pCursor As
As IFeatureCursor
IFeatureCursor
‹ Update method Set
Set pCursor
pCursor == pFClass.Update(pQFilter,
pFClass.Update(pQFilter, False)
False)

‹ Use to update or delete records in the database

‹ Insert cursor Dim


Dim pCursor
pCursor As
As IFeatureCursor
IFeatureCursor
‹ Insert method Set
Set pCursor
pCursor == pFClass.Insert(True)
pFClass.Insert(True)

‹ Use to insert new records into the database

‹ Search cursor Dim


Dim pCursor
pCursor As
As IFeatureCursor
IFeatureCursor
‹ Search method Set
Set pCursor
pCursor == pFClass.Search(pQFilter,
pFClass.Search(pQFilter, True)
True)

‹ Use for read-only analysis of a record subset

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 15-10

Types of cursors
There are three types of cursor objects that can be obtained 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.

Introduction to Programming ArcObjects with VBA Data management 15-10


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 return an automation/unspecified
error). 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 Data management 15-11


Example: Updating misspelled attributes
Dim pQFilt As IQueryFilter
Set pQFilt = New QueryFilter
pQFilt.WhereClause = "StateName = ‘newmexico’"

Dim pUpCursor As IFeatureCursor


Set pUpCursor = pFClass.Update(pQFilt, False)'Only "newmexico"

Dim pFeature As IFeature


Set pFeature = pUpCursor.NextFeature
Do Until pFeature Is Nothing
pFeature.Value(3) = "New Mexico" 'Fix misspelling
pUpCursor.UpdateFeature pFeature 'Update the record
Set pFeature = pUpCursor.NextFeature 'Move to the next
Loop

MsgBox "Features have been updated"

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 15-12

Example: Updating records with a cursor


When producing an update cursor, you can specify a query filter to restrict the records returned.
In the example, the query filter is used to make a subset of misspelled records. Remember: to
access all records inside a cursor, you need to use a Do While or a Do Until loop.
Before entering the loop, the first feature is pulled out of the FeatureCursor
(pFCursor.NextFeature) and stored in a variable (pFeature). The loop will then check to see if
pFeature is Nothing, and until it is, the loop will continue to execute. If, at this point, your
FeatureCursor had no records (i.e., nothing met the search criteria) the first object retrieved from
the cursor would be Nothing, and therefore the body of the loop would never be executed.
Inside the loop, a new value is written to the feature’s fourth field (presumably, the StateName
field). The dataset is then updated by calling the UpdateFeature method on the cursor. The next
feature is again pulled from the cursor by calling the NextFeature method.
Once the loop is complete, a message box is displayed telling the user that features were
successfully updated.

Introduction to Programming ArcObjects with VBA Data management 15-12


Adding a field
‹ ITable::AddField to add a field to an existing dataset
‹ Do not add a field to the Fields collection

‹ Use an Update Cursor to calculate values for the field


Dim
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
End
End With
With
pTable.AddField
pTable.AddField pAverageFld
pAverageFld

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 15-13

Adding a new field to an existing table or feature class


When producing fields for a new table or feature class, a programmer can simply make a new
field, set its properties, then add it to the Fields collection. The process for creating a new field
in an existing dataset is similar, except there is no need to deal with the Fields collection. After
making a new field (using the New keyword) and setting its properties, simply call the AddField
method on ITable or IFeatureClass, passing in the new Field object as the required argument.
After adding a field to an existing dataset, the most efficient way to calculate its values is by
using an update cursor.

Introduction to Programming ArcObjects with VBA Data management 15-13


Creating a domain
‹ Domain is an abstract class with two creatable subtypes
‹ RangeDomain: Minimum and maximum values
‹ CodedValueDomain: List of appropriate values

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

Making a new range or coded value domain


In ArcGIS, attribute domains can be used with geodatabase tables or feature classes to enforce
appropriate values for an attribute. Domains are defined at the geodatabase level, and can be
applied to any number of fields in any of that geodatabase’s tables.
Domain is an abstract class that has two creatable subtypes: RangeDomain and
CodedValueDomain. Use the RangeDomain object to define a range of acceptable values
(minimum and maximum) for a numeric attribute, and a CodedValueDomain object to define a
finite list of acceptable (string or numeric) values. For any Domain that you create, you will
need to specify the type of field it is designed for. If, for example, you create a domain for
integer fields (esriFieldTypeInteger), it will not be available for use with a field defined as
double data type.

Introduction to Programming ArcObjects with VBA Data management 15-14


Adding a domain to a database
‹ Domains must live in a geodatabase
‹ Add to the database before assigning it to a field
‹ IWorkspaceDomains::AddDomain

Dim
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

Adding a domain to a geodatabase


After creating a domain, you cannot simply apply it to a field. Domains must be associated with
a geodatabase. After a domain is added to a geodatabase, it can then be applied to any number of
fields that exist in any of the geodatabase’s tables or feature classes (assuming the field is of the
right data type). To add a domain to a geodatabase, use the AddDomain method on the
IWorkspaceDomains interface, as shown in the example above.
Note: domains cannot be used for shapefile or ArcInfo coverage data.

Introduction to Programming ArcObjects with VBA Data management 15-15


Assigning a domain to a field
‹ IFieldEdit::Domain property

Dim
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.

Introduction to Programming ArcObjects with VBA Data management 15-16


Exercise 15B overview
‹ Load data using a cursor
‹ IFeatureCursor :: InsertFeature

‹ Add a new field to an existing table


‹ Calculate values for a field using a cursor
‹ IFeatureCursor :: UpdateFeature

‹ Create and apply an attribute domain

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 15-17

In this exercise, you will work with the ArcObjects discussed in this lesson 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

Introduction to Programming ArcObjects with VBA Data management 15-17


Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 15-18

Introduction to Programming ArcObjects with VBA Data management 15-18


Application
Introduction to Programming ArcObjects with VBA

framework and events


Lesson overview 16-2 Inbound and outbound interfaces 16-16
Customizing the user interface
CommandBars class
Types of CommandBar objects
16-3
16-4
16-5
Finding outbound interfaces
Using an outbound interface
Events supported by Map
contents
16-17
16-18
16-19
Components of CommandBar: Capturing object events 16-20
CommandItems 16-6 Coding object events 16-21
Finding a CommandItem 16-7 Exercise 16 overview 16-22
Finding an ArcGIS toolbar or
menu 16-8
Document events 16-9
Example: Displaying a different
context menu 16-10
Displaying a new shortcut menu 16-11
Creating new menus 16-12
Creating commands to execute
macros 16-13
Updating the ArcID module 16-14
Lesson overview 16-15
Application framework
and events

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA

Introduction to Programming ArcObjects with VBA Application framework and ArcObjects events 16-1
Lesson overview
‹ Programming the user interface
‹ Commandbars collection
‹ Displaying existing toolbars and menus
‹ Programmatically 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

Application framework and ArcObjects events


One of the first things you learned in this course was how to modify the user interface using the
VBA Customize dialog box. In this lesson, you will learn how to perform many of the
Customize dialog tasks (adding and removing commands, creating new toolbars, changing
command properties) using Visual Basic code.
This section will cover:
• The CommandBars collection
• Creating new CommandBars (toolbars, menus, and context menus)
• Creating new commands (CommandItems)
• Creating and controlling the display of context menus

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

‹ Use drag-and-drop with Customize dialog box


‹ Lesson 2
‹ Static changes persisted in document
‹ Similar to Design mode in Visual Basic

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

‹ Use to create a CommandBar


‹ ICommandBars::Create

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 16-4

CommandBars
The CommandBars object is a collection of all the command bars (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

MacroItem UIControl COM Command

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 16-6

Components of a CommandBar
A CommandBar object is composed of CommandItems. 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).

Using the ArcID module


Rather than having to locate these unique identifiers, an ArcObject programmer can use the
ArcID module (available in the Normal.mxt and Normal.gxt templates) to look up the required
UID using a name that identifies a particular command. The names used by the ArcID module
are generally the name of the command category, followed by the name of the command itself
(e.g., File_AddData).

Introduction to Programming ArcObjects with VBA Application framework and ArcObjects events 16-7
Finding an ArcGIS toolbar or menu
‹ The CommandBar class implements ICommandItem
‹ Use ArcID module to find a CommandBar
‹ ICommandBar::Dock (dockflags, [referenceBar])
‹ Dockflags: Floating, docked, hidden, etc.
‹ [referenceBar]: (optional) Place 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.

Controlling toolbar display


Call the Dock method on the ICommandBar interface to place a command bar in a specified
location, or have it be free-floating.
The esriDockFlags constants specify whether a command bar is visible or floating and where it
should be docked on the application window. Optionally, you can specify another toolbar
relative to which the toolbar should be docked.

Example: open the Tools toolbar, dock it next to the Editor 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

End False == let


False let ArcMap
ArcMap display
display its
its menu
menu
End Function
Function

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 16-10

Dynamically changing the pop-up menu


To control which pop-up (i.e., context) menu is displayed when a user right-clicks on the map
display, you must add logic to the MxDocument_OnContextMenu event procedure. This event
fires when the display is right-clicked with the mouse and before a menu is displayed.
The OnContextMenu event has two parameters that are passed in: the x- and y-coordinates (in
display units) where the mouse was right-clicked. As a programmer, you could use these
coordinates to see where (or what) the user clicked. Using this information, you might choose
to display different menus according to the type of feature that was clicked.
The event procedure returns a Boolean result. If you handle the event (display a different pop-
up), you must return True to prevent ArcMap from also trying to display a pop-up. Returning
False signals ArcMap to display the standard context menu.

The example
The code above will fire when the map is right-clicked by the user. The ArcMap View menu
will be popped up when the name of 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)

‹ Use CommandBar::Add to add menu choices

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

Creating new shortcut menus


The CommandBars collection can be used to produce new CommandBar objects by calling the
Create method. The Create method has two arguments: the name of the new CommandBar, and
the type (toolbar, menu, or shortcut menu).
The example above creates a new shortcut menu called New. Although the name for a shortcut
menu will never be seen by the user (as it will for a toolbar or menu), it is still a required
parameter for the sake of consistency.

Adding CommandItems to a CommandBar


The ICommandBar interface uses the Add method to place CommandItems on a CommandBar.
The Add method has one required argument: a UID that identifies the CommandItem to add.
Optionally, an index indicating the position of the command can also be specified. If no index
is given, the new command will be added to the end (or bottom) of the CommandBar.
In the example above, the ArcID module is used to reference the Add Data command. This
item is then added to the shortcut menu. Notice that the properties (such as the icon and label)
are already set for this command.

Introduction to Programming ArcObjects with VBA Application framework and ArcObjects events 16-11
Creating new menus
‹ Menus are created by a CommandBar
‹ Menus must reside on an existing CommandBar

Dim
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

Creating commands that execute existing macros


Use the CreateMacroItem method on the ICommandBar interface to add a macro from your
map to a toolbar, menu, or shortcut menu.
The required arguments for the CreateMacroItem methods are:
• Name—a string to appear with the command item (‘myMacro’ in the example above).
• FaceID—an integer that specifies a standard ArcGIS icon for the command item.
• Macro—a string that identifies the procedure to execute when the command item is
clicked.

Introduction to Programming ArcObjects with VBA Application framework and ArcObjects events 16-13
Updating the ArcID module
‹ Allows imported tools to be identified in ArcID
‹ ICommandBars::Find

‹ Customize dialog box


‹ Options tab
‹ Update ArcID module

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 16-14

Updating ArcID module


Update the ArcID module by using the Customize dialog box (Options tab). By updating the
ArcID module, you are adding the UID that identify any COM classes that have been added to
ArcMap such as custom controls and toolbars.
After updating the ArcID module, you can programmatically access these custom controls as
you do the existing ArcMap controls (ICommandBars::Find).

Introduction to Programming ArcObjects with VBA Application framework and ArcObjects events 16-14
Lesson overview
‹ Customizing the user interface
‹ Commandbars collection
‹ Displaying existing toolbars and menus
‹ Programmatically 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

‹ Search Object Browser with class name to find events

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 16-17

Finding outbound interfaces and events


The object model diagrams list outbound interfaces with a solid (black) pushpin symbol, as
opposed to the familiar hollow (white) pushpin used for the inbound interfaces. Outbound
interfaces are generally named with the word Events in the interface name and contain nothing
but events (no methods and properties). Some events will have parameters that are passed into the
event procedure. The OnContextMenu event listed above, for example, will pass in the x- and y-
coordinates where the user clicked (in pixels). As a programmer writing code for this event, you
could use these parameters.
When searching for events for a coclass in the object browser, search for the class itself, not for
the interface name. The object model might show an interface called IMapEvents, for example.
To find the events for this interface in the object browser, you would search for MapEvents.
Every ArcObjects coclass that implements more than one outbound interface will have a default.
When examining a coclass in the object browser, events for the default outbound interface will be
listed.

Introduction to Programming ArcObjects with VBA Application framework and ArcObjects events 16-17
Using an outbound interface
‹ Declare an object variable using WithEvents
‹ Module-level variable

Private
Private WithEvents
WithEvents m_pMapEvents
m_pMapEvents As
As Map
Map

‹ Declare as the object, not an interface


‹ Declare with an interface only for an inbound interface

‹ Some classes support more than one outbound


interface
‹ Declare as interface name minus the ‘I’

Private
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

Visual Basic and outbound interfaces


Visual Basic only supports one outbound interface (marked as the default outbound interface) per
coclass. To get around this limitation, the coclasses that implement more than one outbound
interface have an associated dummy coclass that allows access to events on a secondary outbound
interface. These coclasses have the same name as the outbound interface they contain, minus
the I.
For example, by checking the OMD, you will notice that the Map coclass implements two
outbound interfaces: IActiveViewEvents and IMapEvents. Because IActiveViewEvents is the
default outbound interface for the Map coclass, you would capture these events like this:
Private WithEvents m_pAVEvents As Map
To capture the events on the secondary outbound interface (IMapEvents), you would declare your
variable like this:
Private WithEvents m_pMapEvents as MapEvents

Determining whether an outbound interface is outbound or not


The Object Model Diagrams will indicate in parentheses whether or not an outbound interface is
the default not.
You may also want to use the ESRI Object Browser to determine whether an outbound interface
is default or not. You can use the ESRI Object Browser by going to Start > Programs > ArcGIS
> Developer Tools > Object Browser. You will use the ESRI Object Browser in the exercise.

Introduction to Programming ArcObjects with VBA Application framework and ArcObjects events 16-18
Events supported by Map
‹ ActiveViewEvents (default)
‹ AfterDraw 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

Events on the Map class


The Map class supports two outbound interfaces. ActiveViewEvents is the default outbound
interface; access these events by declaring a variable (WithEvents) simply as Map. MapEvents is
a secondary outbound interface that supports some additional events. To access these events,
declare a variable (WithEvents) as MapEvents (do not declare it as IMapEvents).
Map events allow you to respond to actions taken by a user interacting with the active data frame.

Introduction to Programming ArcObjects with VBA Application framework and ArcObjects events 16-19
Capturing object events
‹ Initialize the variable declared WithEvents
‹ Must initialize (set) or events will not be fired
‹ Commonly initialized when the document opens

Private
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)

‹ Write code to respond to the event

Object
Object Procedure
Procedure

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 16-21

Writing event code


After declaring a variable using the WithEvents keyword, you will have access to all events
supported by that outbound interface. To code a specific event procedure, pull down the object
list on the left-hand side of the code module and choose your WithEvents variable. You will then
see each event supported by this object in the procedure list (right-hand side of the code module).
By choosing an event, the stub code will automatically be provided for the procedure. Code you
write inside the stubs will execute each time the corresponding object event fires.
Unlike a COM developer implementing an inbound interface, a programmer implementing an
outbound interface does not have to write code for every event procedure. When implementing
an outbound interface, as in the example above, you can pick and choose which events you want
to provide code for.

Introduction to Programming ArcObjects with VBA Application framework and ArcObjects events 16-21
Exercise 16 overview
‹ Exercise 16A:
‹ Add CommandItems to a context menu
‹ Add a sub-menu to a context menu
‹ Turn layers on/off from a context menu

‹ Exercise 16B:
‹ Declare a variable as an outbound interface
‹ Initialize a variable to code layer’s events
‹ Set the display extent according to layer visibility
‹ Explore selection and Catalog events

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 16-22

Exercise 16A: Programming the user interface


In this exercise, you will create new context menus and menu choices programmatically. You
will write logic to dynamically decide which context menu to display. You will also write code
to add the names of all layers in the map to a context menu, then toggle their visibility by
calling a macro in the project.

Exercise 16B: Coding ArcObjects events


In this exercise, you will write code to capture some ArcObjects events. You will write an
application that automatically changes the extent of the map display according to whether a
particular layer is visible or not. When the layer is turned on (i.e., visible), you will zoom the
extent to the layer. When it is off, you will zoom back to the full extent.
As a challenge, you may try to program selection events in ArcMap and ArcCatalog.

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

Introduction to Programming ArcObjects with VBA ArcObjects Beyond VBA 17-1


Lesson overview
‹ Creating COM classes with Visual Basic
‹ Visual Basic versus VBA
‹ Building a COM class with Visual Basic
Š Referencing the ArcObjects libraries
Š Implementing an interface
Š Delivering your class
‹ ArcObjects interfaces
Š Where can your component plug in?

‹ ArcGIS Engine Developer Kit


‹ ArcGIS Server

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 17-2

Overview
This optional lesson covers the use of standalone Visual Basic to 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.

Introduction to Programming ArcObjects with VBA ArcObjects Beyond VBA 17-2


Visual Basic versus VBA

Visual Basic VBA

Control Arrays Yes No

Integrated Debugging No Yes

Preset Variables No Yes

Import VBA Forms Yes __

Import VB Forms __ No

Ability to Compile Code Yes No

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 17-3

Visual Basic versus Visual Basic for Applications


From a syntactical standpoint, there is virtually no difference between programming in Visual
Basic and programming in VBA. In fact, the code you have written during this course using
VBA could be ported to Visual Basic with only minor modifications.
The table above gives a basic overview of some of the differences between VB and VBA. The
most important difference is standalone Visual Basic’s ability to compile code to disk as a
dynamic-link library (DLL) or executable file (EXE). As you know, all code in VBA must be
stored inside a document, such as a map file (mxd) or template (such as normal.mxt or
normal.gxt). The advantage of having your code compiled (as a DLL, for example) is that it is
easier to share with other users, and it is much more secure (those using your DLL or EXE
cannot see or modify the actual code).

Introduction to Programming ArcObjects with VBA ArcObjects Beyond VBA 17-3


Remember COM?
‹ COM is a standard for creating classes
‹ Classes can be reused between applications
‹ Independent of programming language

‹ Because of COM, you can design a component that


plugs into ArcGIS
‹ ArcGIS Desktop can be extended with COM and .Net
APIs
‹ This lesson will focus on COM with Visual Basic

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 17-4

Remain COM
Remember that the component object model (COM) is not a programming 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.

Introduction to Programming ArcObjects with VBA ArcObjects Beyond VBA 17-4


Basic steps: Building a COM component
1. Create a new COM project
2. Create a COM Class
3. Reference the ArcObjects libraries
4. Implement the required interface(s)
5. Compile the component as a DLL
6. Register your component with ArcGIS

‹ The steps are the same regardless of the language


‹This exercise and lecture shows Visual Basic 6.0

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 17-5

It’s as easy as 1, 2, 3, 4, 5, 6
OK, so it is not as easy as some of the other 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.

Introduction to Programming ArcObjects with VBA ArcObjects Beyond VBA 17-5


1) Create a new COM project
‹ Create a new Visual Basic ActiveX DLL project
‹ Give project meaningful name

ActiveX
ActiveX DLL
DLL

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 17-6

Creating a new Visual Basic project


To design new COM components, you need to make sure you create a new ActiveX DLL
Visual Basic project, as opposed to a standard executable.
When creating your new VB project, make sure you provide meaningful names for the project
and for each class that you create. The name of the project will also be the default name of the
DLL when it is compiled. Each class in your project will be an individual component in your
DLL. If I create a class called Class1 that is going to be a custom control for example, my new
control would also be called Class1 inside my DLL.
A single DLL can contain several classes (i.e., components). It is not necessary, therefore, to
create a new ActiveX DLL project for each component you want to create. If needed, you
could deliver dozens of commands, toolbars, and other components in a single DLL.

Introduction to Programming ArcObjects with VBA ArcObjects Beyond VBA 17-6


2) Create a COM class
‹ Class scope controlled by Instancing property
‹ Use MultiUse to make a public creatable class

Each 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.

Instancing property settings


• Private: Class is only visible to the Visual Basic project.
• PublicNotCreatable: Interface and coclass defined; coclass is not creatable using the Visual
Basic New keyword.
• MultiUse: Interface and coclass defined; coclass is creatable.
• GlobalMultiUse: Lets the developer use a reference without declaring it.

Default interface
When you implement a COM object using a class module in Visual Basic, the object will have
a default interface that has the same name as the 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.

Introduction to Programming ArcObjects with VBA ArcObjects Beyond VBA 17-7


3) Reference the appropriate libraries
‹ Project > References > ESRI libraries
‹ Referenced libraries depend on what you are implementing
‹ Also reference any other libraries required by your component

esriSystemUI.olb
esriSystemUI.olb

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 17-8

Reference the ArcObject library


Remember that when you are programming in ArcMap or ArcCatalog, you do not need to
explicitly reference the ArcObject libraries. This is not the case when programming in a
standalone programming environment such as Visual Basic. Any additional libraries that are
required (apart from the Visual Basic library) need to be explicitly brought into your project.
To reference additional class libraries, choose References from the Project menu. Each
ArcObjects class that you work with is stored in a specific library. You can find out which
library a class belongs in by looking at the help or Object Model Diagrams. You may also use
the Library Locator, which is a utility that can be found in C:\<InstallDirectory>\ArcGIS\
DeveloperKit\Tools to find which library a class or interface belongs in. Place a check next to
the library listings you will be using in this project to reference, then click OK.

Introduction to Programming ArcObjects with VBA ArcObjects Beyond VBA 17-8


4) Implement the required interface(s)

‹ Give
‹ 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

Implement required ArcObject interfaces


To make sure that your component will be understood by the ArcMap or ArcCatalog
application, you need to implement an interface (or interfaces) appropriate for your component.
In the example above, if ArcMap is to place a new control on its user interface, it needs to be
able to ask the control for some basic properties, such as What image should be displayed on
the control? (Bitmap property), What text should be displayed when a user hovers over the
control with the mouse? (ToolTip), and most importantly, What should I do when the control is
clicked? (OnClick event procedure). As a programmer, you answer these questions by writing
code for the proper interface.

Introduction to Programming ArcObjects with VBA ArcObjects Beyond VBA 17-9


4) Implement the required interface(s)
‹ Implements statement
‹ First line of code in your class module
‹A contract to code everything on the interface
Must
Must stub
stub out
out code
code for
for all
all
methods
methods and
and properties
properties

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 17-10

Write code to make your component work


After deciding which interfaces your component needs to implement, the next step is to write
code for every method and property on each interface. To satisfy the rules of COM, this simply
means having all method and property procedure stubs in your class module.
Upon entering the implements statement in the general declarations (top) portion of the class
module, you will be able to choose the interface from the object list (upper-left), and then see
all its methods and properties in the procedure list (upper-right). You may need to provide code
for only a handful of these procedures in order to make your control function to your liking.
You must, however, have stub code for at least each member on your implemented interfaces
before your DLL will compile.

Introduction to Programming ArcObjects with VBA ArcObjects Beyond VBA 17-10


Referencing the Application
‹ OnCreate procedure passes in a reference (hook)
‹ Cannot use Application or ThisDocument variables

‹ Store hook in a module-level variable


‹ Will be used throughout your component (e.g., OnClick)

‹ Your way into the object model

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 17-11

Hooking into the ArcMap or ArcCatalog application


A major difference that you will find when programming in a standalone environment such as
Visual Basic as opposed to VBA is the lack of easily available preset variables. When
programming in ArcMap or ArcCatalog, you can jump into your code by using the preset
Application or ThisDocument variables. To get access to the current application or document
from your COM component, you will need to use another technique.
Most ArcObject interfaces that your custom components implement pass in a reference to the
application object in one of their event procedures. On the ICommand interface, the OnCreate
event passes in a parameter called hook that is mysteriously referred to as an Object (see the
example above). This object is the equivalent of the Application preset variable. In order to use
this object throughout your component, however, you will need to store it in a module-level
variable as shown above (m_pMxApp).
The OnCreate event fires when a user drags the command from the Customize dialog box to a
toolbar or menu, or when a map containing the control is opened.

Introduction to Programming ArcObjects with VBA ArcObjects Beyond VBA 17-11


Example: Branching in a COM component

Perform
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

Creating an all-purpose command


The example above shows how to create a command that works in both ArcMap and
ArcCatalog. This class implements the ICommand interface, which is required for all ArcMap
and ArcCatalog commands.
When the OnCreate event fires, the TypeOf statement is used to see if hook is the ArcMap or
ArcCatalog application. A string variable is set to record which application the control is being
used in.
The OnClick event uses the string variable (m_strApp) to see if the control is being used in
ArcMap or ArcCatalog. Depending on the application, the control will serve a different
purpose: reporting the selected layer in ArcMap, and reporting the selected file in ArcCatalog.

Introduction to Programming ArcObjects with VBA ArcObjects Beyond VBA 17-12


5) Compile your component DLL
‹ File > Make DLL
‹ Compiles your code and writes it to disk as a DLL
‹ Dynamic linked library

‹ Common compile errors


‹ ArcObjects library was not referenced
‹ Did not fully implement an interface
‹ The component is in use (ArcMap or ArcCatalog): only for
recompile

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 17-13

Compiling the COM DLL


Once you have written all the required code to make your control work inside of ArcGIS, you
need to compile the project to a DLL on disk. Choose ‘Make <project name>’ to compile your
DLL, specifying an output file location. If there are no syntax errors in your code, the DLL will
compile, otherwise VB will report an error.

Common errors encountered when compiling

• ‘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.

• ‘User-defined type not defined’—you probably forgot to reference a required library


(esriSystemUI.olb, for example). If you forget this, you should be able to clue in quickly as
you would not see code completion anyway.

• ‘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.

Introduction to Programming ArcObjects with VBA ArcObjects Beyond VBA 17-13


6) Registering your COM component
‹ Customize dialog box (Add from file)
‹ ArcGIS will automatically register the component

‹ Component category manager

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 17-14

Registering you COM DLL


Before you can use your custom component in ArcMap or ArcCatalog, you need to make sure
it is registered with your operating system. There are three ways in which you can register a
component.
• Customize dialog box—when you use the Add from file button to bring in a component, your
component DLL is automatically registered.
• Component category manager—the component category manager allows you to add and
remove ArcGIS components. Components are organized into various categories. By adding
your DLL to the proper category, your components will be incorporated into ArcGIS. To add
a new edit task that you have created, for example, add your component to the ESRI Edit
Tasks category (as in the example above).

Introduction to Programming ArcObjects with VBA ArcObjects Beyond VBA 17-14


Where can COM components plug in?
Edit
Edit Task
Task

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

COM components on the ArcMap interface


Here are some examples of components that can be added to ArcMap
• Command—a button, tool, or menu choice. To create this component, you must implement
ICommand, and may also need to implement ITool, IToolCommand, or both.
• Edit task—a task that works with the ArcMap Editor in conjunction with the sketch tool. It
must implement IEditTask.
• Table of Contents tab—an additional tab on the ArcMap Table of Contents that implements
the IContentsView interface.

Introduction to Programming ArcObjects with VBA ArcObjects Beyond VBA 17-15


Where can COM components plug in?

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

More custom components for ArcMap …


Some additional places to use custom COM components:
• Class extension—a component that works with a dataset (feature class or table) to provide
limited custom behavior (attribute calculation or validation, for example). A class extension
must implement IClassExtension, and may also implement IPropertyInspector,
IObjectClassValidation, or several others.
• Tool control—a custom control that extends the abilities of simple buttons or tools. Must
implement the ICommand and IToolCommand interfaces.
• Network trace task—a task on the Utility Network toolbar for solving network problems.
Implements the ITraceTask interface.

Introduction to Programming ArcObjects with VBA ArcObjects Beyond VBA 17-16


Resources for creating custom components
‹ Instructor-led course
‹ Extending the ArcGIS Desktop Applications

‹ http://arcgisdeveloperonline.esri.com
‹ ArcGIS Desktop Developer’s Guide
‹ Samples

‹ Extending ArcObjects

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 17-17

Extending ArcGIS applications resources


The Extending the ArcGIS Desktop Applications instructor-led course will supply a wealth of
information to get you started extending ArcGIS applications. This course will cover a variety
of COM APIs, including Visual Basic 6 and .NET languages.
ArcGIS Developer Online also provides a developers guide, many samples and online books to
help assist you in your development tasks.

Introduction to Programming ArcObjects with VBA ArcObjects Beyond VBA 17-17


Exercise 17 (Optional): Building a COM command
‹ Create a new Visual Basic project
‹ ActiveX DLL

‹ Add a new Class module


‹ Reference the appropriate ArcObjects libraries
‹ Implement the ICommand interface
‹ Compile the DLL
‹ Add the control to ArcMap

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 17-18

Exercise 17: creating a COM control in Visual Basic


In this optional exercise, you will use (standalone) Visual Basic to create a new COM DLL.
The COM class you create will implement the required interface for a command that works in
ArcGIS, ICommand. After writing the required code to implement this interface, you will
compile your DLL, and then test it in ArcMap.

Introduction to Programming ArcObjects with VBA ArcObjects Beyond VBA 17-18


Lesson overview
‹ Creating COM classes with Visual Basic
‹ Visual Basic versus VBA
‹ Building a COM class with Visual Basic
Š Referencing the ArcObjects libraries
Š Implementing an interface
Š Delivering your class
‹ ArcObjects interfaces
Š Where can your component plug in?

‹ ArcGIS Engine Developer Kit


‹ ArcGIS Server

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 17-19

Overview
This optional lesson covers the ArcGIS Engine Developer Kit, a new product at ArcGIS 9. This
product allows you to use ArcObjects to build stand alone custom applications.

Introduction to Programming ArcObjects with VBA ArcObjects Beyond VBA 17-19


ArcGIS Engine
‹ There are two parts to ArcGIS Engine
‹ (1) Engine Developer Kit
Š Used by developers
‹ (2) Engine Runtime
Š What the end user needs to run the developer product

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 17-20

ArcGIS Engine is a complete library of embeddable GIS components for developers to build
custom applications. Using ArcGIS Engine, developers can embed GIS 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.

Introduction to Programming ArcObjects with VBA ArcObjects Beyond VBA 17-20


ArcGIS Engine Developer Kit
‹ New developer product that creates standalone desktop
applications
‹ A toolkit for developers (not an end user application)
‹ Cross Platform
‹ COM, .Net, C++(new), Java(new) APIs
‹ Development tools
‹ ArcObjects and Controls
Š Map, PageLayout, Toolbar, TOC,
Reader, Scene, Globe controls

‹ Documentation
‹ Sample code
‹ Help and tutorials

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 17-21

The ArcGIS Engine Developer Kit provides the developer with many resources to 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.

Introduction to Programming ArcObjects with VBA ArcObjects Beyond VBA 17-21


Engine Runtime
‹ Runtime license needed for all custom applications built
with Engine Developer Kit
‹ Licensing:
‹ Standard Engine Runtime
ŠView and author maps, query, analysis, simple editing
‹ Engine Runtime Options
ŠGeoDatabase Update
ŠSpatial
Š3D
ŠStreetMap

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 17-22

ArcGIS Engine Runtime


All applications built with the Engine Developer Kit will need the ArcGIS Engine Runtime or
ArcGIS Desktop with the appropriate level of license to execute successfully. There are
different license levels for the Engine Runtime. The standard Engine Runtime provides core
functionality of all ArcGIS applications. This standard Engine Runtime can be enhanced with
options for full read-write access of the enterprise Geodatabase supports, as well as advanced
functionality for 3D visualization and spatial analysis. Visit the ArcGIS Engine Developer
Guide for a complete listing of functionality for the different runtime options.
To obtain the ArcGIS Engine Runtime, users can contact ESRI for CDs to install the Engine
Runtime for internal use. Business partners that develop applications may also purchase
runtime licenses and incorporate them into the setup program for installing the custom built
application.

Introduction to Programming ArcObjects with VBA ArcObjects Beyond VBA 17-22


Why ArcGIS Engine Developer Kit?
‹ So end users don’t need a full ArcGIS Desktop license
on their machine to use a developer’s standalone
application
‹ Designed for focused applications that don’t need
everything ArcGIS Desktop offers
Java Example

Windows
Example
Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming 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.

Introduction to Programming ArcObjects with VBA ArcObjects Beyond VBA 17-23


ArcGIS Engine Developer Kit resources
‹ Instructor-led course
‹ Developing Applications with ArcGIS Engine

‹ http://arcgisdeveloperonline.esri.com
‹ ArcGIS Engine Developer Guide
‹ Samples

‹ Extending ArcObjects

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 17-24

The Developing Applications with ArcGIS Engine instructor-led course will supply a wealth of
information to get you started building and deploying ArcGIS Engine applications.
ArcGIS Developer Online also provides developer guides and samples that are specific to
building ArcGIS Engine applications.

Introduction to Programming ArcObjects with VBA ArcObjects Beyond VBA 17-24


Lesson overview
‹ Creating COM classes with Visual Basic
‹ Visual Basic versus VBA
‹ Building a COM class with Visual Basic
Š Referencing the ArcObjects libraries
Š Implementing an interface
Š Delivering your class
‹ ArcObjects interfaces
Š Where can your component plug in?

‹ ArcGIS Engine Developer Kit


‹ ArcGIS Server

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 17-25

Overview
This optional lesson covers ArcGIS Server, a new product at ArcGIS 9. 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.

Introduction to Programming ArcObjects with VBA ArcObjects Beyond VBA 17-25


ArcGIS Server
‹ A Web developer framework that makes it easy to build
GIS Web applications and enterprise GIS applications
‹ Supports Client-Server, GIS Web Services, and GIS Web
Applications
‹ Cross platform
‹ Multiple APIs
‹ .Net, Java

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 17-26

ArcGIS Server is a GIS enterprise application server that provides complete GIS capabilities
throughout an organization while maintaining a centrally managed 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.

Introduction to Programming ArcObjects with VBA ArcObjects Beyond VBA 17-26


Why ArcGIS Server?
‹ So users can perform more advanced analysis over a
LAN/Internet (take advantage of the ArcObjects)
‹ So users can interact with an enterprise system

Geodatabase Editing

Network Tracing

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming 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.

Introduction to Programming ArcObjects with VBA ArcObjects Beyond VBA 17-27


ArcGIS Server resources
‹ Instructor-led course
‹ Developing Applications with ArcGIS Server

‹ http://arcgisdeveloperonline.esri.com
‹ ArcGIS Server Developer Guide
‹ Samples

Copyright © 2001–2004 ESRI. All rights reserved. Introduction to Programming ArcObjects with VBA 17-28

ArcGIS Server resources


The Developing Applications with ArcGIS Server instructor-led course will supply a wealth of
information to get you started building and deploying ArcGIS Server applications.
ArcGIS Developer Online also provides developer guides and samples that are specific to
building ArcGIS Server applications.

Introduction to Programming ArcObjects with VBA ArcObjects Beyond VBA 17-28

You might also like