簡體   English   中英

VBA Excel,在窗體之間返回變量

[英]VBA Excel, Returning a Variable between Forms

我需要協助。 我正在為Excel宏編寫VBA腳本。 我有兩種形式,第一種有一個調用第二種的按鈕。 在第二個上,我希望它返回一個變量( tempdate ,在主工作表中將其聲明為public type Date )。

主要表單按鈕代碼:

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

我會在用戶表單中使用屬性

您的主要表單代碼將更改為如下所示:

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

您需要在模塊而不是工作表中聲明變量,並且聲明必須是:

Global tempDate as Date

要么

Public tempDate as Date

工作表中的變量在窗體中不可用。

可以在工作表中創建一個函數並調用該函數,但這是一個簡單得多的解決方案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM