HOW TO
This article contains sample code that creates a spatial index for a shapefile if one does not already exist.
Note:
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.
Code:
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
Article ID:000004972
Get help from ArcGIS experts
Download the Esri Support App