VBA Excel,在窗体之间返回一个variables

我需要一些帮助。 我正在写一个Excelmacros的VBA脚本。 我有两种forms,第一种有一个button叫第二种。 第二我希望它返回一个variables( tempdate ,这是在主工作表中声明为public type Date )。

主窗体button代码:

 Private Sub SetDueButton_Click() UserForm1.Show DueDate.Value = tempdate 'display tempdate in the DueDate text box End Sub 

UserForm1“确定”button:

 Private Sub CommandButton53_Click() tempdate = TextBox1.Value Unload Me End Sub 

我错过了什么,以获得这个variables加载TextBox1.Value什么的?

您需要在模块中声明variables,而不是在工作表中,声明需要是:

 Global tempDate as Date 

要么

 Public tempDate as Date 

工作表中的variables在表单中不可用。

可以在工作表中创build一个函数并调用这个函数,但这是一个更简单的解决scheme。

我会在用户窗体中使用一个属性

你的主窗体代码将会变成如下所示:

 Option Explicit Private Sub SetDueButton_Click() Dim UF As UserForm1 'you can declare a user form as an independent object UF.Show DueDate.Value = UF.tempdate 'get the property Unload UF 'now you can unload or set to Nothing End Sub 

你的UserForm1代码是这样的:

 Option Explicit Public Property Get tempdate() As String tempdate = Me.TextBox1.Value 'Me refers to the form itself End Property Private Sub CommandButton53_Click() Me.Hide 'hide don't unload yet or you can't get the data. End Sub