English

How To: Zoom to the XY extent of a feature layer in ArcMap

Summary

This document contains a VBA example that zooms to the XY domain of the selected layer in ArcMap's Table of Contents.

Procedure

  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. Right-click and select View Code.
    [O-Image] Visual Basic Project  Explorer
    Note:
    Code in ThisDocument code module will only run in the current map document. To store the code in all your map documents, open the Normal.mxt ThisDocument code module.

  4. Copy the following code into the code module.

    Code:
    Public Sub ZoomToDomainExtent()
    Dim pMxDoc As IMxDocument
    Dim pMap As IMap
    Dim pActiveView As IActiveView
    Dim pContentsView As IContentsView

    Set pMxDoc = Application.Document
    Set pMap = pMxDoc.FocusMap
    Set pActiveView = pMap
    Set pContentsView = pMxDoc.CurrentContentsView

    Dim pLayer As ILayer
    Dim pDataSet As IDataset
    Dim pFeatureLayer As IFeatureLayer
    Dim pGeoDataset As IGeoDataset

    If Not TypeOf pContentsView.SelectedItem Is ILayer Then Exit Sub
    Set pLayer = pContentsView.SelectedItem
    Set pFeatureLayer = pLayer
    Set pGeoDataset = pFeatureLayer

    Dim pSpatialReference As ISpatialReference
    Dim pEnvelope As IEnvelope
    Set pSpatialReference = pGeoDataset.SpatialReference
    Set pEnvelope = New Envelope

    Dim dXmax As Double
    Dim dYmax As Double
    Dim dXmin As Double
    Dim dYmin As Double

    pSpatialReference.GetDomain dXmin, dXmax, dYmin, dYmax
    pEnvelope.XMax = dXmax
    pEnvelope.YMax = dYmax
    pEnvelope.XMin = dXmin
    pEnvelope.YMin = dYmin

    pActiveView.Extent = pEnvelope
    pActiveView.Refresh

    End Sub

  5. Close the Visual Basic Editor.
  6. Select Tools > Customize.
  7. Switch to the Commands tab.
  8. Select Macros from the Categories list.
  9. Switch the Save in dropdown list to the name of the current project.
  10. Drag the ZoomtoDomainExtent macro to a tool bar.
  11. Select the layer you wish to zoom to from the Table of Contents.
  12. Click the macro button.