English

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

Summary

Note:
This article pertains to ArcGIS versions 8.x. Later versions of ArcGIS may contain different functionality, as well as different names and locations for menus, commands and geoprocessing tools.

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

Note: 
Support for Visual Basic for Applications (VBA) for ArcMap and ArcCatalog ended with the ArcGIS 10.2.2 release, and Esri has not included VBA compatibility setups since version 10.5. See: ArcGIS Desktop and VBA Moving Forward

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'
  1. Right-click the UIButtonControl and select View Source.
  2. Paste this code into the UIButtonControl's click event.
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
  1. Add data to ArcMap.
  2. Switch to Layout View.
  3. Click the new button to insert the scale bar.

Last Published: 8/1/2019

Article ID: 000004966