English

How To: Use Scripting Dictionary to return the values and frequency for a numeric or text field

Summary

ArcInfo has a Frequency command that returns a list of unique code occurences and their frequency for numeric and text fields. Instructions provided illustrate how to perform this task in ArcMap using VBA and ArcObjects.

Procedure

  1. Start ArcMap.
  2. Open the Visual Basic Editor.

    In ArcMap, select Tools > Macros > Visual Basic Editor.

  3. From the Tools menu, select References. Scroll through the list of available references and check the box adjacent to the Microsoft Scripting Runtime library.
  4. In the Project Explorer window, expand Project.mxt, select ArcMap Objects > ThisDocument, and right-click and select View Code.
    [O-Image] Visual Basic Project  Explorer
    Note:
    Code in the Project's ThisDocument code module only runs in the current map document. To store the code in all of the map documents, open the Normal.mxt ThisDocument code module instead.

  5. Copy the following code into the code module. It currently provides the frequency for the NAME field. The line of code to change the field is commented below.
    Code:
    'Set a reference to Microsoft Scripting Runtime Library
    Option Explicit
    Sub TestFrequency()
    ' Make a dictionary of key-value pairs where the key is the
    ' field value, and the dictionary value is the frequency count
    Dim pDict As New Scripting.Dictionary
    Dim pMxDoc As IMxDocument
    Dim pFLayer As IFeatureLayer
    Dim pFSel As IFeatureSelection
    Dim pFCur As IFeatureCursor
    Dim lFld As Long
    Dim v As Variant
    Dim pFeat As IFeature

    Set pMxDoc = ThisDocument
    ' US Counties are in layer(0)
    Set pFLayer = pMxDoc.FocusMap.Layer(0)
    Set pFSel = pFLayer

    If pFSel.SelectionSet.Count = 0 Then
    Set pFCur = pFLayer.FeatureClass.Search(Nothing, True)
    Else
    pFSel.SelectionSet.Search Nothing, True, pFCur
    End If

    lFld = pFCur.FindField("Name")'change the name of the field here
    If lFld = -1 Then
    Debug.Print "field NAME not found" 'change the name of the field in the error message here
    Exit Sub
    End If

    Set pFeat = pFCur.NextFeature
    Do While Not pFeat Is Nothing
    v = pFeat.Value(lFld)
    If pDict.Exists(v) Then
    pDict.Item(v) = pDict.Item(v) + 1
    Else
    pDict.Add v, 1
    End If
    Set pFeat = pFCur.NextFeature
    Loop

    ' list all counties and their frequency
    For Each v In pDict.Keys
    If pDict.Item(v) >= 1 Then
    Debug.Print v & ", " & pDict.Item(v)
    End If
    Next v
    End Sub

  6. Close the Visual Basic Editor.
  7. Run the code.

    A. Click Tools > Macros > Macros to display the Macros dialog box.
    B. Select a macro and click Run.