English

How To: Add a new field to a shapefile or a feature class using ArcObjects.

Summary

Instructions provide a code sample that shows how to add a new field to a shapefile or featureclass using VBA. The layer that the field will be added to must be selected in the Table of Contents before running the code.

Procedure

  1. Start ArcMap.
  2. Open the Visual Basic Editor.

    In ArcMap, select Tools > Macros > Visual Basic Editor.

  3. Expand Project.mxt in the Project Explorer window and select ArcMap Objects > ThisDocument and right-click to select View Code.
    [O-Image] Visual Basic Project  Explorer
    Note:
    Code in the Project's ThisDocument code module will only run in the current map document. If you want to store the code in all map documents, open the Normal.mxt ThisDocument code module instead.

  4. Copy the following code into the code module.

    Code:
    Public Sub AddField()

    Dim pMxDoc As IMxDocument
    Dim pLayer As ILayer
    Dim pFLayer As IFeatureLayer
    Dim pFeatClass As IFeatureClass
    Dim NewField As IFieldEdit

    Set pMxDoc = ThisDocument
    Set pLayer = pMxDoc.SelectedLayer
    Set pFLayer = pLayer
    Set pFeatClass = pFLayer.FeatureClass
    Set NewField = New Field

    With NewField
    .Type = 3
    .Name = "NewField"
    End With

    pFeatClass.AddField NewField

    End Sub


  5. Close the Visual Basic Editor.
  6. Run the code.

    A. Click Tools > Macros > Macros to display the Macros dialog box.
    B. Select a macro and click Run.