Move a dynamic created control on a form using VBA

馋奶兔 提交于 2020-01-21 23:42:36

问题


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?


回答1:


Private Sub CommandButton1_Click()
  Me.Controls("CommandButton1").Move 0, 0
End Sub



回答2:


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?



来源:https://stackoverflow.com/questions/20932711/move-a-dynamic-created-control-on-a-form-using-vba

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!