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


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.


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
     For more information on creating a UIControl, see the ArcGIS Desktop Help topic "Creating custom commands with VBA and UI Controls".
  3. 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.
  4. Right-click the UIButtonControl and select View Source.
  5. 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]"
    End With
  6. 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.
  7. Make sure that the layer to be updated is listed first in the Table of Contents.
  8. Select one or more records in this layer's attribute table.
  9. 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.