Frequently asked question

Can I select features at random?

Last Published: April 25, 2020


** Internal Publish Only! This article may contain information that is not intended for external circulation. **

If this information needs to be sent out to users point them to the original Discussion Forum link below:

The following ArcObjects sample code illustrates how to select random features. Specify the number of features to select on the line that is marked.
Sub SelectRandom()
Dim pMxDoc As IMxDocument
Dim pFeatureLayer As IFeatureLayer
Dim pFeatureCursor As IFeatureCursor
Dim pFeature As IFeature
Dim pFeatures() As IFeature
Dim pFeatureSelection As IFeatureSelection
Dim lTotNumFeatures As Long
Dim lNumFeatures As Long
Dim lFeatureCount As Long
Dim lRandom As Long
Dim dPercentage As Double
Dim l As Long

'set number of features to select
lNumFeatures = 500

Set pMxDoc = ThisDocument
Set pFeatureLayer = pMxDoc.FocusMap.Layer(0)

lTotNumFeatures = pFeatureLayer.FeatureClass.FeatureCount(Nothing)

ReDim pFeatures(0 To lTotNumFeatures - 1)
Set pFeatureCursor = pFeatureLayer.FeatureClass.Search(Nothing, False)
Set pFeature = pFeatureCursor.NextFeature
Do While Not pFeature Is Nothing
Set pFeatures(l) = pFeature
l = l + 1

Set pFeature = pFeatureCursor.NextFeature


l = 0
Do While l < lNumFeatures
lRandom = CLng(Rnd * (lTotNumFeatures - 1))
If Not pFeatures(lRandom) Is Nothing Then

pMxDoc.FocusMap.SelectFeature pFeatureLayer, pFeatures(lRandom)

Set pFeatures(lRandom) = Nothing

l = l + 1
End If

End Sub

Article ID:000007142

  • ArcMap 8 x

Get help from ArcGIS experts

Contact technical support

Download the Esri Support App

Go to download options

Discover more on this topic