How to perform cell statistics using RasterLocalOp


This sample code demonstrates how to perform cell-by-cell statistics using ILocalOp::LocalStatistics

How to use

  1. Start ArcMap and add multiple rasters.
  2. Paste the code into VBA.
  3. Make sure the Spatial Analyst extension is checked.
  4. Add reference to ESRI SpatialAnalyst Object Library.
  5. Run the sub from the Macros dialog.
[VBA]
Sub CellStatistics()
    'Get the focused map from MapDocument
    Dim pMxDoc As IMxDocument
    Set pMxDoc = ThisDocument
    Dim pMap As IMap
    Set pMap = pMxDoc.FocusMap
    
    'Create a RasterBandCollection from the raster layers in ArcMap
    Dim pEnumLayers As IEnumLayer
    Set pEnumLayers = pMap.Layers
    
    Dim pLayer As ILayer
    Dim pRasLayer As IRasterLayer
    
    Dim pRaster As IRaster
    Dim pRBCollTmp As IRasterBandCollection
    Dim pRBand As IRasterBand
    
    Dim pRBColl As IRasterBandCollection
    Set pRBColl = New Raster
    
    'Loop through all layers in ArcMap
    Set pLayer = pEnumLayers.Next
    Do Until pLayer Is Nothing
        If TypeOf pLayer Is IRasterLayer Then
            Set pRasLayer = pLayer
            Set pRaster = pRasLayer.Raster
            Set pRBCollTmp = pRaster
            Set pRBand = pRBCollTmp.Item(0)
            pRBColl.AppendBand pRBand
        End If
        Set pLayer = pEnumLayers.Next
    Loop
    
    'Create a RasterLocalOp operator
    Dim pLocalOp As ILocalOp
    Set pLocalOp = New RasterLocalOp
    
    'Set output workspace
    Dim pEnv As IRasterAnalysisEnvironment
    Set pEnv = pLocalOp
    
    Dim pWS As IWorkspace
    Dim pWSF As IWorkspaceFactory
    Set pWSF = New RasterWorkspaceFactory
    Set pWS = pWSF.OpenFromFile("c:\temp", 0)
    Set pEnv.OutWorkspace = pWS
    
    'Compute cell-by-cell (local) statistics
    Dim pOutRaster As IRaster
    Set pOutRaster = pLocalOp.LocalStatistics(pRBColl, esriGeoAnalysisStatsMean)
    
    'Add output into ArcMap as a raster layer
    Dim pOutRasLayer As IRasterLayer
    Set pOutRasLayer = New RasterLayer
    pOutRasLayer.CreateFromRaster pOutRaster
    pMap.AddLayer pOutRasLayer
End Sub