English

How To: Programmatically find the path of a layer in ArcMap

Summary

This VBA sample code shows the steps required to find the path of a layer in ArcMap.

Procedure

  1. Get a reference to the first layer in your map.

    Code:
    Option Explicit

    Sub GetPath()
    Dim pDoc As IMxDocument
    Dim pLayer As ILayer
    Set pDoc = ThisDocument
    Set pLayer = pDoc.FocusMap.Layer(0)


    Note:
    pDoc.FocusMap.Layer(0) gets the first layer in the map. Layer(1) will return the second layer.

  2. Get access to the dataset. The method depends on what type of layer you have. This macro will work for feature, raster, and tin layers.

    Code:
    Dim pDs As IDataset
    If (TypeOf pLayer Is IFeatureLayer) Or (TypeOf pLayer Is IRasterLayer) Then
    ' Query Interface to IGeoDataset, then to IDataset.
    Dim pGD As IGeoDataset
    Set pGD = pLayer
    'Qi from GeoDataset to Dataset
    Set pDs = pGD

    ElseIf (TypeOf pLayer Is ITinLayer) Then
    'Qi from Layer to TinLayer
    Dim pTinLayer As ITinLayer
    Set pTinLayer = pLayer
    Set pDs = pTinLayer.Dataset

    Else
    MsgBox "Layer is not a FeatureLayer, RasterLayer, or TinLayer. Exiting..."
    Exit Sub
    End If


    Note:
    Query Interface (QI) retrieves other interfaces allowing access to the methods and properties on that interface.

  3. Use the PathName property on IWorkspace to return the Path Name for the layer.

    Code:
    'Get the Workspace
    Dim pW As IWorkspace
    Set pW = pDs.Workspace
    MsgBox pW.PathName
    End Sub