Cell Statistics


This sample code demonstrates how to use ILocalOp::LocalStatistics of Spatial Analyst Objects in VBA

How to use:
  1. Run ArcMap and add 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 Extension Object Library" and "ERSI Spatial Analyst Shared Object Library".
  5. From the Macros dialog, run CellStatistics subroutine.
Sub CellStatistics() 
    ' Get the Map     
    Dim pMxDoc As IMxDocument
    Set pMxDoc = ThisDocument
    Dim pMap As IMap
    Set pMap = pMxDoc.FocusMap  

   ' Get the rasterbandcollection from the raster layers in ArcMap     
    Dim pEnumLayers As IEnumLayer
    Set pEnumLayers = pMap.Layers
    Dim pGeoDs As IGeoDataset
    Dim pRBandC As IRasterBandCollection
    Set pRBandC = New Raster
    Dim pRBandC1 As IRasterBandCollection
    Dim pRLayer As IRasterLayer
    Dim pRaster As IRaster
    Dim pRBand As IRasterBand
    Dim pLayer As ILayer
    Set pLayer = pEnumLayers.Next
    Do Until pLayer Is Nothing
    If TypeOf pLayer Is IRasterLayer Then
        Set pRLayer = pLayer
        Set pRaster = pRLayer.Raster
        Set pRBandC1 = pRaster
        Set pRBand = pRBandC1.Item(0)
        pRBandC.AppendBand pRBand
    End If
    Set pLayer = pEnumLayers.Next
    Set pGeoDs = pRBandC  

   ' Create a Spatial 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 

    ' Perform the Cell Statistics     
    Dim pOutRaster As IRaster
    Set pOutRaster = pLocalOp.LocalStatistics(pGeoDs, esriGeoAnalysisStatsMean) 

    ' Add it into ArcMap 
    Dim pRLayer1 As IRasterLayer
    Set pRLayer1 = New RasterLayer
    pRLayer1.CreateFromRaster pOutRaster
    pMap.AddLayer pRLayer1

End Sub