2016-03-02 73 views
0

我需要一些帮助。我正在为Excel宏编写VBA脚本。我有两种形式,第一种有一个按钮叫第二种。在第二个我希望它返回一个变量(tempdate,这是在主工作表中声明为public type Date)。VBA Excel,在表单之间返回变量

主要形式的按钮代码:

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

UserForm1 '确定' 按钮:

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

缺少什么我得到这个变量加载无论是在TextBox1.Value

回答

0

您需要声明变量的模块,而不是在工作表中,并声明必须是:

Global tempDate as Date 

Public tempDate as Date 

在工作表中的变量是不可用的形式。

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

1

我会在用户窗体使用属性

你的主要形式的代码会改变看起来像这样:

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 
+0

这实际上是比我提供的更好的解决方案;我只是提供最简单的修复。 – OpiesDad

+0

感谢您的反馈,我使用公共财产方法,它的工作原理非常棒! – Bennyono