How to add new field to a feature class with VBA ArcObject

734
1
11-07-2011 07:17 AM
New Contributor
Can anyone show me how to add a new field to a feature class using VBA. Thank you very much in advance.
Reply
0 Kudos
1 Reply
New Contributor III
This will add an Integer type field named "Count" to the feature class of a selected feature layer. It is just the basics, but should get you started


Private Sub UIButtonControlAddField_Click()

    Dim sToolName As String
    sToolName = "Test Add Field"

    Dim pMxDoc As IMxDocument
    Dim pLayer As ILayer
    Dim pFeatureLayer As IFeatureLayer
    Dim pFeatureClass As IFeatureClass
    Dim pField As IField


    Set pMxDoc = Application.Document

    Set pLayer = pMxDoc.SelectedLayer

    ' Make sure some type of layer is selected
    If (pLayer Is Nothing) Then
        MsgBox "Please Select a feature layer.", vbOKOnly, sToolName
        Exit Sub
    End If

    ' Make sure a feature layer (not a group layer) is selected
    If Not (TypeOf pLayer Is IFeatureLayer) Then
        MsgBox "Please Select a feature layer.", vbOKOnly, sToolName
        Exit Sub
    End If

    Set pFeatureLayer = pMxDoc.SelectedLayer

    Set pFeatureClass = pFeatureLayer.featureClass

    Set pField = MakeIntField("COUNT")

    AddFieldToFeatureClass pFeatureClass, pField

End Sub

Public Function MakeIntField(fieldName As String) As IField
    Dim pFieldEdit As IFieldEdit
    Dim pField As IField

    Set pField = New field
    Set pFieldEdit = pField

    pFieldEdit.Name = fieldName
    pFieldEdit.Type = esriFieldTypeInteger

    Set MakeIntField = pField
End Function

Public Sub AddFieldToFeatureClass(featureClass As IFeatureClass, field As IField)
    Dim schemaLock As ISchemaLock

    On Error GoTo ErrorHandler

    Set schemaLock = featureClass

    schemaLock.ChangeSchemaLock (esriSchemaLock.esriExclusiveSchemaLock)

    featureClass.AddField field

    schemaLock.ChangeSchemaLock (esriSchemaLock.esriSharedSchemaLock)

    Exit Sub

ErrorHandler:
    schemaLock.ChangeSchemaLock (esriSchemaLock.esriSharedSchemaLock)
   
End Sub

Reply
0 Kudos