This sample code demonstrate how to get Spatial Analyst toolbar environment using RasterSettings object.
How to use
- Start ArcMap and add a DEM.
- Make sure the Spatial Analyst extension is checked.
- Paste the code into VBA.
- Add reference to ESRI SpatialAnalyst Object Library.
- Add reference to ESRI SpatialAnalystUI Object Library.
- Set cellsize and extent in the Options (Spatial Analyst/Options...) dialog.
- Run the sub from the Macros dialog.
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