Map Algebra in VBA


This sample code demonstrates how to run slope through IMapAlgebraOp of Spatial Analyst Objects in VBA

How to use:
  1. Run ArcMap and add an raster dataset.
  2. Make sure the Spatial Analyst Extension is checked.
  3. Add reference to ERSI Spatial Analyst Shared Object Library.
  4. Paste the code into VBA.
  5. From the Macros dialog, run MapAlgebra subroutine.
Sub MapAlgebra() 
    ' Get the Map     
    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 pRLayer As IRasterLayer
    Set pRLayer = pLayer
    Dim pInRaster As IRaster
    Set pInRaster = pRLayer.Raster  

   ' Create a Spatial operator     
    Dim pAlgbOp As IMapAlgebraOp
    Set pAlgbOp = New RasterMapAlgebraOp 

    ' Set output workspace 
    Dim pEnv As IRasterAnalysisEnvironment
    Set pEnv = pAlgbOp
    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 
    Call pAlgbOp.BindRaster(pInRaster, "R1") 

    ' Perform Spatial operation     
    Dim pOutRaster As IRaster
    Set pOutRaster = pAlgbOp.Execute("Slope([R1])") 

    ' Add it into ArcMap 
    Set pRLayer = New RasterLayer
    pRLayer.CreateFromRaster pOutRaster
    pMap.AddLayer pRLayer

End Sub