使用 VBA 将控件添加到 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
下面的代码演示了如何使用控件动态填充用户窗体中的框架...
在我使用的窗体中,我有一个名为 Frame1 的框架控件,因此在 UserForm_Initialize 中,您可以调用 Frame1.Controls.Add 将控件嵌入到框架中。 您可以设置返回到您在 UserForm 代码模块中定义的 WithEvents 控制变量的控件,以便您可以响应您想要的任何控件上的事件...
因此,使用此方法,您需要预先编写您想要的任何事件代码想要您创建的任何控件...
另请注意,即使顶部、左侧、宽度和高度属性不一定出现在智能感知中,您也可以定位控件并调整其大小...
The following code demonstrates how you can dynamically populate a frame in a userform with controls...
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...
添加
方法要将控件添加到用户窗体或框架,您可以使用
添加
方法。SetControl = object.Add(ProgID [, Name [, Visible ]] )
第一个参数将引用您要添加的控件类型,它是
ProgID
其定义为功能性解决方案
为了使这个过程更容易,让我们使用枚举来帮助我们管理各种控件。
有了这个枚举,我们现在可以轻松创建一个函数来获取所有控件的 ProgID 字符串。
最后,让我们创建一个使用新函数添加到表单或框架的函数。
使用这样的枚举的美妙之处在于,我们现在对所有控件都有智能感知,而不必记住它们。
演示
为了演示它,我们可以通过循环枚举将每个控件添加到空白用户窗体。
The
Add
MethodTo add controls to a userform or a frame you use the
add
method.SetControl = object.Add(ProgID [, Name [, Visible ]] )
The first argument is going to reference what type of control you want to add, and it is
ProgID
which is defined asA Functional Solution
To make this process easier, let's use an enum to help manage the various controls for us.
With this enum, we can now easily create a function to get the ProgID string for all controls.
And lastly, let's create a function that adds to a form or frame using our new function.
The beauty of using enums like this is that we now have a intellisense for all the controls and don't have to memorize them all.
Demo
To demo it, we can add every control to a blank userform by looping the enum.
我对上述主题的变体。 但这仅适用于 4x4 的按钮阵列。 创建一个用户表单并将其添加到其代码中。 相同的概念可以用于您的标签(或参见前面的答案):
My variation on the theme above. This is just for a 4x4 array of buttons though. Create a userform and add this to its code. The same concepts can be used with your labels (or see the previous answer):