Remove Feature From Selection


This sample shows one way to remove a feature from the map's selection. For simplicity, the script uses the first feature found in the map's current feature selection.

One tricky step is firing the SelectionChanged event. This should be done in two places, on the Map and on the FeatureLayer, clients can be listening to either one.

How to use:
  1. Paste the code into VBA.
  2. Select a feature in the map.
  3. Run the 'RemoveFeatureFromSelectionSet' macro .
  4. The selected feature should be removed.
  5. To verify the events are working, open the attribute tables and the editor's attribute window before running the script.
Public Sub RemoveFeatureFromSelectionSet()
  Dim pActiveView As IActiveView
  Dim pEnumFeature As IEnumFeature
  Dim pEnumFeatureSetup As IEnumFeatureSetup
  Dim pFeature As IFeature
  Dim pFeatureLayer As IFeatureLayer
  Dim pFeatureSelection As IFeatureSelection
  Dim pMxDoc As IMxDocument
  Dim pMap As IMap
  Dim pSelectionEvents As ISelectionEvents
  Dim pSelectionSet As ISelectionSet
  Set pMxDoc = Application.Document
  Set pMap = pMxDoc.FocusMap
  If pMap.SelectionCount = 0 Then Exit Sub
  Set pActiveView = pMap 'QI
  'For simplicity, get a reference to the first selected feature
  Set pEnumFeature = pMap.FeatureSelection
  'Set AllFields equal to True to ensure OIDs are returned
  Set pEnumFeatureSetup = pEnumFeature 'QI
  pEnumFeatureSetup.AllFields = True
  Set pFeature = pEnumFeature.Next
  Set pFeatureLayer = GetFeatureLayer(pMap, pFeature.Class)
  If pFeatureLayer Is Nothing Then Exit Sub
  'Flag the area of the old selection to refresh later
  pActiveView.PartialRefresh esriViewGeoSelection, Nothing, pFeature.Shape.Envelope
  'Remove the feature from the selection
  Set pFeatureSelection = pFeatureLayer 'QI
  Set pSelectionSet = pFeatureSelection.SelectionSet
  pSelectionSet.RemoveList 1, pFeature.OID
  'Broadcast the selection changed events
  Set pSelectionEvents = pMap 'QI
End Sub

Private Function GetFeatureLayer(pMap As IMap, pFeatureClass As IFeatureClass) As IFeatureLayer
  Dim pEnumLayer As IEnumLayer
  Dim pFeatureLayer As IFeatureLayer
  Dim pUID As New UID
  pUID = "{E156D7E5-22AF-11D3-9F99-00C04F6BC78E}"
  Set pEnumLayer = pMap.Layers(pUID)
  Set pFeatureLayer = pEnumLayer.Next
  Do While Not pFeatureLayer Is Nothing
    If pFeatureLayer.FeatureClass Is pFeatureClass Then
      Set GetFeatureLayer = pFeatureLayer
      Exit Function
    End If
    Set pFeatureLayer = pEnumLayer.Next
End Function