Thursday, September 18, 2008

Search a Collection or an Array for a value

I want to check my attribute table for a few specific fields of data (Comments, Reachcode, Waterbody_Type, etc.). If these fields are not included, I want them to be added before my custom tool set can do work on them; fields cannot be edited if they do not exist in the dataset.

This is broken down into several steps:
  • Find all of the fields in a dataset
  • Add specific fields that do not already exist
I use ListOfFields to populate a collection or an array (I used a collection since the dataset will be small, and collections are super simple) with all of the included field names, search the collection or array for values that are not present, and add a new field where the required field is missing.


Private Sub SearchCollection()

Dim fieldName As New Collection

'Fill in a few values for the collection
fieldName.Add ("FID") 'collection position 1
fieldName.Add ("Shape") 'collection position 2
fieldName.Add ("Id") 'collection position 3
fieldName.Add ("Comments")'collection position 4

Dim valueComment As Integer
Dim i As Integer

'Loops through the collection looking for "Comment"
For i = 1 To fieldName.count
If fieldName.Item(i) = "Comments" Then
valueComment = 1
Else
End If
Next i

'Check valueComment for a change
If valueComment = 1 Then
MsgBox "Totally just found That value!"
Else
MsgBox "It's not here..."
End If

End Sub


The collection will be populated automatically using ListOfFields - this is just an example.

The crux of the searching will use a For Loop to step through each item of the collection, and change valueComment to equal 1 if it finds a matching field. If the field is not included in the attribute table/collection, nothing happens (valueComment will remain equal to its default 0). Following this is an If/Then statement that checks what to do next. This will be blank when the other code is applied, since the field is indeed included. The Else message box will be replaced with the code to add the comments field.

The object valueComment type can easily be Boolean, but the double and triple negatives when discussing this out loud get a bit confusing.

No comments: