English

How To: Programmatically create and populate an area field in ArcMap

Summary

This article contains sample code that adds a field called Area to your polygon attribute table and populates it with the area for each polygon.

Procedure

 

  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"
  3. Right-click the UIButtonControl and select View Source.
  4. Copy this code into the UIButtonControl's click event.
     
    Code:
    Dim pDoc As IMxDocument
      Dim pMap As IMap
      
      Set pDoc = ThisDocument
      Set pMap = pDoc.FocusMap
      
      '-- Get the selected layer
      Dim pFLayer As IFeatureLayer
      Set pFLayer = pDoc.SelectedLayer
      
      Dim pFc As IFeatureClass
      Set pFc = pFLayer.FeatureClass
      '-- Check to see if layer already has an area field
      If Not pFc.FindField("Area") = -1 Then
         MsgBox "Area already exists"
         Exit Sub
      End If
      '-- Create a field called Area
      Dim pField As IField
      Set pField = New Field
      Dim pFieldEdit As IFieldEdit
      Set pFieldEdit = pField
      With pFieldEdit
        .Name = "Area"
        .Type = esriFieldTypeDouble
        .Precision = 11
        .Length = 12
        .Scale = 3
      End With
      pFc.AddField pField
    
     '-- Loop through the features and get the area
      Dim pFCursor As IFeatureCursor
      Set pFCursor = pFLayer.Search(Nothing, False)
      Dim pFeat As IFeature
      Set pFeat = pFCursor.NextFeature
    
      Do Until pFeat Is Nothing
        Dim pArea As IArea
         If pFeat.Shape.GeometryType = esriGeometryPolygon Then
           Set pArea = pFeat.Shape
           pFeat.Value(pFc.FindField("Area")) = pArea.Area
           pFeat.Store
         End If
        Set pFeat = pFCursor.NextFeature
      Loop

     
  5. Select the layer in the Table of Contents and run the code.
     
    Note:
    The selected layer should not have an existing field called area