Add a spatial index to a shapefile using ArcObjects


This article contains sample code that creates a spatial index for a shapefile if one does not already exist.


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

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

  3. In the Project Explorer window, expand Project.mxt and select ArcMap Objects > ThisDocument . Right-click and select View Code.
    [O-Image] Visual Basic Project  Explorer
    Code in the Project's ThisDocument code module will only run in the current map document. To store the code in all map documents, open the Normal.mxt ThisDocument code module instead.

  4. Paste the following code into the code module.

    Sub CheckforSpatialIndex()
    Dim pDoc As IMxDocument
    Set pDoc = ThisDocument
    'Get the first layer in the map
    Dim pLayer As IFeatureLayer
    Set pLayer = pDoc.FocusMap.Layer(0)
    Dim pFc As IFeatureClass
    Set pFc = pLayer.FeatureClass

    'Check the shapefile to see if it
    'already has a spatial index
    Dim pIndexes As IIndexes
    Dim pEnumIndex As IEnumIndex
    Set pIndexes = pFc.Indexes
    Set pIndexes = pFc.Indexes
    If pIndexes.FindIndexesByFieldName("Shape").Next Is Nothing Then
    Debug.Print pFc.AliasName
    Call AddMyIndex(pFc, pFc.ShapeFieldName)
    End If
    End Sub
    Public Sub AddMyIndex(pFc As IFeatureClass, strFieldName As String)
    'Set up fields
    Dim pFields As IFields
    Dim pFieldsEdit As IFieldsEdit
    Dim pField As IField
    Dim lfld As Long
    Set pFields = New Fields
    Set pFieldsEdit = pFields
    pFieldsEdit.FieldCount = 1
    lfld = pFc.FindField(strFieldName)
    Set pField = pFc.Fields.Field(lfld)
    Set pFieldsEdit.Field(0) = pField
    Dim pIndex As IIndex
    Dim pIndexEdit As IIndexEdit
    Set pIndex = New Index
    'QI for IIndexEdit
    Set pIndexEdit = pIndex
    With pIndexEdit
    Set .Fields = pFields
    .Name = "Idx_1"
    End With
    'Add index to feature class
    pFc.AddIndex pIndex
    End Sub

  5. Close the Visual Basic Editor.
  6. Add a shapefile to ArcMap.
  7. Run the code.

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

Article ID:000004972

  • ArcMap 8 x

Get help from ArcGIS experts

Contact technical support

Download the Esri Support App

Go to download options

Discover more on this topic