This sample code demonstrates how to execute Map Algebra expression using IMapAlgebraOp methods
How to use
- Start ArcMap and add an elevation raster dataset.
- Paste the code into VBA.
- Make sure the Spatial Analyst extension is checked.
- Add reference to ESRI SpatialAnalyst Object Library.
- Run the sub from the Macros dialog.
Sub MapAlgebra()
'Get the focused map from MapDocument
Dim pMxDoc As IMxDocument
Set pMxDoc = ThisDocument
Dim pMap As IMap
Set pMap = pMxDoc.FocusMap
'Get the input raster from the first layer in ArcMap
Dim pLayer As ILayer
Set pLayer = pMap.Layer(0)
If Not TypeOf pLayer Is IRasterLayer Then
Exit Sub
End If
Dim pRasLayer As IRasterLayer
Set pRasLayer = pLayer
Dim pInRaster As IRaster
Set pInRaster = pRasLayer.Raster
'Create a RasterMapAlgebraOp operator
Dim pMapAlgebraOp As IMapAlgebraOp
Set pMapAlgebraOp = New RasterMapAlgebraOp
'Set output workspace
Dim pEnv As IRasterAnalysisEnvironment
Set pEnv = pMapAlgebraOp
Dim pWS As IWorkspace
Dim pWSF As IWorkspaceFactory
Set pWSF = New RasterWorkspaceFactory
Set pWS = pWSF.OpenFromFile("c:\temp", 0)
Set pEnv.OutWorkspace = pWS
'Bind a raster
pMapAlgebraOp.BindRaster pInRaster, "R1"
'Execute the Map Algebra expression to calculate slope of the input raster
Dim pOutRaster As IRaster
Set pOutRaster = pMapAlgebraOp.Execute("Slope([R1])")
'Add output into ArcMap as a raster layer
Dim pOutRasLayer As IRasterLayer
Set pOutRasLayer = New RasterLayer
pOutRasLayer.CreateFromRaster pOutRaster
pMap.AddLayer pOutRasLayer
End Sub