How to add a field to a grid attribute table (VAT)


This sample code demonstrates how to add a field to a Grid value attribute table (VAT) using GridTableOp.

How to use

  1. Paste the code into VBA.
  2. Make sure the Spatial Analyst extension is checked.
  3. Add reference to ESRI SpatialAnalyst Object Library.
  4. Add reference to ESRI GeoAnalyst Object Library.
  5. Call the sub AddFieldToVAT from another Sub or Function and pass the Grid path, name, field name, field type and the field length.
[VBA]
Sub AddFieldToVAT(sGridPath As String, sGridName As String, sFieldName As String, enumFieldType As esriFieldType, lFieldLength As Long)
    On Error GoTo ErrorHandler
    
    'Open Grid As IRasterDataset
    Dim pRasDS01 As IRasterDataset
    Set pRasDS01 = OpenGridAsIRasterDataset(sGridPath, sGridName)
    
    'Create a field that you want to add
    Dim pField As IField
    Set pField = New esriGeoDatabase.Field
    Dim pFieldEdit As IFieldEdit
    Set pFieldEdit = pField
    pFieldEdit.Name = sFieldName
    pFieldEdit.Type = enumFieldType
    pFieldEdit.Length = lFieldLength
    
    'Create GridTableOp
    Dim pGridTableOp As IGridTableOp
    Set pGridTableOp = New GridTableOp
    
    'Add Field
    pGridTableOp.AddField pRasDS01, pField
    
    Exit Sub
ErrorHandler:
    MsgBox Err.Description
End Sub

Public Function OpenGridAsIRasterDataset(sPath As String, sRasterName As String) As IRasterDataset
    'Returns RasterDataset given a file name and it's directory
    
    On Error GoTo ErrorHandler
    Dim pWSFact As IWorkspaceFactory
    Dim pWS As IWorkspace
    Dim pRasterWS As IRasterWorkspace
    Dim pRasDS As IRasterDataset
    
    Set pWSFact = New RasterWorkspaceFactory
    If pWSFact.IsWorkspace(sPath) Then
        Set pWS = pWSFact.OpenFromFile(sPath, 0)
        Set pRasterWS = pWS
        Set pRasDS = pRasterWS.OpenRasterDataset(sRasterName)
        Set OpenGridAsIRasterDataset = pRasDS
    Else
        Set OpenGridAsIRasterDataset = Nothing
    End If
    Exit Function
ErrorHandler:
    Set OpenGridAsIRasterDataset = Nothing
End Function