This sample code demonstrates how to create a zonal statistics table from feature or raster zones using IZonalOp::ZonalStatisticsAsTable method
How to use
- Run ArcMap and add a zone dataset and a value raster as first and second layer respectively.
- Make sure the Spatial Analyst Extension is checked.
- Add reference to ESRI SpatialAnalyst Object Library.
- Add reference to ESRI GeoAnalyst Object Library.
- Paste the code into VBA.
- Change field name (sFieldName) in the code.
- Run the sub from the Macros dialog.
Sub ZonalStatistics()
'Get the focused map from MapDocument
Dim pMxDoc As IMxDocument
Set pMxDoc = ThisDocument
Dim pMap As IMap
Set pMap = pMxDoc.FocusMap
'Get the zone dataset (feature or raster) from the first layer in ArcMap
Dim pLayer As ILayer
Set pLayer = pMap.Layer(0)
Dim pZoneGeoDataset As IGeoDataset
Dim sFieldName As String
sFieldName = "ZoneID"
'Create a FeatureClassDescriptor from featureclass zone dataset
If TypeOf pLayer Is IFeatureLayer Then
Dim pFLayer As IFeatureLayer
Set pFLayer = pLayer
Dim pFClass As IFeatureClass
Set pFClass = pFLayer.FeatureClass
Dim pFDescriptor As IFeatureClassDescriptor
Set pFDescriptor = New FeatureClassDescriptor
pFDescriptor.Create pFClass, Nothing, sFieldName
Set pZoneGeoDataset = pFDescriptor
'Create a RasterDescriptor from raster zone dataset
ElseIf TypeOf pLayer Is IRasterLayer Then
Dim pRasLayer As IRasterLayer
Set pRasLayer = pLayer
Dim pRaster As IRaster
Set pRaster = pRasLayer.Raster
Dim pRasDescriptor As IRasterDescriptor
Set pRasDescriptor = New RasterDescriptor
pRasDescriptor.Create pRaster, Nothing, sFieldName
Set pZoneGeoDataset = pRasDescriptor
Else
Exit Sub
End If
'Get the value raster from the second layer in ArcMap
Set pLayer = pMap.Layer(1)
If Not TypeOf pLayer Is IRasterLayer Then
Exit Sub
End If
Dim pValueRasLayer As IRasterLayer
Set pValueRasLayer = pLayer
Dim pValueRaster As IRaster
Set pValueRaster = pValueRasLayer.Raster
'Create a RasterZonalOp operator
Dim pZonalOp As IZonalOp
Set pZonalOp = New RasterZonalOp
'Set output workspace
Dim pEnv As IRasterAnalysisEnvironment
Set pEnv = pZonalOp
Dim pWS As IWorkspace
Dim pWSF As IWorkspaceFactory
Set pWSF = New RasterWorkspaceFactory
Set pWS = pWSF.OpenFromFile("c:\temp", 0)
Set pEnv.OutWorkspace = pWS
'Create zonal statistics table
Dim pTable As ITable
Set pTable = pZonalOp.ZonalStatisticsAsTable(pZoneGeoDataset, pValueRaster, True)
'Add the output statistics table into ArcMap and display
Dim pTableWindow As ITableWindow
Set pTableWindow = New TableWindow
Set pTableWindow.Table = pTable
Set pTableWindow.Application = Application
pTableWindow.Show True
End Sub