How to remove the last join from a layer or table in ArcMap


This sample removes the most recently joined table or layer from the selected table or layer in the table of contents. It performs the same function as removing the top most table listed under joins in the Joins and Relates tab in layer or table properties
Once the sample is executed, you can click the Joins and Relates tab in layer or table properties to see that the table has been unjoined. If the table window was opened when you ran the sample, you must close and re-open the table window in order to remove the joined columns.

How to use

  1. Paste the code into VBA.
  2. In the table of contents, select the joined layer or table. Thesample will warn you if the layer or table has no joins.
  3. Execute the routine.
[VBA]
Public Sub RemoveLastJoin()
    
    ' Get the map
    Dim pDoc As IMxDocument
    Set pDoc = ThisDocument
    Dim pMap As IMap
    Set pMap = pDoc.FocusMap
    
    ' Get the selected layer or table
    Dim pSelItem As IUnknown
    Set pSelItem = pDoc.SelectedItem
    If Not TypeOf pSelItem Is IDisplayTable Then
        MsgBox "No Feature layer or table selected"
        Exit Sub
    End If
    
    ' Make sure the selected layer is joined
    Dim pDispTable As IDisplayTable
    Dim pTable As ITable
    Set pDispTable = pSelItem
    Set pTable = pDispTable.DisplayTable
    If Not TypeOf pTable Is IRelQueryTable Then
        MsgBox "The layer or table is not joined"
        Exit Sub
    End If
    
    ' Get the source table of the current join
    ' object (RelQueryTable)
    Dim pRelQTab As IRelQueryTable
    Set pRelQTab = pTable
    Set pTable = pRelQTab.SourceTable
    
    ' UnJoin
    Dim pDispRC As IDisplayRelationshipClass
    Dim pRQTInfo As IRelQueryTableInfo
    Set pDispRC = pSelItem
    ' If more than one table had been joined, replace
    ' the current join with the previous join
    If TypeOf pTable Is IRelQueryTable Then
        Set pRelQTab = pTable
        Set pRQTInfo = pRelQTab
        pDispRC.DisplayRelationshipClass pRelQTab.RelationshipClass, pRQTInfo.JoinType
        ' If one table has been joined, remove all joins
    Else
        pDispRC.DisplayRelationshipClass Nothing, esriLeftInnerJoin
    End If
    
End Sub