English

How To: Programmatically insert a scale bar into an ArcMap layout

Summary

This article contains sample code that shows how to insert a scale bar into an ArcMap layout using VBA and ArcObjects.

Procedure

 

  1. Open ArcMap.
  2. Create a new UIButtonControl: How To: Create a new UIButtonControl​
    Note:
    For more information on creating a UIControl, see the ArcGIS Desktop Help topic: 'Creating custom commands with VBA and UI Controls'
  3. Right-click the UIButtonControl and select View Source.
  4. Paste this code into the UIButtonControl's click event.
     
    Code:
    Sub InsertScaleBar()
    Dim pMxDoc As IMxDocument
    Dim pMap As IMap
    Dim pGC As IGraphicsContainer
    Dim pElem As IElement
    Dim pMapFrame As IMapFrame
    Dim pMSFrame As IMapSurroundFrame
    Dim pMS As IMapSurround
    Dim pGeom As IGeometry
    Dim pEnv As IEnvelope
    Dim pActView As IActiveView
    
    Set pMxDoc = ThisDocument
    Set pGC = pMxDoc.PageLayout
    
    ' Get map frame for map of interest
    ' (in this case, the focus map)
    pGC.Reset
    Set pElem = pGC.Next
    Do While (Not pElem Is Nothing)
        Set pMapFrame = Nothing
        If (TypeOf pElem Is IMapFrame) Then
            Set pMapFrame = pElem
            If (pMapFrame.Map Is pMxDoc.FocusMap) Then
                Exit Do
            End If
        End If
        Set pElem = pGC.Next
    Loop
    
    If (pMapFrame Is Nothing) Then
        MsgBox "Couldn't find map frame"
        Exit Sub
    End If
    
    ' Create scale bar object
    Set pMS = New AlternatingScaleBar
    Set pMS.Map = pMapFrame.Map
    
    ' Create surround frame for scale bar
    Set pMSFrame = New MapSurroundFrame
    Set pMSFrame.MapFrame = pMapFrame
    Set pMSFrame.MapSurround = pMS
    
    ' Set the map surround frame size and position
    Set pEnv = New Envelope
    pEnv.PutCoords 2, 2, 4, 2.5
    
    Set pElem = pMSFrame
    pElem.Geometry = pEnv
                
    ' Add to graphics container
    pGC.AddElement pMSFrame, 0
    
    ' Refresh display
    pMxDoc.ActiveView.Refresh
    End Sub
  5. Add data to ArcMap.
  6. Switch to Layout View.
  7. Click the new button to insert the scale bar.