English

How To: Change the projection of a dataframe programmatically

Summary

This document demonstrates how to programmatically change the coordinate system (projection) of a dataframe.

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:
    Private Sub Change_Projection()
    Dim pIMxDoc As IMxDocument
    Set pIMxDoc = ThisDocument

    Dim pMap As IMap
    Set pMap = pIMxDoc.FocusMap

    Dim pSpatRefFact As ISpatialReferenceFactory
    'Set the spatial reference factory to a new spatial referenceEnvironment
    Set pSpatRefFact = New SpatialReferenceEnvironment

    Dim pspatref As ISpatialReference
    'Read a .prj file with projection data
    Set pspatref = pSpatRefFact.CreateESRISpatialReferenceFromPRJFile _
    ("E:\80testing\states\prj.adf")
    If Not pspatref Is Nothing Then
    MsgBox "Created Spatial reference successfully"
    End If

    ' put the new spatial reference into the map
    If Not pspatref Is Nothing Then
    Set pMap.SpatialReference = pspatref
    Dim pActView As IActiveView
    Set pActView = pMap
    pActView.Refresh
    MsgBox "done!!!"
    End If
    Dim pSecSpatRef As ISpatialReference
    Set pSecSpatRef = pMap.SpatialReference
    If Not pSecSpatRef Is Nothing Then
    MsgBox "Assigning Spatial reference to map was successful"
    End If
    End Sub

  5. Modify the path to the .prj file to match your data.
  6. Close the Visual Basic Editor.
  7. Run the code.

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