How to set the analysis environment


This sample code demonstrates how to set analysis environment and create a constant raster using RasterMakerOp

How to use

  1. Run ArcMap.
  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. Paste the code into VBA.
  6. Run the sub from the Macros dialog.
[VBA]
Sub SetAnalysisEnvironment()
    'Create a RasterMakerOp operator
    Dim pRasMakerOp As IRasterMakerOp
    Set pRasMakerOp = New RasterMakerOp
    
    'Create an analysis environment object
    Dim pEnv As IRasterAnalysisEnvironment
    Set pEnv = pRasMakerOp
    
    'Set output workspace
    Dim pWS As IWorkspace
    Dim pWSF As IWorkspaceFactory
    Set pWSF = New RasterWorkspaceFactory
    Set pWS = pWSF.OpenFromFile("c:\temp", 0)
    Set pEnv.OutWorkspace = pWS
    
    'Set cellsize
    pEnv.SetCellSize esriRasterEnvValue, 30
    
    'Set output extent to left = 0, bottom = 2000, right = 3000, top = 5000
    Dim pExt As IEnvelope
    Set pExt = New Envelope
    pExt.XMin = 0
    pExt.YMin = 2000
    pExt.XMax = 3000
    pExt.YMax = 5000
    pEnv.SetExtent esriRasterEnvValue, pExt
    
    'Set output spatial reference
    Dim pSpRef As ISpatialReference
    Dim pSpRefFactory As ISpatialReferenceFactory2
    Set pSpRefFactory = New SpatialReferenceEnvironment
    Set pSpRef = pSpRefFactory.CreateSpatialReference(54008) 'PCS code for Sinusodial
    Set pEnv.OutSpatialReference = pSpRef
    
    'Create a constant raster
    Dim pOutRaster As IRaster
    Set pOutRaster = pRasMakerOp.MakeConstant(10, True)
    
    'Create a raster layer from the output and add it to ArcMap
    Dim pRasLayer As IRasterLayer
    Set pRasLayer = New RasterLayer
    pRasLayer.CreateFromRaster pOutRaster
    
    Dim pMxDoc As IMxDocument
    Set pMxDoc = ThisDocument
    Dim pMap As IMap
    Set pMap = pMxDoc.FocusMap
    pMap.AddLayer pRasLayer
End Sub