English

How To: Label selected features in ArcMap using ArcObjects

Summary

This article shows how to label the selected features in ArcMap using VBA and ArcObjects.

Procedure

  1. Create a UIButtonControl.

    Note:
    For information on creating a UIControl, see the ArcGIS Desktop Help topic "How to create custom commands with VBA."

  2. Right-click the UIButtonControl and select View Source.
  3. Copy this code into the UIButtonControl's Click event.

    Code:
    'Get the focus map
    Dim pDoc As IMxDocument
    Set pDoc = ThisDocument
    Dim pMap As IMap
    Set pMap = pDoc.FocusMap

    ' Get the selected layer
    Dim pLayer As IGeoFeatureLayer
    Set pLayer = pDoc.SelectedLayer
    ' Make sure a layer was selected
    If pLayer Is Nothing Then
    MsgBox "You must select a Layer to Label"
    Exit Sub
    End If

    ' Get the feature class to get the correct
    ' oid field name for the data type (oid,fid,objectid)
    Dim pFc As IFeatureClass
    Dim strOIDName As String
    Set pFc = pLayer.FeatureClass
    strOIDName = pFc.OIDFieldName

    ' Get the selected features from the layer
    Dim pFSel As IFeatureSelection
    Set pFSel = pLayer
    Dim pSelSet As ISelectionSet
    Set pSelSet = pFSel.SelectionSet
    Dim pFCur As IFeatureCursor
    pSelSet.Search Nothing, False, pFCur
    ' Loop through the selected features and create a label
    ' expression for the selected features
    Dim pFeat As IFeature
    Dim strSql As String
    Set pFeat = pFCur.NextFeature
    Do While Not pFeat Is Nothing
    If strSql = "" Then
    strSql = strOIDName & " = " & pFeat.OID
    Else
    strSql = strSql & " or " & strOIDName & " = " & pFeat.OID
    End If
    Set pFeat = pFCur.NextFeature
    Loop
    Debug.Print strSql

    ' Get AnnotateLayerPropertiesCollection from layer
    Dim pAnnoLayerPropsColl As IAnnotateLayerPropertiesCollection
    Set pAnnoLayerPropsColl = pLayer.AnnotationProperties
    Dim pAnnoLayerProps As IAnnotateLayerProperties
    pAnnoLayerPropsColl.QueryItem 0, pAnnoLayerProps, Nothing, Nothing
    pAnnoLayerProps.Class = "LabelSel"
    pAnnoLayerProps.WhereClause = strSql
    ' Display the lables
    pLayer.DisplayAnnotation = True
    ' Refresh the Data Frame
    pDoc.ActiveView.Refresh

  4. Select the layer, in the TOC, to label.
  5. Select the features to label.
  6. Click the new UIButtonControl.