Change the feature class of a layer file using ArcObjects

Last Published: April 25, 2020


This article provides a code sample showing how to change the feature class which a layer file references. This would be useful if the feature class had been renamed or moved and the link between the layer file and the data needed to be recreated.


In the following example, the TEST.LYR file will be modified to point to a different shapefile called WELLS, located in the C:\WORK directory.

  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 it is necessary to store the code in all map documents, open the Normal.mxt ThisDocument code module instead.

  4. Copy the following code into the code module.
    Public Sub test()
    ' open existing lyr file.
    Dim pGxLayer As IGxLayer
    Dim pGxFile As IGxFile
    Set pGxLayer = New GxLayer
    Set pGxFile = pGxLayer
    pGxFile.Path = "D:\work\test.lyr"
    ' get new feature class.
    Dim pWorkspaceFactory As IWorkspaceFactory
    Set pWorkspaceFactory = New ShapefileWorkspaceFactory
    Dim pWorkspace As IFeatureWorkspace
    Set pWorkspace = pWorkspaceFactory.OpenFromFile("d:\work", 0)
    Dim pNewFeatClass As IFeatureClass
    Set pNewFeatClass = pWorkspace.OpenFeatureClass("wells")
    ' change lyr file's feature class.
    Dim pLayer As ILayer
    Set pLayer = pGxLayer.Layer
    Dim pFeatLayer As IFeatureLayer
    Set pFeatLayer = pLayer
    Set pFeatLayer.FeatureClass = pNewFeatClass
    Set pGxLayer.Layer = pFeatLayer
    End Sub

  5. Close the Visual Basic Editor.
  6. Run the code.

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

Article ID:000006096

  • ArcMap 9 x
  • ArcMap 8 x

Get help from ArcGIS experts

Contact technical support

Download the Esri Support App

Go to download options

Discover more on this topic