How to get the environment from the Spatial Analyst toolbar


This sample code demonstrate how to get Spatial Analyst toolbar environment using RasterSettings object.

How to use

  1. Start ArcMap and add a DEM.
  2. Make sure the Spatial Analyst extension is checked.
  3. Paste the code into VBA.
  4. Add reference to ESRI SpatialAnalyst Object Library.
  5. Add reference to ESRI SpatialAnalystUI Object Library.
  6. Set cellsize and extent in the Options (Spatial Analyst/Options...) dialog.
  7. Run the sub from the Macros dialog.
[VBA]
Sub GetSpatialAnalystToolbarEnvironment()
    '1.0 Get the map from map document
    Dim pMxDoc As IMxDocument
    Set pMxDoc = ThisDocument
    Dim pMap As IMap
    Set pMap = pMxDoc.FocusMap
    
    '2.0 Get the FIRST layer
    Dim pInRasterLayer As IRasterLayer
    Set pInRasterLayer = pMap.Layer(0)
    
    '3.0 Get the raster from raster layer
    Dim pInRaster As IRaster
    Set pInRaster = pInRasterLayer.Raster
    
    '4.0 Create RasterSurfaceOp
    Dim pSurfaceOp As ISurfaceOp
    Set pSurfaceOp = New RasterSurfaceOp
    
    Dim pOpEnv As IRasterAnalysisEnvironment
    Set pOpEnv = pSurfaceOp
    
    '5.0 Get environment from toolbar
    Dim pTBEnv As IRasterAnalysisEnvironment
    Set pTBEnv = New RasterSettings
    
    Dim cs As Double
    cs = 10.5
    Dim enumCellSize As esriRasterEnvSettingEnum
    pTBEnv.GetCellSize enumCellSize, cs
    pOpEnv.SetCellSize enumCellSize, cs
    
    Dim ext As Envelope
    Dim enumExtent As esriRasterEnvSettingEnum
    pTBEnv.GetExtent enumExtent, ext
    pOpEnv.SetExtent enumExtent, ext
    
    '6.0 Create Hillshade
    Dim pOutRaster As IRaster
    Set pOutRaster = pSurfaceOp.Hillshade(pInRaster, 315, 45, False)
    
    '7.0 Create raster layer from the output raster
    Dim pOutRasterLayer As IRasterLayer
    Set pOutRasterLayer = New RasterLayer
    pOutRasterLayer.CreateFromRaster pOutRaster
    pOutRasterLayer.Name = "Hillshade"
    
    '8.0 Add output raster layer to map
    pMap.AddLayer pOutRasterLayer
    
    '9.0 Clean up
    Set pMxDoc = Nothing
    Set pMap = Nothing
    Set pInRasterLayer = Nothing
    Set pInRaster = Nothing
    Set pSurfaceOp = Nothing
    Set pOutRaster = Nothing
    Set pOutRasterLayer = Nothing
    Set pOpEnv = Nothing
    Set pTBEnv = Nothing
End Sub






Additional Requirements
  • Service Pack 1