HOW TO
This article contains VBA sample code that returns the text and position for all labels in a layer.
Note:
Code in ThisDocument code module will only run in the current map document. To store the code in all map documents, open the code in the Normal.mxt ThisDocument code module.
Code:
Public Sub GetLabels()
Dim pDoc As IMxDocument
Set pDoc = ThisDocument
Dim pMap As IMap
Set pMap = pDoc.FocusMap
'Get the first layer in ArcMap
Dim pGLayer As IGeoFeatureLayer
Set pGLayer = pMap.Layer(0)
Dim pAnnoLayerPropsCol As IAnnotateLayerPropertiesCollection
Dim pAnnoLayerProps As IAnnotateLayerProperties
Dim pAnnoProps As IAnnotateProperties
Dim pEnumVisibleElements As IElementCollection
Set pEnumVisibleElements = New ElementCollection
' Get the Annotation Collection
Set pAnnoLayerPropsCol = pGLayer.AnnotationProperties
pGLayer.DisplayAnnotation = True
pAnnoLayerPropsCol.QueryItem 0, pAnnoLayerProps, _
pEnumVisibleElements, Nothing
pAnnoLayerProps.LabelWhichFeatures = esriVisibleFeatures
pAnnoLayerProps.UseOutput = True
'Populate visible element collection
Dim pAnnotateMap As IAnnotateMap
Set pAnnotateMap = pMap.AnnotationEngine
Dim pAnnotateMapProps As IAnnotateMapProperties
Set pAnnotateMapProps = New AnnotateMapProperties
Set pAnnotateMapProps.AnnotateLayerPropertiesCollection = _
pAnnoLayerPropsCol
Dim pTC As ITrackCancel
Set pTC = New CancelTracker
Set pAnnoLayerProps.FeatureLayer = pGLayer
pAnnotateMap.Label pAnnotateMapProps, pMap, pTC
Set pAnnoLayerProps.FeatureLayer = Nothing
' Query the element collection for the visible labels
Dim i As Integer
Dim pElement As IElement
Dim pTextElement As ITextElement
Dim sText As String
Dim pPolyline As IPolyline
For i = 0 To pEnumVisibleElements.Count - 1
pEnumVisibleElements.QueryItem i, pElement
Set pTextElement = pElement
If (Not pTextElement Is Nothing) Then sText = pTextElement.Text
Set pPolyline = pElement.Geometry
MsgBox sText & " " & pPolyline.FromPoint.X & _
" " & pPolyline.FromPoint.Y
Next i
End Sub
Get help from ArcGIS experts
Download the Esri Support App