English

How To: Programmatically export selected features to a shapefile

Summary

This article shows how to export a selected set of features in ArcMap to a new shapefile using VBA and ArcObjects.

Procedure

  1. Open ArcMap.
  2. Open the Visual Basic Editor.

    In ArcMap, select Tools > Macros > Visual Basic Editor.

  3. In the Project Explorer window, expand the Project folder and select 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 map documents, open the code in the Normal.mxt ThisDocument code module.

  4. Paste the following code into the code module.

    Code:
    Sub ExportFeatureClass()

    Dim pDoc As IMxDocument
    Dim pMap As IMap
    Dim pFLayer As IFeatureLayer
    Dim pFc As IFeatureClass
    Dim pINFeatureClassName As IFeatureClassName
    Dim pDataset As IDataset
    Dim pInDsName As IDatasetName
    Dim pFSel As IFeatureSelection
    Dim pSelSet As ISelectionSet
    Dim pFeatureClassName As IFeatureClassName
    Dim pOutDatasetName As IDatasetName
    Dim pWorkspaceName As IWorkspaceName
    Dim pExportOp As IExportOperation

    Set pDoc = ThisDocument
    Set pMap = pDoc.FocusMap
    Set pFLayer = pMap.Layer(0)
    Set pFc = pFLayer.FeatureClass

    'Get the FcName from the featureclass
    Set pDataset = pFc
    Set pINFeatureClassName = pDataset.FullName
    Set pInDsName = pINFeatureClassName

    'Get the selection set
    Set pFSel = pFLayer
    Set pSelSet = pFSel.SelectionSet

    'Define the output feature class name
    Set pFeatureClassName = New FeatureClassName
    Set pOutDatasetName = pFeatureClassName
    pOutDatasetName.Name = "TestExport"
    Set pWorkspaceName = New WorkspaceName
    pWorkspaceName.PathName = "c:\temp"
    pWorkspaceName.WorkspaceFactoryProgID = _
    "esriCore.shapefileworkspacefactory.1"
    Set pOutDatasetName.WorkspaceName = pWorkspaceName
    pFeatureClassName.FeatureType = esriFTSimple
    pFeatureClassName.ShapeType = esriGeometryAny
    pFeatureClassName.ShapeFieldName = "Shape"

    'Export
    Set pExportOp = New ExportOperation
    pExportOp.ExportFeatureClass pInDsName, Nothing, _
    pSelSet, Nothing, pOutDatasetName, 0

    End Sub

  5. If necessary, modify the pWorkspaceName.PathName statement to point to a folder where the new shapefile should be created.
  6. Close the Visual Basic Editor.
  7. Add a feature class to ArcMap and select some features to export.
    Note:
    The first layer in the map must be a vector layer, otherwise a "type mismatch" error will occur.

  8. Run the code.

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


    Look in the folder you specified in the PathName setting to see the shapefiles created. Add the shapefile to the map document to see the features that were created.

Related Information