HOW TO

Switch the selected set of features in ArcMap using ArcObjects

Last Published: April 25, 2020

Summary

This sample code performs the same functionality as the Switch Selection button in ArcMap.

Procedure

Use ISelectionSet::Combine with the esriSetDifference operation to get the difference between the selection set and all the features in the layer.

  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. Right-click and select View Code.
    [O-Image] Visual Basic Project  Explorer
    Note:
    Code in 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.

  4. Copy the following code into the code module.

    Code:
    Sub SwitchSelection()

    Dim pDoc As IMxDocument
    Set pDoc = ThisDocument

    Dim pMap As IMap
    Set pMap = pDoc.FocusMap

    'Get the Feature Selection
    Dim pFLayer As IFeatureLayer
    Set pFLayer = pMap.Layer(0)
    Dim pFSel As IFeatureSelection
    Set pFSel = pFLayer

    'Get the set of selected features
    Dim pSelFeats As ISelectionSet
    Set pSelFeats = pFSel.SelectionSet
    Debug.Print "Selected Features " & pSelFeats.Count
    'Get a selection set of all features
    Dim pAllFeats As ISelectionSet
    Set pAllFeats = pFLayer.FeatureClass.Select(Nothing, _
    esriSelectionTypeIDSet, esriSelectionOptionNormal, Nothing)
    Debug.Print "Total Features " & pAllFeats.Count

    'Switch the Selection
    Dim pNewSel As ISelectionSet
    pAllFeats.Combine pSelFeats, esriSetDifference, pNewSel
    Debug.Print "New Selection " & pNewSel.Count
    Set pFSel.SelectionSet = pNewSel
    pDoc.ActiveView.Refresh
    End Sub


  5. Close the Visual Basic Editor.
  6. Add data to ArcMap and select some features.
  7. Run the code.

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

Article ID:000004816

Software:
  • ArcMap 9 x
  • 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