This sample code demonstrates how to updates records in a Grid value attribute table (VAT) using GridTableOp.
How to use
- Paste the code into VBA.
- Make sure the Spatial Analyst extension is checked.
- Add reference to ESRI SpatialAnalyst Object Library.
- Add reference to ESRI GeoAnalyst Object Library.
- Modify the name and path of the grid, field position and the new values in the code.
- Call the sub UpdateRecordsInGridVAT from another Sub or Function.
Sub UpdateRecordsInGridVAT()
On Error GoTo ErrorHandler
'Specify Grid name and path
Dim sGridPath As String
Dim sGridName As String
sGridPath = "C:\temp"
sGridName = "mygrid01"
'Open Grid As IRasterDataset
Dim pRasDS01 As IRasterDataset
Set pRasDS01 = OpenGridAsIRasterDataset(sGridPath, sGridName)
'Create GridTableOp
Dim pGridTableOp As IGridTableOp
Set pGridTableOp = New GridTableOp
'Get a cursor and update values. The new value is the square of the record number
Dim pCur As ICursor
Set pCur = pGridTableOp.Update(pRasDS01, Nothing, False)
Dim iFieldPos As Integer
iFieldPos = 5
Dim pRow As IRow
Set pRow = pCur.NextRow
Dim i As Long
Dim lNewValue As Long
i = 1
Do Until pRow Is Nothing
lNewValue = i * i
pRow.Value(iFieldPos) = lNewValue
pRow.Store
pCur.UpdateRow pRow
Set pRow = pCur.NextRow
i = i + 1
Loop
pCur.Flush
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