This sample code demonstrates how to perform cell-by-cell statistics using ILocalOp::LocalStatistics
How to use
- Start ArcMap and add multiple rasters.
- 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 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