English

How To: Programatically export all layers in the ArcMap TOC

Summary

Instructions provided demonstrate how to export all layers in the ArcMap TOC programatically.

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 the Project's ThisDocument code module will only run in the current map document. 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.

    Code:
    Public Sub ExportAll_TOC()

    Dim pDoc As IMxDocument
    Dim pEnumLayer As IEnumLayer
    Dim pLayer As IFeatureLayer
    Dim pName As IName
    Dim pLayerSet As ISet
    Dim pMap As IMap
    Dim pFC As IFeatureClass
    Dim pINFeatureClassName As IFeatureClassName
    Dim pDataset As IDataset
    Dim pInDSName As IDatasetName
    Dim pFields As IFields
    Dim pField As IField
    Dim pGeometryDef As IGeometryDef
    Dim pFeatureClassName As IFeatureClassName
    Dim pOutDatasetName As IDatasetName
    Dim pWorkspaceName As IWorkspaceName
    Dim pExportOp As IExportOperation

    Set pDoc = Application.Document
    Set pMap = pDoc.FocusMap
    Set pEnumLayer = pMap.Layers
    Set pLayerSet = New esriSystem.Set
    pEnumLayer.Reset
    Set pLayer = pEnumLayer.Next

    Do Until pLayer Is Nothing
    'Enumerate through the layers in the TOC and
    'Get the Feature Class Name from the featureclass
    Set pFC = pLayer.FeatureClass
    Set pDataset = pFC
    Set pINFeatureClassName = pDataset.FullName
    Set pInDSName = pINFeatureClassName
    Set pFields = pFC.Fields
    Set pField = pFields.Field(lGeomIndex)
    Set pGeometryDef = pField.GeometryDef
    Set pFeatureClassName = New FeatureClassName
    Set pOutDatasetName = pFeatureClassName

    'Assign name to each exported layer
    pLayerSet.Add pLayer
    For i = 0 To pLayerSet.Count - 1
    X = pLayerSet.Count - 1
    pOutDatasetName.Name = pDataset.Name & "_Export"
    Next i

    Set pWorkspaceName = New WorkspaceName
    pWorkspaceName.PathName = "C:\temp"
    pWorkspaceName.WorkspaceFactoryProgID = "esriDataSourcesFile.ShapefileWorkspaceFactory"
    Set pOutDatasetName.WorkspaceName = pWorkspaceName

    'Export the layers in the TOC
    Set pExportOp = New ExportOperation
    pExportOp.ExportFeatureClass pInDSName, Nothing, Nothing, pGeometryDef, _
    pOutDatasetName, hWnd

    Set pLayer = pEnumLayer.Next

    Loop

    'Update the table of contents
    pDoc.UpdateContents

    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.