简体   繁体   English

使用VBA在表单上移动动态创建的控件

[英]Move a dynamic created control on a form using VBA

In Excel I have created a form. 在Excel中,我创建了一个表单。 On this form I have created 3 buttons. 在这个表单上,我创建了3个按钮。

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? 我遇到的问题是如何在运行时引用按钮?

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

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 ? 注意"CmdXYZ" & i

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM