VBA:多个用户形式引用相同的代码 [英] VBA: Multiple Userforms Referencing Same Code
问题描述
我有一个VBA代码,通过用户形式获取用户输入(条件),创建符合条件的项目列表,并通过消息框随机输出其中一个列表项。
I have a VBA code that takes user inputs (criteria) via a userform, creates a list of items that meet said criteria, and randomly outputs one of the list items via message box.
我想创建一个第二个userform,在上述代码完成后打开,并且userform显示随机输出。
I want to create a second userform that will open after the above code completes, and have the userform display the random output.
我有几个关于如何做到这一点的问题。
I have a few questions regarding how this can be done.
- 我想让第二个userform包含一个标签,其标题将反映随机输出。 / li>
- 我希望第二个用户窗体允许用户重新执行原始代码(即更改随机结果)
任何人都有这方面的经验?
Anyone have experience with this?
推荐答案
我将使用第二种形式的Property获取随机值。
I'd use a Property procedure in the second form to get the random value.
作为新的空白工作簿中的示例:
插入一个新模块并粘贴到下面的代码中。此代码代表您输出随机结果的代码。
As an example in a new blank workbook: Insert a new module and paste in the code below. This code represents your code which outputs a random result.
Public Function RandomNumber() As Double
RandomNumber = Rnd(10)
End Function
创建一个新的userform UserForm2),添加一个命令按钮(CommandButton1)和一个标签(Label1)。将以下代码添加到此表单。我在那里放了四个程序。 MyProp设置 ThePassedNumber 的值, UpdateLabel1 更新标签中显示的值, UserForm_Initialize 在表单加载时执行, CommandButton1_Click
Create a new userform (UserForm2), add a command button (CommandButton1) and a label (Label1). Add the below code to this form. I've put four procedures in there. MyProp sets the value of ThePassedNumber, UpdateLabel1 updates the value shown in the label, UserForm_Initialize executes when the form loads, CommandButton1_Click executes when you click the button.
Private ThePassedNumber As Double
Property Let MyProp(TheNumber As Double)
ThePassedNumber = TheNumber
UpdateLabel1
End Property
Private Sub CommandButton1_Click()
ThePassedNumber = RandomNumber
UpdateLabel1
End Sub
Private Sub UserForm_Initialize()
UpdateLabel1
End Sub
Private Sub UpdateLabel1()
Me.Label1.Caption = ThePassedNumber
End Sub
添加第二个表单(UserForm1)并添加一个命令按钮(CommandButton1),并将此代码放在窗体中。
它将创建一个新的用户形式,通过一个随机值,然后显示表单。
Add a second form (UserForm1) and add a command button (CommandButton1) and place this code within the form.
It will create a new instance of the userform, pass a random value to it and then display the form.
Private Sub CommandButton1_Click()
Dim frm2 As UserForm2
Set frm2 = New UserForm2
frm2.MyProp = RandomNumber
frm2.Show
End Sub
现在你只需要重写RandomNumber函数来返回你的列表项,而不是一个数字。
Now you just need to rewrite the RandomNumber function to return your list item rather than a number.
这篇关于VBA:多个用户形式引用相同的代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!