HOW TO

Get the selected ArcMap layer programmatically with VBA

Last Published: April 25, 2020

Summary

Steps to get the selected object in ArcMap's Table of Contents (TOC) using VBA.

Procedure



  1. Get a reference to the current Contents View.

    Code:
    Dim pDoc As IMxDocument
    Dim pCV As IContentsView
    Set pDoc = ThisDocument
    Set pCV = pDoc.CurrentContentsView


    Note:
    Contents View is a tab in ArcMap's TOC. ArcMap has two contents views, Display and Source.

  2. Determine the type of the selected object(s).

    Code:
    Dim pFLayer As IFeatureLayer
    Dim mySet As esriCore.ISet
    Set mySet = New esriCore.Set
    If (TypeOf pCV.SelectedItem Is IFeatureLayer) Then
    Set pFLayer = pCV.SelectedItem
    Debug.Print pFLayer.Name
    ElseIf (TypeOf pCV.SelectedItem is ISet) Then
    Set mySet = pCV.SelectedItem
    Set pFLayer = mySet.Next
    Do Until pFLayer Is Nothing
    Debug.Print pFLayer.Name
    Set pFLayer = mySet.Next
    Loop
    End If


    Note:
    The return value for IContentsView.SelectedItem is of type variant because there are many possible objects that can be returned. In the Display tab, the selected item could be a map, layer, or a legend group object. In the Source tab, the selected item could be any of the above plus a Table, Feature Dataset or Workspace. If multiple items are selected a Set object is returned.

Article ID:000002527

Software:
  • ArcMap 8 x

Receive notifications and find solutions for new or common issues

Get summarized answers and video solutions from our new AI chatbot.

Download the Esri Support App

Discover more on this topic

Get help from ArcGIS experts

Contact technical support

Download the Esri Support App

Go to download options