Get Zonal Statistics

Created:5/4/2001
Description:

This sample code demonstrates how to use IZonalOp::ZonalStatisticsAsTable of Spatial Analyst Objects in VBA

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

    ' Get the zone dataset from the first layer in ArcMap     
    Dim pLayer As ILayer
    Set pLayer = pMap.Layer(0)
    Dim pGeoDs As IGeoDataset
    Dim strField As String
    If TypeOf pLayer Is IFeatureLayer Then
        Dim pFLayer As IFeatureLayer
        Set pFLayer = pLayer
        Set pGeoDs = pFLayer.FeatureClass
        'Pick the zone field
        Dim pFDesc As IFeatureClassDescriptor
        Set pFDesc = New FeatureClassDescriptor
        strField = InputBox("Enter the zone field:")
        pFDesc.Create pGeoDs, Nothing, strField
    ' pFDesc.Create pInFeature, Nothing, "ZVAL"
        Set pGeoDs = pFDesc
     Else
        If TypeOf pLayer Is IRasterLayer Then
            Dim pRLayer As IRasterLayer
            Set pRLayer = pLayer
            Set pGeoDs = pRLayer.Raster
            Dim pRDesc As IRasterDescriptor
            Set pRDesc = New RasterDescriptor
            strField = InputBox("Enter the zone field:")
            pRDesc.Create pGeoDs, Nothing, strField
           ' pRDesc.Create pGeoDs, Nothing, "Value"
            Set pGeoDs = pRDesc
        Else
            Exit Sub
        End If
    End If  

   ' Create the value raster from the second layer     
    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 pZoneOp As IZonalOp
    Set pZoneOp = New RasterZonalOp  

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

    ' Perform Spatial operation   
    Dim pTable As ITable
    Set pTable = pZoneOp.ZonalStatisticsAsTable(pGeoDs, pGeoDs1, True) 

    ' Add the table into ArcMap    
    Dim pTWindow As ITableWindow
    Set pTWindow = New TableWindow
    Set pTWindow.Table = pTable
    Set pTWindow.Application = Application
    pTWindow.Show True

End Sub