Search code examples
excelvbauserform

Move back all objects to original position in excel VBA Userforms


Scenario

I have an excel VBA userform whereby it has many combobox, text box, labels, checkbox and buttons all around. When I click some button these object will change its position to a new position.

What I need

I need to move back all these to the original position when a button is clicked without using the positioning technique I used earlier. Is there any method whereby I can move all objects back to original position with some single command?

What I tried

I tried userform_initialize but its not working


Solution

  • As Jeffrey Weir pointed out; Put the original positions in the Tag property

    Private Sub UserForm_Initialize()
    Dim ctrl As MSForms.Control
        For Each ctrl In Me.Controls
            ctrl.Tag = ctrl.Top & "|" & ctrl.Left
        Next
    End Sub
    

    and to go back to the original positions:

    Private Sub CommandButton1_Click()
    'button to go back, adjust name to your button
    Dim ctrl As MSForms.Control
        For Each ctrl In Me.Controls
            ctrl.Top = Split(ctrl.Tag, "|")(0)
            ctrl.Left = Split(ctrl.Tag, "|")(1)
        Next
    End Sub