Move a dynamic created control on a form using VBA

后端 未结 2 753
生来不讨喜
生来不讨喜 2021-01-24 16:19

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 re

2条回答
  •  伪装坚强ぢ
    2021-01-24 17:22

    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?

提交回复
热议问题