散らかしたボタンを、じわじわ動かしてみる。

昨日は、ユーザーフォーム上にコマンドボタンを散らかしてみた。
infoment.hatenablog.com
さらに、コマンドボタンをビュンビュンと飛ばしてみた。

そこで今日も↓こちらを参考に(というより丸写しで)、コマンドボタンにWithEventsを設定する。これで、散らかしただけのコマンドボタンをクリックすると、キャプションが表示されるようになる(今日も、参考にさせてもらいました。ありがとうございます)。
www.excellovers.com

更に、ビュンビュン飛ばしていたコマンドボタンを、じわじわと集合させてみる。
f:id:Infoment:20181122215306p:plain

とはいえ、今日は遅くなってしまったので、上手く説明を書ききれるかどうかわからない。今日は解説抜きで、とにかくコードを掲載する。

ユーザーフォーム

まっさらなユーザーフォームを作成し、以下を張り付けるだけでOK。

Option Explicit
    Const ButtonSize As Double = 20
    Const Left_Start As Double = 10
    Const Top_Start As Double = 30
    Dim myCol As Collection
    Dim myCls As Class1
    Dim myFlag As Boolean

Private Sub UserForm_Click()

    If myFlag = True Then Exit Sub

    Dim i As Long
    Dim myControl As Control

    Dim j As Long
    Dim jMax As Long
        jMax = 10

    Dim dx(1 To 42) As Double
    Dim dy(1 To 42) As Double

    i = 1
    For Each myControl In Me.Controls
        With myControl
            dx(i) = (.Left - Locate(i)(0)) / jMax
            dy(i) = (.Top - Locate(i)(1)) / jMax
            i = i + 1
        End With
    Next

    For j = 1 To jMax
        i = 1
        For Each myControl In Me.Controls
            With myControl
                .Left = .Left - dx(i)
                .Top = .Top - dy(i)
                Application.Wait [now()+"0:00:00.001"]
                i = i + 1
            End With
        Next
    Next
    myFlag = True
End Sub

Private Sub UserForm_Initialize()
    Dim i As Long
    Dim myCmdBtn As MSForms.CommandButton
    
    Set myCol = New Collection

    For i = 1 To 42
        Set myCmdBtn = Me.Controls.Add("Forms.CommandButton.1", _
                                               "CommandButton" & i, True)
        With myCmdBtn
            .Left = Me.Width * Rnd * 0.9
            .Top = Me.Height * Rnd * 0.9
            .Width = ButtonSize
            .Height = ButtonSize
            .Caption = i
        End With
        Set myCls = New Class1
        myCls.setBtn myCmdBtn
        myCol.Add myCls
    Next
    
    myFlag = False
End Sub

Private Property Get Locate() As Variant
    Dim seq(1 To 42) As Variant
    Dim i As Long
        For i = 1 To UBound(seq)
            seq(i) = Array(Left_Start + ButtonSize * ((i - 1) Mod 7), _
                           Top_Start + ButtonSize * WorksheetFunction.RoundDown((i - 1) / 7, 0))
        Next
        Locate = seq
End Property

クラスモジュールも、こちらを張り付けるだけでOK。

Option Explicit
Private WithEvents myCmdBtn As MSForms.CommandButton

Private Sub myCmdBtn_Click()
    MsgBox myCmdBtn.Caption
End Sub

Sub setBtn(Cmdbtn As MSForms.CommandButton)
    Set myCmdBtn = Cmdbtn
End Sub

結果は、こんな感じだ。
f:id:Infoment:20181122220330g:plain

詳細は、のちほど(何も問題なければ、明日)。

参考まで。