使用VBA将Excel控件添加到Excel用户窗体中 [英] Adding controls to a frame in an Excel userform with VBA

查看:842
本文介绍了使用VBA将Excel控件添加到Excel用户窗体中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要动态创建标签和按钮,然后将它们添加到用户窗体中的框架中。我该怎么做?似乎这样应该比实际更容易。

I need to create labels and buttons dynamically and then add them to a frame within a userform. How do I do this? Seems like it should be easier than it really is.

推荐答案

以下代码演示如何在控件中动态填充用户窗体中的框架...

The following code demonstrates how you can dynamically populate a frame in a userform with controls...

在我使用的窗体中,我有一个名为Frame1的框架控件,所以在UserForm_Initialize中调用Frame1.Controls。添加在框架中嵌入控件。您可以设置返回到您在UserForm代码模块中定义的WithEvents控件变量的控件,以便您可以根据需要的任何控件回复事件。

In the form I used I had a frame control named Frame1, so in the UserForm_Initialize you call Frame1.Controls.Add to embed a control in the frame. You can set the control which gets returned to a WithEvents control variable that you have defined in the UserForm code module so you can respond to events on whatever controls you want...

所以使用这种方法,您需要预先编写任何您创建的控件的事件代码...

So with this method you need to pre-write any event code you want for any controls you create...

还要注意,您可以将控件的位置和大小均匀如果顶部,左侧,宽度和高度属性不一定在智能感知中出现...

Also note that you can position and size your controls even if the top, left, width, and height properties don't necessarily come up in intellisense...

Private WithEvents Cmd As MSForms.CommandButton
Private WithEvents Lbl As MSForms.Label

Private Sub UserForm_Initialize()
    Set Lbl = Frame1.Controls.Add("Forms.Label.1", "lbl1")
    Lbl.Caption = "Foo"
    Set Cmd = Frame1.Controls.Add("Forms.CommandButton.1", "cmd1")
End Sub

Private Sub Cmd_Click()
    Cmd.Top = Cmd.Top + 5
End Sub

Private Sub Lbl_Click()
    Lbl.Top = Lbl.Top + 5
End Sub

这篇关于使用VBA将Excel控件添加到Excel用户窗体中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆