Introduction To Vba Programming With Arcobjects: Workshop Outline
Introduction To Vba Programming With Arcobjects: Workshop Outline
Workshop Outline
ArcObjects/VBA overview (9:15-9:45) Customizing ArcMap interface (9:45 10:30) Visual Basic for Applications (VBA) environment (10:30-11:00) Morning break (11:00-11:15) VBA programming concepts ( p g g p (11:15-12:15) ) Lunch (12:15-12:45) ArcObjects overview (12:45-1:30) Using ArcObjects Using ArcObjects 1: Map Display (1:45 2:45) Afternoon Break (2:45 3:00) Using ArcObjects II: Selecting, Geoprocessing (3:00 4:00)
Warning
Developing ArcGIS functionality and understanding ArcObjects is complicated
ArcObjects/VBA Overview
ArcObjects/VBA Overview
ArcGIS provides a large amount of functionality However users often want to harness that functionality in different ways than is p y y possible out of the box
Develop customizations to carry out work-flow tasks Develop customized spatial modeling operations Combine multiple steps into a single customized tool
ArcObjects
Set of components or building blocks on which the scaleable ArcGIS framework is built Developed by ESRI using C++ as classes Basically everything you see and interact with in any ArcGIS application is an ArcObject
Maps Layers Points Tables Fields Rasters Buttons
9/5/2007
Map
Button
ArcObjects
Graphic Point
Layer
There are a huge number of ArcObjects Accessible through various programming/development enviroments
Focus today on VBA y
Almost impossible to get to know all ArcObjects A strong background using the applications (ArcMap, ArcCatalog, etc.) important Learn how to navigate to get to proper ArcObject
Polygon Table Field
9/5/2007
Tool
Button
Buttons make something happen immediately Tools work by clicking on the control and then clicking in the map ork b display
Menus Menu items (really are just buttons) Combo boxes (e.g. Map scale) Provide user dropdown choice Editbox (rarely used) To enter and report information
9/5/2007
Projects
Code Module
Procedure
A sophisticated program in itself that takes time to learn Lots of functionality and tools to help you more efficiently write code
Object Box
Procedure Box
Forms
User can design custom interfaces using the form designer
VBA Environment
You can store customized controls and codes in either an .mxd project, in the Normal.mxt or in one of your own template. If you save these customizations in the Normal.mxt they will be available every time you open ArcMap (only on your computer). Today we are only going to work saving customizations into a specific .mxd.
Check box
9/5/2007
Comments
For your sake and others it is important to put comments in your code Comment enough so when you return to the code later it will make it much easier for you to understand Comments begin with and are shown in red
Get the number of layers that are in the map intLayerCnt = pMap.LayerCount
Intellisense
VBA has functionality to finish code for you While typing a variable, method, procedure, etc., clicking Ctrl+Spacebar will finish code An A example f a variable named l for i bl d strStateName
Type strSt and click Cntrl+Spacebar and VBA will finish strStateName for you
Variables
Variables are used to store values It is encouraged practice to declare variables
Dim intMyNumber as Integer
Data types
Numbers
Integer whole numbers from -32768-32767 Long large whole numbers Double all numbers (very large or with decimals) ( y g )
This tells the program what kind of data type the variable is and provides clarity One programming convention has the variable name prefaced by an abbreviation for what the data type is
Strings text Boolean true or false Dates hold dates Variant a generic data type that can hold any data type
9/5/2007
Setting variables
You set the variables in an assignment statement
Ex. 1
Dim lngX as Long g g lngX = 120000 Ex. 2 Dim dblAnnualTax as Double Dim dblParcelValue as Double dblParcelValue = 100000 dblAnnualTax = 0.05 * dblParcelValue
Conditional logic
It is common to have to account for different conditions in programming Use conditional logic Most M t common is If Then i Th
If intTempF <= 32 then
msgBox It might snow
Looping
A program often needs to loop through a collection of objects First way to do it is with a For.Next
For intNum = 1 to 10 msgBox The number is & intNum Next I ArcMap Example For i = 0 to pMap.LayerCount - 1 msgBox The layer name is & pMap.Layer(i).Name Next i
Else
msgBox It might rain
End if
Looping
Second way to do it is with a Do.Until or DoWhile
Do While intCnt < 50 msgBox intCnt intCnt = intCnt + 1 Loop ArcMap Example Do Until pRow Is Nothing dblArea = pRow.Value(2) Set pRow = pCursor.NextRow Loop
Procedures
Procedures hold blocks of code that carry out specific functions We have seen event procedures
E.g. MyButton_Click E M B tt Cli k
Two types
Sub procedures Functions
9/5/2007
Sub procedures
Can be a control event procedure or a stand-alone procedure that is called from somewhere else Should be named logically
E.g. ReturnMapRasters g p
When you create a control in ArcMap or Form then each sub procedure linked with an event is automatically named
ZoomOut_Click (ArcMap button) cmdGetMapName_Click (form command button)
End Sub
Functions
Functions take input, process the input, and return output Many built-in functions in VBA
Int(2.6) t I t(2 6) returns 2 Len(Long) returns 4 (i.e. length of string)
Function example
Public Sub ReportTax()
dblPropVal = 80000 dblTotalTax = CalculateTax(dblPropVal) msgBox The tax due is & dblTotalTax
Functions have a single output that can be string or numeric You can define your own functions
End Function
Objects
Mentioned ArcObjects before There are other objects
Forms and all controls are objects Other objects such as Collections and Arrays
Properties
Properites are characteristics of an object Can set properties in form designer window
9/5/2007
Properties
Can also set form and command properties through code Use the object.property syntax
cmdLayerName.Caption = Fi t Layer N dL N C ti First L Name cmdLayerName.Enabled = False txtLayerName.Text = frmLayerName.Width = 200
Events
Forms and controls have a number of potential events they react to
cmdLayerName.Click txtLayerName.Change txtLayerName Change frmLayerName.Initialize
Methods
Things that an object can do
frmLayerName.Hide cmdLayerName.Move 25, 50 cboLayerName.AddItem Iowa Counties cboLayerName AddItem Iowa Counties
Other Tips
To get help put your cursor on a method or property and click F1
Overview of ArcObjects
9/5/2007
ArcObjects
Set of components or building blocks on which the scaleable ArcGIS framework is built ArcObjects come from classes designed by ESRI programmers Basically everything you see and interact within any ArcGIS application is an ArcObject
Maps Layers Points Tables Fields Rasters
Map
Button
Programming Interfaces
Graphic Point
Layer
In order to work with ArcObjects you need to learn how to access objects with interfaces An interface is a logical grouping of properties and methods for a class Interfaces start with the letter I and variables are prefaced with p
Dim pMap as IMap
Can have multiple interfaces on a single class All ArcObjects classes have interfaces
A single interface (IDog) on a dog class which has a single property (Breed) and method (Bark)
9/5/2007
ArcObjects example
Map IMap
Name: String AddLayer
Multiple Interfaces
As mentioned before, can be multiple interfaces on the same class In order to access properties and methods from multiple interfaces you might set up two variables that are equal to the same object
This is called a QueryInterface or QI
The Map class has an interface named IMap and through that interface you can get/set name of the map and you can add a layer.
Monkey IMonkey
Species: String Climb Age: Integer Eat
IAnimal
IAnimal
Two interfaces with different properties and methods on the Dog object The IAnimal is an interface on different classes
OMDs
Designed with Unified Modeling Language Very detailed Have to learn how to read like a roadmap Can be complicated and daunting Learn how to read and only get to what you need OMDs organized by categories (i.e. Geometry, Geodatabase, ArcCatalog, Spatial Analyst)
There are a set of diagrams (pdf files) which provide a graphical representation of these objects, interfaces, methods, properties, and relationships
Object Model Diagrams
10
9/5/2007
OMD Key
There is a key on every OMD explaining classes and relationships
Symbols
Get/Put (read/write) Get (read) Put (write) P t ( it ) Put by reference (use Set ..) Method Interface
OMDs online
Go to
http://edndoc.esri.com/arcobjects/9.2/welcome.ht m Panel on right of window click on ArcObjects Library Reference at bottom Choose the category you think that you think your ArcObject might be found and click on it Click on the .Object Model Diagram and it will open up the OMD
Class Types
There are different kinds of classes
Abstract classes no objects created from these Classes (regular) made or gotten from other classes Coclasses can create objects from coclasses
E.g. our Dog class earlier could create a new Dog object. Can also get objects of coclasses from other objects that return them
E.g. a new Map object is returned from another class with the .FocusMap method
11
9/5/2007
Class Relationships
Associations Instantiation one class has a method that creates new object from another class Inheritance a class uses as an i t f I h it l interface from a more general class Composition objects in one class (whole class) control lifetime of another class (part class)
Layer ILayer
Name
FeatureLayer IFeatureLayer
Code Examples
Association
Dim pMap as IMap Dim pLayer as ILayer pMap set here p p Set pLayer = pMap.Layer(0)
Instantiation (create)
FeatureClass IFeatureClass
Search
Inheritance
Dim pFeatureLayer as ILayer Set pFeatureLayer = New FeatureLayer pLayer.Name = Iowa Counties
FeatureCursor IFeatureCursor
A FeatureCursor object is created from a FeatureClass object using the Search method
Composition (create)
MxDocument IMxDocument
FocusMap: IMap
* Map IMap
An MxDocument can have multiple maps. If maps you delete the MxDocument then the Maps are deleted
y This syntax indicates the Layer property requires a variable of type Long and returns an ILayer object
12
9/5/2007
Code Example
Instantiation
pFeatureClass would be set in here Dim pFeatureCursor as IFeatureCursor Set pFeatureCursor = pFeatureClass Search(Nothing True) pFeatureClass.Search(Nothing,
MxDocument object
Called ThisDocument
MxDocument
With an .mxd open saved as ThisDoc.mxd
Application.Caption
To get help for ArcObjects click F1 on and interface in the code module windows
MsgBox ThisDocument.Title E.g. put your mouse on IMap and click F1
Method help
13
9/5/2007
Code example
Using ArcObjects: Map Display, Layers, Feature Classes, and Tables
Dim pMxDoc as IMxDocument Dim pMap as IMap Dim pLayer as ILayer get the map Set pMxDoc = ThisDocument Set pMap = pMxDoc.FocusMap get the first layer in the map Set pLayer = pMap.Layer(0) msgBox pLayer.Name
Map IMap
Layer (in Index:Long): ILayer
. Dim pSFWSFact as IWorkspaceFactory Dim pFeatWS as IFeatureWorkspace Dim pFeatureClass as IFeatureClass Dim pFeatureLayer as IFeatureLayer set the workspace Set pSFWSFact as new ShapefileWorkspaceFactory Set pFeatWS = pSFWSFact.OpenFromFile(D:\VBAWshop, 0) pSFWSFact.OpenFromFile( D:\VBAWshop , open feature class Set pFeatureClass = pFeatWS.Open(IowaRivers.shp) create layer, set its feature class, set name, and add to map Set pFeatureLayer = new FeatureLayer Set pFeatureLayer.FeatureClass = pFeatureClass pFeatureLayer.Name = Iowa Rivers pMap.AddLayer pFeatureLayer
14
9/5/2007
Workspace IFeatureWorkspace
OpenFeatureClass (in String): IFeatureClass
FeatureLayer IFeatureLayer
FeatureClass: IFeatureClass
FeatureClass
IFeatureClass
Row
IRow
Composed p Inherits
FeatureClass
*
Feature
MxDocument IMxDocument
ActiveView: IActiveView
IFeatureClass
IFeature
ActiveView
Extent (in: IEnvelope)
IActiveView
Tables
Open from an IWorkspace object
Use an AccessWorkspaceFactory to open a personal geodatabase table Use a ShapefileWorkspaceFactory to open a .dbf dbf table ExcelWorkspaceFactory to open an .xls table others???
15
9/5/2007
Cursors
Cursors are used to retrieve a set of records You can step through a cursor row by row in a forward direction These are not the selected records you might Th t th l t d d i ht see through an attribute query Very useful for getting and setting values in records row by row
Selection Set
Row
Value
IRow
ICursor
'select the counties that have a population > 100000 'Declarations Dim pCountyFLayer As IFeatureLayer Dim pCountyQF As IQueryFilter Dim pCountyFSel As IFeatureSelection .. 'get the layer and its feature class Set pCountyFLayer = pMap.Layer(0) 'set up the query filter Set pCountyQF = New QueryFilter pCountyQF.WhereClause = "Tot_Pop > 100000" 'set feature selection to the layer and refresh the map Set pCountyFSel = pCountyFLayer QI pCountyFSel.SelectFeatures pCountyQF, esriSelectionResultNew, False pMxDoc.ActiveView.Refresh
Table
Search
QueryFilter
ITable
IQueryFilter
16
9/5/2007
FeatureLayer
FeatureClass
IFeatureSelection
IFeatureLayer
ITopologicalOperator
Buffer, Clip, Cut, Simplify, etc.
QueryFilter
ITopologicalOperator2
ConstructBuffers, ClipToDomain
IQueryFilter
Buffer Example
'This sub should buffer the first feature layer in map with graphics 'Declarations .. Dim pTopoOperator As ITopologicalOperator Dim pFeatureCursor As IFeatureCursor Dim pFeature As IFeature Dim pElement As IElement Dim pGraphicsContainer As IGraphicsContainer .. 'set the graphics container Set pGraphicsContainer = pMap 'get the layer and feature class .. 'set up feature cursor, loop through and buffer each feature, add graphic to map Set pFeatureCursor = pBufferFC.Search(Nothing, True) Set pFeature = pFeatureCursor.NextFeature Do Until pFeature Is Nothing Set pTopoOperator = pFeature.Shape Set pElement = New PolygonElement pElement.Geometry = pTopoOperator.Buffer(2500) pGraphicsContainer.AddElement pElement, 0 Set pFeature = pFeatureCursor.NextFeature Loop 'refresh the view pMxDoc.ActiveView.Refresh
17