English

How To: Programmatically add a sequential id to sorted data

Summary

This article contains sample code that adds a sequential identifier to sorted data.

Procedure

  1. Start 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. Then, right-click and 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 your map documents, open the Normal.mxt ThisDocument code module instead.

  4. Copy the following code into the code module.
    Code:
    Sub AddSequentialIdsToSortedData()

    Dim pMxDoc As IMxDocument
    Dim pMap As IMap
    Dim player As ILayer
    Dim pFLayer As IFeatureLayer
    Dim pFClass As IFeatureClass
    Dim pTableSort As ITableSort
    Dim pTable As ITable
    Dim pCursor As ICursor
    Dim pRow As IRow
    Dim pQf As IQueryFilter
    Dim x As Long
    Dim y As Long: y = 0
    Dim pEditor As IEditor
    Dim pID As New UID
    Dim pDataset As IDataset

    Set pMxDoc = ThisDocument
    Set pMap = pMxDoc.FocusMap
    Set player = pMap.Layer(0)
    Set pFLayer = player
    Set pFClass = pFLayer.FeatureClass
    Set pTable = pFClass
    Set pTableSort = New tablesort
    Set pQf = New QueryFilter

    With pTableSort
    .Fields = "Name"
    .Ascending("Name") = True
    Set .QueryFilter = pQf
    Set .Table = pTable
    End With

    pTableSort.Sort Nothing
    Set pCursor = pTableSort.Rows
    Set pRow = pCursor.NextRow

    Set pDataset = pTable
    pID = "esriCore.editor"
    Set pEditor = Application.FindExtensionByCLSID(pID)

    x = pTable.FindField("test")

    Do Until pRow Is Nothing
    y = y + 1
    pRow.Value(x) = y
    pRow.Store
    Set pRow = pCursor.NextRow
    Loop

    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.