English

How To: Programatically calculate between items for a selected set of records

Summary

Note:
This article pertains to ArcGIS versions 8.x and 9.x. Later versions of ArcGIS may contain different functionality, as well as different names and locations for menus, commands and geoprocessing tools.

Instructions provide sample code showing how to set one field's data value equal to another field's value in a selected set of records.

Note: 
Support for Visual Basic for Applications (VBA) for ArcMap and ArcCatalog ended with the ArcGIS 10.2.2 release, and Esri has not included VBA compatibility setups since version 10.5. See: ArcGIS Desktop and VBA Moving Forward

Procedure

Modify ICalculator::Expression values to perform desired calculation, using the steps that follow.

  1. Start ArcMap.
  2. Create a new UIButtonControl: How To: Create a new UIButtonControl
Note:
 For more information on creating a UIControl, see the ArcGIS Desktop Help topic "Creating custom commands with VBA and UI Controls".
  1. Add a feature class or layer to the map. The layer must have two fields in its attribute table with compatible data types, such as both numeric or both text, and so on. One field is the source of the calculation's data, the other is the target of the calculation.
  2. Right-click the UIButtonControl and select View Source.
  3. Copy the code below into the UIButtonControl's click event (by default, "UIButtonControl1_Click").
Dim pMxDoc As IMxDocument
Dim pFlayer As IFeatureLayer2
Dim pFClass As IFeatureClass

Set pMxDoc = ThisDocument
'This assumes that the table is taken from the 
'first layer listed in the Table of Contents

Set pFlayer = pMxDoc.FocusMap.layer(0)
Set pFClass = pFlayer.FeatureClass

Dim pFeatureSel As IFeatureSelection
Set pFeatureSel = pFlayer

Dim pSelSet As ISelectionSet2
Set pSelSet = pFeatureSel.SelectionSet

Dim pfCursor As IFeatureCursor
pSelSet.Update Nothing, True, pfCursor

Dim pCalculator As ICalculator
Set pCalculator = New Calculator

With pCalculator
Set .Cursor = pfCursor
.Expression = "[SOURCEFIELDNAME]"
.Field = "TARGETFIELDNAME"
End With
pCalculator.Calculate
  1. Modify the code, changing "[SOURCEFIELDNAME]" to the appropriate source field in the attribute table. Modify "TARGETFIELDNAME" to be the name of the field whose values are updated.
  2. Make sure that the layer to be updated is listed first in the Table of Contents.
  3. Select one or more records in this layer's attribute table.
  4. Click the new button to execute the code. The calculation performed on the source field is assigned to the target field of the selected records. If the attribute table is open when the button is clicked, close and re-open the attribute table to see the results.