Insert a legend into ArcMap using ArcObjects

Last Published: April 25, 2020


The sample code in this article shows how to insert a legend into ArcMap using VBA and ArcObjects.


  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 then right-click and select View Code.
    [O-Image] Visual Basic Project  Explorer
    Code in the Project's ThisDocument code module will only run in the current map document. If you want to store the code in all your map documents, open the Normal.mxt ThisDocument code module instead.

  4. Copy the following code into the code module.

    Public Sub AddMapSurrounds()
    Dim pMxDoc As IMxDocument
    Dim pActiveView As IActiveView
    Dim pEnv As IEnvelope
    Dim pId As New UID
    Dim pMapSurround As IMapSurround

    Set pMxDoc = ThisDocument
    Set pActiveView = pMxDoc.PageLayout
    Set pEnv = New Envelope
    pEnv.PutCoords 7.5, 0.2, 8.5, 4

    pId.Value = "esricore.Legend"
    Set pMapSurround = CreateSurround(pId, pEnv, "Legend", pMxDoc.FocusMap, pMxDoc.PageLayout)
    pActiveView.PartialRefresh esriViewGraphics, Nothing, Nothing

    End Sub

    Private Function CreateSurround(pId As UID, pEnv As IEnvelope, strName As String, _
    pMap As IMap, pPageLayout As IPageLayout) As IMapSurround
    Dim pGc As IGraphicsContainer
    Dim pActiveView As IActiveView
    Dim pMapSurroundFrame As IMapSurroundFrame
    Dim pMapSurround As IMapSurround
    Dim pMapFrame As IMapFrame
    Dim pElement As IElement

    Set pGc = pPageLayout
    Set pMapFrame = pGc.FindFrame(pMap)
    Set pMapSurroundFrame = pMapFrame.CreateSurroundFrame(pId, Nothing)
    pMapSurroundFrame.MapSurround.Name = strName

    Set pElement = pMapSurroundFrame
    Set pActiveView = pPageLayout
    pElement.Geometry = pEnv
    pElement.Activate pActiveView.ScreenDisplay
    pGc.AddElement pElement, 0
    Set CreateSurround = pMapSurroundFrame.MapSurround

    End Function

  5. Close the Visual Basic Editor.
  6. Run the AddMapSurrounds subroutine.

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

Article ID:000004662

  • 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