How to remove a layer or table from ArcMap


This sample shows how to remove a layer or standalone table from ArcMap. To use this sample, select a standalone table or layer in the table of contents and run to remove them from ArcMap.

How to use

  1. Paste the code into VBA.
  2. In the table of contents, select the layer or standalone table that you wish to remove.
  3. Run the routine.
[VBA]
Public Sub RemoveSelectedLayerorTable()
    
    ' Get the map
    Dim pDoc As IMxDocument
    Dim pMap As IMap
    Set pDoc = ThisDocument
    Set pMap = pDoc.FocusMap
    
    ' Get the selected layer or table
    Dim pSelItem As IUnknown
    Set pSelItem = pDoc.SelectedItem
    If pSelItem Is Nothing Then
        MsgBox "No Feature layer or table selected"
        Exit Sub
        ' Remove a Layer and refresh the map
    ElseIf TypeOf pSelItem Is IFeatureLayer Then
        pMap.DeleteLayer pDoc.SelectedLayer
        Dim pActiveView As IActiveView
        Set pActiveView = pMap
        pActiveView.Refresh
        ' Remove a table
    ElseIf TypeOf pSelItem Is IStandaloneTable Then
        Dim pStTab As IStandaloneTable
        Dim pStTabColl As IStandaloneTableCollection
        Set pStTab = pSelItem
        Set pStTabColl = pMap
        pStTabColl.RemoveStandaloneTable pStTab
    Else
        MsgBox "Selected item is not a table or layer"
        Exit Sub
    End If
    
    ' refresh the TOC
    pDoc.UpdateContents
    
End Sub