VERSION 1.0 CLASS
BEGIN
  MultiUse = -1  'True
END
Attribute VB_Name = "AlignAll"
Attribute VB_Creatable = False
Attribute VB_Exposed = False
'Instances of this class handle all Alignment events.
'This class does not need its Instancing or Public
'properties set.

Option Explicit
Public MainProp As String 'Left or Top
Public ShiftProp As String 'Width or Height
Public VBInstance As VBIDE.Application

Public Sub AfterClick()
Dim TheseControls As VBIDE.SelectedControlTemplates
'Using 'As Object' for collection iterator is faster cross process.
Dim Control As Object 'VBIDE.ControlTemplate
Dim bDoShift As Boolean
Dim CheckValue As Long
Dim tmpValue As Long
Dim Controls() As VBIDE.ControlTemplate 'Don't cycle twice through collection
Dim i%, iControlCount As Integer
    
    'Shift properties are Height and Width.  bDoShift will be true for
    'Bottom and Right alignment.
    bDoShift = Len(ShiftProp)
    If Not bDoShift Then CheckValue = 99999 'Defaults to 0 for a shifted property
    Set TheseControls = VBInstance.ActiveProject.ActiveForm.SelectedControlTemplates
    
    'If a property access fails, then just ignore it.
    On Error Resume Next
    
    iControlCount = TheseControls.Count
    If iControlCount < 2 Then Exit Sub 'Nothing to do
    ReDim Controls(iControlCount - 1)
    
    'Scan all the selected controls, checking for the best value to align to.
    For Each Control In TheseControls
        'Keep a reference to the Control for the second pass through the collection.
        Set Controls(i%) = Control
        If bDoShift Then 'Right and Bottom alignment
            With Controls(i%).Properties 'Use the typed object for fastest performance.
                tmpValue = .Item(MainProp) + .Item(ShiftProp)
                If tmpValue > CheckValue Then CheckValue = tmpValue
            End With
        Else 'Left and Top alignment.
            With Controls(i%).Properties(MainProp)
                If .Value < CheckValue Then CheckValue = .Value
            End With
        End If
        i% = i% + 1 'Increment to maintain the position in the collection.
    Next
    
    'Use the best value found on the first pass to align each control.
    For i% = 0 To iControlCount - 1
        If bDoShift Then 'Right and Bottom alignment
            With Controls(i%).Properties
                .Item(MainProp) = CheckValue - .Item(ShiftProp).Value
            End With
        Else 'Left and Top alignment
            Controls(i%).Properties(MainProp) = CheckValue
        End If
    Next i%
End Sub


