VBA MS Excel:我可以在模块中编写用户窗体代码吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17493872/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
VBA MS Excel: Can I Write UserForm Code in a Module?
提问by Elias
Quick Question,
快速问题,
Is there a way I can write my Userform code in a module?
有没有办法在模块中编写我的用户表单代码?
The reason I'm asking this is because I have a multi-page userform with an increasingly massive amount of code behind it. For organizational purposes, I'd like to be able to space out the code in different modules. But I don't know if this can be done for userforms (aside from calling a subroutine from the userform event).
我问这个的原因是因为我有一个多页用户表单,背后有越来越多的代码。出于组织目的,我希望能够将不同模块中的代码隔开。但我不知道这是否可以为用户表单完成(除了从用户表单事件调用子例程)。
Is there a way to write UserForm code in a module without having to call the subroutine from the userform code?
有没有办法在模块中编写用户窗体代码而不必从用户窗体代码调用子例程?
Thanks,
谢谢,
回答by Andy Brazil
Actually it's simple. The code in your form module can call subroutines in other modules. So simply cut your code for a particular routine and paste it into another module, name it appropriately, and then in the form module place the name of the routine to call it. The only gotcha is that when the code is in a seperate module you can't use the Me keyword. If you use that in your code then pass the form as an argument and replace Me with your variable. A simplistic example: Assume you orinally have
其实很简单。表单模块中的代码可以调用其他模块中的子程序。因此,只需剪切特定例程的代码并将其粘贴到另一个模块中,适当命名,然后在表单模块中放置例程的名称以调用它。唯一的问题是,当代码位于单独的模块中时,您不能使用 Me 关键字。如果您在代码中使用它,则将表单作为参数传递并用您的变量替换 Me 。一个简单的例子:假设你最初有
Sub OK_Click()
If Me.txtName<>"" then
MsgBox "Ok",vbOkOnly,"It Worked"
End If
End Sub
Then you can create the following in a seperate module:
然后您可以在单独的模块中创建以下内容:
Sub DoOkClick( f as UserForm)
if f.txtname<>"" then
MsgBox "Ok",vbOkOnly,"It Worked"
End If
End Sub
and then replace the button click code with
然后将按钮单击代码替换为
Sub Ok_Click
DoOkClick Me
end sub
回答by Andy G
An approach is outlined herethat involves defining a Class and adding controls to the form dynamically, which are then associated with Events of the Class.
此处概述了一种方法,该方法涉及定义一个类并将控件动态添加到表单中,然后将这些控件与类的事件相关联。
From you description, though, it sounds like your UserForm is doing too much. I suggest that you consider creating other forms, rather than trying to do everything from a single form. You could, perhaps, create a Class to store properties (and behaviours) that are common to the two or three forms that you might create. Instantiate the Class when the first (main) form is opened.
但是,根据您的描述,听起来您的 UserForm 做得太多了。我建议您考虑创建其他表单,而不是尝试从单个表单完成所有操作。您或许可以创建一个类来存储您可能创建的两个或三个表单共有的属性(和行为)。当第一个(主)窗体打开时实例化类。