Home » excel » excel vba – Move a dynamic created control on a form using VBA

excel vba – Move a dynamic created control on a form using VBA

Posted by: admin May 14, 2020 Leave a comment

Questions:

In Excel I have created a form. On this form I have created 3 buttons.

I want to be able to move these button at runtime.

The problem which I have is how do I reference the buttons at runtime?

How to&Answers:
Private Sub CommandButton1_Click()
  Me.Controls("CommandButton1").Move 0, 0
End Sub

Answer:

The problem which I have is how do I reference the buttons at runtime?

It depends on how are you assigning the names to the button.

Here is a simple way to create a command button at runtime and move it using another button

Option Explicit

Const CmdName As String = "Click_Me"

Dim ctl_Command As Control

'~~> Create command button on the fly
'~~> and give it a predefined name
Private Sub CommandButton1_Click()
    Set ctl_Command = Me.Controls.Add("Forms.CommandButton.1", CmdName, False)

    With ctl_Command
        .Left = 100
        .Top = 100
        .Width = 255
        .Caption = "Blah Blah"
        .Visible = True
    End With
End Sub

'~~> Use that name to move the control
Private Sub CommandButton2_Click()
    Dim X As Double, Y As Double

    X = 5: Y = 5.5

    Set ctl_Command = Me.Controls(CmdName)
    ctl_Command.Move X, Y
End Sub

In case you are creating multiple dynamic controls then you can use a variable and increment it to assign names. See THIS example. In that link, see the line

Set ctl_Command = Me.Controls.Add("Forms.CommandButton.1", "CmdXYZ" & i, False)

Notice "CmdXYZ" & i?