Using RasterMathOps


This sample code demonstrates how to use IMathOp::Plus of Spatial Analyst Objects in VBA

How to use:
  1. Run ArcMap and two rasters in ArcMap.
  2. Paste the code into VBA.
  3. Make sure the Spatial Analyst Extension is checked.
  4. Add reference to ERSI Spatial Analyst Shared Object Library.
  5. From the Macros dialog, run Calculator_Math subroutine.
Sub Calculator_Math() 
    ' Get the Map     
    Dim pMxDoc As IMxDocument
    Set pMxDoc = ThisDocument
    Dim pMap As IMap
    Set pMap = pMxDoc.FocusMap  

   ' Get the 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 pGeoDs As IGeoDataset
    Set pGeoDs = pRLayer.Raster    

   ' Get another raster from the second layer in ArcMap     
    Dim pLayer1 As ILayer
    Set pLayer1 = pMap.Layer(1)
    If Not TypeOf pLayer1 Is IRasterLayer Then
        Exit Sub
    End If
    Dim pGeoDs1 As IGeoDataset
    Set pRLayer = pLayer1
    Set pGeoDs1 = pRLayer.Raster  

   ' Create a Spatial operator     
    Dim pMathOp As IMathOp
    Set pMathOp = New RasterMathOps 

    ' Set output workspace 
    Dim pEnv As IRasterAnalysisEnvironment
    Set pEnv = pMathOp
    Dim pWS As IWorkspace
    Dim pWSF As IWorkspaceFactory
    Set pWSF = New RasterWorkspaceFactory
    Set pWS = pWSF.OpenFromFile("c:\temp",0)
    Set pEnv.OutWorkspace = pWS 

    ' Perform the operation     
    Dim pOutRaster As IRaster
    Set pOutRaster = pMathOp.Plus(pGeoDs, pGeoDs1) 

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

End Sub