This sample joins the attributes of the first table in the table of contents to the first layer in the table of contents in ArcMap. You will be prompted for the join field which must be named the same in both the layer and table for the purposes of this sample. This sample performs the same function as the join command from the layer context menu.
Once the join is completed, you will be able to see it listed in the Joins and Relates tab of layer properties. If the layer's table was opened when you ran the script, you must close and re-open it to see the joined columns.
How to use
- Paste the function into your code file.
- Make sure that the first layer and the first table in the table of contents are the ones that you want to join. Optionally, you can modify the code to specify the proper layer and table.
- Execute the routine.
- When prompted, provide the name of the join column which must be in both the layer and the table. You can later modify the code to allow different join column names.
Public Sub JoinTabletoLayer()
On Error GoTo EH
Dim pDoc As IMxDocument
Dim pMap As IMap
Set pDoc = ThisDocument
Set pMap = pDoc.FocusMap
' Get the first layer in the table on contents
Dim pFeatLayer As IFeatureLayer
Dim pDispTable As IDisplayTable
Dim pFCLayer As IFeatureClass
Dim pTLayer As ITable
If pMap.LayerCount = 0 Then
MsgBox "Must have at least one layer"
Exit Sub
End If
Set pFeatLayer = pMap.Layer(0)
Set pDispTable = pFeatLayer
Set pFCLayer = pDispTable.DisplayTable
Set pTLayer = pFCLayer
' Get the first table in the table on contents
Dim pTabCollection As IStandaloneTableCollection
Dim pStTable As IStandaloneTable
Dim pDispTable2 As IDisplayTable
Dim pTTable As ITable
Set pTabCollection = pMap
If pTabCollection.StandaloneTableCount = 0 Then
MsgBox "Must have atleast one table"
Exit Sub
End If
Set pStTable = pTabCollection.StandaloneTable(0)
Set pDispTable2 = pStTable
Set pTTable = pDispTable2.DisplayTable
' Prompt for the join field, in this example both joined
' fields must be named the same.
Dim strJnField As String
strJnField = InputBox("Provide the name of the join field:", "Joining a table to a layer", _
"FIPS_CODE")
' Create virtual relate
Dim pMemRelFact As IMemoryRelationshipClassFactory
Dim pRelClass As IRelationshipClass
Set pMemRelFact = New MemoryRelationshipClassFactory
Set pRelClass = pMemRelFact.Open("TabletoLayer", pTTable, strJnField, pTLayer, _
strJnField, "forward", "backward", esriRelCardinalityOneToMany)
' use Relate to perform a join
Dim pDispRC As IDisplayRelationshipClass
Set pDispRC = pFeatLayer
pDispRC.DisplayRelationshipClass pRelClass, esriLeftOuterJoin
Exit Sub
EH:
MsgBox Err.Number & " " & Err.Description
End Sub