z9/5/2007

Introduction to VBA Workshop Outline Programming with z ArcObjects/VBA overview (9:15-9:45) ArcObjects z Customizing ArcMap interface (9:45 – 10:30) z for Applications (VBA) environment (10:30-11:00) z Morning break (11:00-11:15) GeoTREE Center z VBA ppgrogrammin g conce pts (11:15-12:15) z Lunch (12:15-12:45) University of Northern Iowa z ArcObjects overview (12:45-1:30) Geography z Using ArcObjects z Using ArcObjects 1: Display (1:45 – 2:45) July 18, 2007 z Afternoon Break (2:45 – 3:00) z Using ArcObjects II: Selecting, Geoprocessing (3:00 – 4:00)

Warning

z Developing ArcGIS functionality and understanding ArcObjects is complicated z This workshop is a basic introduction to help you ArcObjects/VBA Overview develop ArcGIS customizations

ArcObjects/VBA Overview ArcObjects z ArcGIS provides a large amount of z Set of components or building blocks on which the functionality scaleable ArcGIS framework is built z Developed by using C++ as classes z However users often want to harness that z Basically everything you see and interact with in any functionalityyyp in different ways than is possible ArcGIS application is an ArcObject out of the box z z Layers z Develop customizations to carry out work-flow z Points tasks z Tables z Develop customized spatial modeling operations z Fields z Rasters z Combine multiple steps into a single customized tool z Buttons

z1 z9/5/2007

Map Button ArcObjects

Layer z There are a huge number of ArcObjects z Accessible through various Graphic Point programming/development enviroments z Focus today on VBA z Almost impossible to get to know all ArcObjects z A strong background using the applications (ArcMap, ArcCatalog, etc.) important z Learn how to navigate to get to proper ArcObject Polygon

Table Field

Visual Basic for Applications Other Development (VBA) Environments

z Visual Basic z VBA is a development environment that is z C# provided with ArcGIS (also with Microsoft z C++ Word, Excel , Powerpoint , etc . ) with which you z Delphi can access ArcObjects z others z It is a simplified version of Visual Basic z For customizing applications

Scripting vs. development environment (ArcObjects)

Start VBA Interface z Scripting for geoprocessing in ArcGIS z Python, VBScript, etc. z Scripting calls on ArcObjects to do processing z Scrippgting calls u pon one main ArcOb ject z Geoprocessing ArcObject z Development environments (VBA, VB, C# etc.) z Allow access to all ArcObjects z Developing customized interfaces z Distributable customizations

z2 z9/5/2007

Scripting vs. Arcobjects (VBA,etc.) z Scripting with Python z ArcObjects with VBA z Clip feature class with z Clip feature class with another feature class another feature class z Add clipped layer to map z Symbolize the new layer Customizing ArcMap Interface z Create a map layout with the new layer z Print the map

Customizing ArcMap Interface

z You can control the look and feel of the ArcMap interface

z Add/remove existing controls A full ArcMap Interface z Create new controls z Can associate VBA code to newly created tools, buttons and menu items

Control Types in ArcMap

z Toolbars z Buttons, tools

Tool Button A minimalist ArcMap Interface z Buttons make something happen immediately z Tools work b y clicking on the control and then clicking in the map display z Menus z Menu items (really are just buttons) z Combo boxes (e.g. Map scale) z Provide user dropdown choice z Editbox (rarely used) z To enter and report information

z3 z9/5/2007

Customization Demonstration and Exercise VBA Development Environment

VBA Development Visual Basic Editor Projects Code Module Procedure Window Environment

z Accessed through ArcMap or ArcCatalog z Tools for developing code and user interfaces z i.e. modules for code and forms for user interfaces Object Box z A sophisticated program in itself that takes Procedure Box time to learn z Lots of functionality and tools to help you more efficiently write code

Forms VBA Environment • User can design custom interfaces using z You can store customized controls and codes the form designer in either an .mxd project, in the Normal.mxt or in one of your own template. z If you save these customizations in the Normal.mxt they will be available every time Check box you open ArcMap (only on your computer). z Today we are only going to work saving customizations into a specific .mxd.

z4 z9/5/2007

VBA Development Environment Demonstration and Exercise VBA Programming Concepts

Comments Intellisense z For your sake and others it is important to put z VBA has functionality to finish code for you comments in your code z While typing a variable, method, procedure, z Comment enough so when you return to the etc., clicking Ctrl+Spacebar will finish code code later it will make it much easier for you z AlfibldAn example for a variable named to understand strStateName z Comments begin with ‘ and are shown in red z Type strSt and click Cntrl+Spacebar and VBA will ‘Get the number of layers that are in the map finish strStateName for you intLayerCnt = pMap.LayerCount z Very useful to guard against typos

Variables Data types z Variables are used to store values z Numbers z It is encouraged practice to ‘declare’ z Integer – whole numbers from -32768-32767 variables z Long – large whole numbers z Dim intMyNumber as Integer z Double – all numbers ((ygvery large or with decimals ) z This tells the program what kind of data type z Strings – text the variable is and provides clarity z Boolean – true or false z One programming convention has the z Dates – hold dates variable name prefaced by an abbreviation z Variant – a generic data type that can hold for what the data type is any data type

z5 z9/5/2007

Basic data types and abbreviations Setting variables z Integer – int z You set the variables in an assignment z intTemp = 32 statement z Long – lng z lngLength = 45000 Ex. 1 z Double – dbl Dim lngggX as Long z dblArea = 1254.56 lngX = 120000 z String – str Ex. 2 z strStreet = “Clay Street” z Boolean – bln Dim dblAnnualTax as Double z blnCancel = True Dim dblParcelValue as Double z Date – dat dblParcelValue = 100000 z Variant - var dblAnnualTax = 0.05 * dblParcelValue

Conditional logic Looping z It is common to have to account for different z A program often needs to loop through a collection conditions in programming of objects z First way to do it is with a For….Next z Use conditional logic For intNum = 1 to 10 z MtMost common i iIfThs If Then msgBox “The number is “ & intNum If intTempF <= 32 then Next I msgBox “It might snow” ArcMap Example Else For i = 0 to pMap.LayerCount - 1 msgBox “The layer name is “ & pMap.Layer(i).Name msgBox “It might rain” Next i End if

Looping Procedures z Second way to do it is with a Do….Until or z Procedures hold blocks of code that carry out Do…While specific functions Do While intCnt < 50 msgBox intCnt z We have seen event procedures intCnt = intCnt + 1 z E.g. MyB utt on_Cli c k Loop ArcMap Example z Two types Do Until pRow Is Nothing z Sub procedures dblArea = pRow.Value(2) z Functions Set pRow = pCursor.NextRow Loop

z6 z9/5/2007

Sub procedures Call sub example z Can be a control event procedure or a stand-alone Public Sub ShowName() procedure that is called from somewhere else Dim strName as string z Should be named logically Call GetName(strName) z E.ggp. ReturnMapRasters msgBox “The name is “ & strName z When you create a control in ArcMap or Form then End Sub each sub procedure linked with an event is automatically named Public Sub GetName(strName as string) z ‘ZoomOut_Click’ (ArcMap button) strName = InputBox(“Enter Name”, “Name”) z ‘cmdGetMapName_Click’ (form command button) End Sub

Functions Function example z Functions take input, process the input, and Public Sub ReportTax() return output ……… dblPropVal = 80000 z Many built-in functions in VBA dblTotalTax = CalculateTax(dblPropVal) z It(26)tInt(2.6) returns 2 msgBox “The tax due is “ & dblTotalTax z Len(“Long”) – returns 4 (i.e. length of string) End Sub z Functions have a single output that can be string or numeric Public Function CalculateTax(dblPropVal) as Double z You can define your own functions CalculateTax = 0.075 * dblPropVal End Function

Objects Properties z Mentioned ArcObjects before z Properites are characteristics of an object z There are other objects z Can set properties in form designer window z Forms and all controls are objects z Other objects such as Collections and Arrays z Each of these objects has properties, events and methods z Property is a characteristic or attribute z Events are user actions that happen to an object z Methods are things an object can do

z7 z9/5/2007

Properties Events z Can also set form and command properties z Forms and controls have a number of through code potential events they react to z Use the ‘object.property’ syntax z cmdLayerName.Click z cmdLayer Name. Cap tion = “Firs t L ayer Name ” z txtLayerName. Change z cmdLayerName.Enabled = False z frmLayerName.Initialize z txtLayerName.Text = “” z frmLayerName.Width = 200

Methods Other Tips z Things that an object can do z To get help put your cursor on a method or z frmLayerName.Hide property and click F1 z cmdLayerName.Move 25, 50 z cboLayerName.AddItem “Iowa Counties” z Other VBA objects have methods z E.g. Collection objects are lists to which can hold different variables z rasterColl.Add pRaster z intRasterCnt = rasterColl.Count

Object Oriented Programming

z OOP is centered around objects z OOP programs have objects that hold data, have properties, respond to methods, and raise events Overview of ArcObjects z E.g. a professor’s program to calculate grades z A student object might hold name, midterm grade, etc. z A SemGrade method might calculate semester grade

z8 z9/5/2007

Object Oriented Programming ArcObjects

z Two tiers of OOP z Set of components or building blocks on which the scaleable ArcGIS framework is built z Low-level is creating and using objects (properties z ArcObjects come from classes designed by ESRI and methods) from existing classes (client) z Upper-tier of creating the classes themselves z Basically everything you see and interact within any (server) and writing code for properties and ArcGIS application is an ArcObject methods z Maps z Layers z We will mainly look at the client side today z Points z i.e. We are going to make use of existing objects z Tables (VBA and ArcObjects) z Fields z Rasters

Map Button Programming Interfaces

Layer z In order to work with ArcObjects you need to learn how to access objects with interfaces Graphic Point z An interface is a logical grouping of properties and methods for a class z Interfaces start with the letter I and variables are prefaced with p Dim pMap as IMap z Can have multiple interfaces on a single class Polygon z All ArcObjects classes have interfaces

Table Field

Hypothetical Dog Class Example Dog class example (cont.)

z To declare and use and IDog object from the Dog Breed: String dog class IDog Bark Dim pDog as IDog Set pDog = New Dog pDog.Breed = “Poodle” msgBox “The dog is a “ & pDog.Breed z A single interface (IDog) on a dog class which has a single property (Breed) and method (Bark)

z9 z9/5/2007

ArcObjects example Multiple Interfaces

z As mentioned before, can be multiple Map Name: String interfaces on the same class IMap AddLayer z In order to access properties and methods from multiple interfaces you might set up two variables that are equal to the same object z This is called a QueryInterface or QI z The Map class has an interface named IMap and z Following is a hypothetical example through that interface you can get/set name of z Will see ArcMap related examples as we go on the map and you can add a layer.

Hypothetical Dog Class Example (Two interfaces) Dog class example (cont.)

z To declare and use and IDog object from the dog class Dog Monkey Breed: String Species: String Dim pDog as IDog IDog IMonkey Bark Climb Dim pAnimal as IAnimal

AItAge: Integer Age: Integer IAnimal IAnimal Set pDog = New Dog Eat Eat Set pAnimal = pDog ‘QueryInterface pDog.Breed = “Poodle” z Two interfaces with different properties and pAnimal.Age = 10 methods on the Dog object msgBox “The dog is a “ pDog.Breed & “ and she is “ pAnimal.Age & “ years old.” z The IAnimal is an interface on different classes

Object Model Diagrams OMD’s

z There are many (thousands) of ArcObjects z Designed with Unified Modeling Language classes z Very detailed z In order to get to a given object you might z Have to learn how to read like a roadmap have to navigggyate through many others z Can be complicated and daunting z MxDocument - Map – Layer z Learn how to read and only get to what you z There are a set of diagrams (pdf files) which need provide a graphical representation of these objects, interfaces, methods, properties, and z OMD’s organized by categories (i.e. relationships Geometry, Geodatabase, ArcCatalog, Spatial Analyst) z Object Model Diagrams

z10 z9/5/2007

OMD Key

z There is a key on every OMD explaining classes and relationships

Symbols OMD’s online

Get/Put (read/write) z Go to z http://edndoc.esri.com/arcobjects/9.2/welcome.ht Get (read) m Pt(Put (wr it)ite) z Panel on right of window click on ArcObjects Reference at bottom z Choose the category you think that you think your Put by reference (use Set ..) ArcObject might be found and click on it z Click on the ….Object Model Diagram and it will Method open up the OMD Interface

Class Types Class Types Symbology z There are different kinds of classes z Abstract classes – no objects created from these z Classes (regular) – made or gotten from other classes z Coclasses – can create objects from coclasses z E.g. our Dog class earlier could create a new Dog object. z 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

z11 z9/5/2007

Class Relationships Association and inheritance

z Associations Map z Instantiation – one class has a method that IMap creates new object from another class Layer(s) associated * with Map z IhInher itance – a clitflass uses as an interface Layer

from a more general class ILayer Name z Composition – objects in one class (‘whole FeatureLayer(s) class’) control lifetime of another class (‘part use interfaces of Layer class’) FeatureLayer (inheritance) IFeatureLayer

Code Examples Instantiation (create)

z Association FeatureClass

Dim pMap as IMap IFeatureClass Search Dim pLayer as ILayer A FeatureCursor object ……… ‘pppMap set here is created from a Set pLayer = pMap.Layer(0) FeatureClass object z Inheritance using the Search Dim pFeatureLayer as ILayer FeatureCursor

Set pFeatureLayer = New FeatureLayer IFeatureCursor method pLayer.Name = “Iowa Counties”

Composition (create) Miscellaneous OMD stuff

MxDocument A balloon like this indicates you need to go

IMxDocument FocusMap: IMap to another OMD An MxDocument can This syntax indicates the have multiple maps . If Layer (in Index: Long): ILayer Layer property requires a you delete the * variable of type Long and MxDocument then the returns an ILayer object Map

IMap Maps are deleted

z12 z9/5/2007

Code Example Two special objects z Instantiation z To use VBA for ArcMap a map document ………… ‘pFeatureClass would be set in here must be already be open Dim pFeatureCursor as IFeatureCursor z Two objects are already in use at this point Set pFeatureCursor = pFeaturpFeatureClasseClass. Search(Nothing, True) z AlitibjtApplication object z Called Application z MxDocument object z Called ThisDocument

MxDocument ArcObjects and VBA Help z With an .mxd open saved as ThisDoc.mxd z In the VBA editor to get Visual Basic Help go to Help – Microsoft Visual Basic Help Application.Caption

z To get help for ArcObjects click F1 on and interface in the code module windows MsgBox ThisDocument.Title z E.g. put your mouse on ‘IMap’ and click F1

Example ArcObjects Help Method help

Tells which OMD

z13 z9/5/2007

Code example

Using ArcObjects: Map Display, Layers, Feature Classes, and Tables

Get layer from Map Practical Examples – Get Map Dim pMxDoc as IMxDocument z Get the MxDocument and the active map or Dim pMap as IMap data frame Dim pLayer as ILayer z The following code is probably going to be ‘get the map used in most programs you write Set pMxDoc = ThisDocument Dim pMxDoc as IMxDocument Set pMap = pMxDoc.FocusMap Dim pMap as IMap MxDocument ‘get the first layer in the map ‘get the map IMxDocument FocusMap: IMap Set pLayer = pMap.Layer(0) Set pMxDoc = ThisDocument msgBox pLayer.Name Set pMap = pMxDoc.FocusMap Map IMap Layer (in Index:Long): ILayer

Create and add a new feature layer ………. Find and move a layer Dim pSFWSFact as IWorkspaceFactory Dim pFeatWS as IFeatureWorkspace ………. Dim pFeatureClass as IFeatureClass Dim pFeatureLayer as IFeatureLayer ‘get layer count, use that to get bottom layer, ‘set the workspace ‘move that layer to the top Set pSFWSFact as new ShapefileWorkspaceFactory intLayerCnt = pMap. LayerCount Set pFeatWS = pSFWSFact.OpenFromFile(“ D:\VBAWshop” ,,0) 0) ‘open feature class Set pMoveLayer = pMap.Layer(intLayerCnt – 1) Set pFeatureClass = pFeatWS.Open(“IowaRivers.shp”) pMap.MoveLayer pMoveLayer, 0 ‘create layer, set its feature class, set name, and add to map Set pFeatureLayer = new FeatureLayer Set pFeatureLayer.FeatureClass = pFeatureClass pFeatureLayer.Name = “Iowa Rivers” Map pMap.AddLayer pFeatureLayer IMap MoveLayer (in Layer:ILayer, in Index:Long)

z14 z9/5/2007

Create and add a new feature layer Zoom to Extent of Layer WorkspaceFactory

IWorkspaceFactory OpenFromFile (in FileName: String, ……… In hWnd: OLE_Handle): IWorkspace Dim pExtent as IEnvelope ‘get the layer and it’s extent Workspace Set ppyppy()ZoomLayer = pMap.Layer(0) IFeatureWorkspace OpenFeatureClass (in String): Set pExtent = pZoomLayer.AreaOfInterest IFeatureClass ‘zoom to the extent and refresh the view pMxDoc.ActiveView.Extent = pExtent FeatureLayer pMxDoc.ActiveView.Refresh IFeatureLayer FeatureClass: IFeatureClass FeatureClass

IFeatureClass

Zoom to layer extent Tables and feature classes Layer

ILayer AreaOfInterest: IEnvelope Table Row *

ITable IRow

IEnvelope Composed Inherits IEnvelope XMin: Double FeatureClass Feature *

MxDocument IFeatureClass IFeature

IMxDocument ActiveView: IActiveView ActiveView

Extent (in: IEnvelope) IActiveView

Tables Open Table (.dbf)

'declarations z Open from an IWorkspace object Dim pSFWSFact As IWorkspaceFactory Dim pTableWS As IFeatureWorkspace z Use an AccessWorkspaceFactory to open a Dim pOpenTable As ITable personal geodatabase table Dim intRowCnt As Integer z Use a ShapefileWorkspaceFactory to open a .dbf 'set the workspace Set pSFWSFact = New ShapefileWorkspaceFactory table Set pTableWS = pSFWSFact.OpenFromFile("D:\temp\julytrash\VBAwshop", 0) z ExcelWorkspaceFactory to open an .xls table 'open the table z …others??? Set pOpenTable = pTableWS.OpenTable(“IowaCounty_Population.dbf") 'get the number of rows and report intRowCnt = pOpenTable.RowCount(Nothing) MsgBox intRowCnt

z15 z9/5/2007

Open Table (Personal Geodatabase table)

'declarations Dim pAccessFact As IWorkspaceFactory Dim pTableWS As IFeatureWorkspace Dim pOpenTable As ITable Using ArcObjects II: Dim intRowCnt As Integer Cursors, Selection Sets, 'set the workspace Set pAccessFact = New AccessWorkspaceFactory Geoprocessing Set pTableWS = pAccessFact.OpenFromFile("D:\VBAWshop\Iowa.mdb", 0)

'open the table Set pOpenTable = pTableWS.OpenTable("IowaCountyPopulation")

'get the intRowCnt = pOpenTable.RowCount(Nothing) MsgBox intRowCnt

Table cursor example Cursors …….. Dim pCursor as ICursor z Cursors are used to retrieve a set of records Dim pQF as IQueryFilter Dim pRow as IRow z You can step through a cursor row by row in Dim intFldPos as integer a forward direction ‘get the field position of the County name field intFldPos = pOpenTable.FindField(“ COUNTY” ) z These are not th e sel ect ed record s you mi ght 'set up the cursor using a query filter see through an attribute query Set pQF = New QueryFilter pQF.WhereClause = "[TOT_POP] > 100000" z Very useful for getting and setting values in Set pCursor = pOpenTable.Search(pQF, True) Set pRow = pCursor.NextRow records row by row ‘loop through and list counties with Pop > 100000 Do Until pRow Is Nothing MsgBox pRow.Value(intFldPos) Set pRow = pCursor.NextRow Loop

Selection Set Tables and feature classes 'select the counties that have a population > 100000 'Declarations Dim pCountyFLayer As IFeatureLayer Dim pCountyQF As IQueryFilter Row Dim pCountyFSel As IFeatureSelection ICursor …………………………………………….. Value 'get the layer and its feature class NextRow IRow ICursor Set pCountyFLayer = pMap.Layer(0)

'set up the query filter Set pCountyQF = New QueryFilter Table QueryFilter pCountyQF.WhereClause = "Tot_Pop > 100000"

Search 'set feature selection to the layer and refresh the map ITable IQueryFilter Set pCountyFSel = pCountyFLayer ‘QI pCountyFSel.SelectFeatures pCountyQF, esriSelectionResultNew, False pMxDoc.ActiveView.Refresh

z16 z9/5/2007

Tables and feature classes Spatial Processing

z There is no central location for accessing FeatureSelection FeatureLayer spatial processing objects SelectFeatures FeatureClass IFeatureSelection IFeatureLayer z IBasicGeoprocessor z Clip, Disso lve, In tersec t, Merge, Un ion, e tc. z ITopologicalOperator z Buffer, Clip, Cut, Simplify, etc.

QueryFilter z ITopologicalOperator2 z 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

z17