2016-10-19 40 views
0

當我使用按鈕在用戶框架(UF2和UF3)之間傳輸值時遇到了問題。VBA_如何使用按鈕在用戶窗體之間傳遞不同的值

我的目的是使用不同的按鈕來更改userform3標籤中的內容。例如,如果我點擊'aaa到3',那麼userform3就會出現,標籤中的文本將是'aaa'。

這裏是Userform2: enter image description here

和代碼是在這裏:

Public UF3 As UserForm3 
Public Zone As String 

Private Sub CommandButton2_Click() 

Set UF3 = UserForm3 
Zone = "aaa" 
UF3.Show 
Zone = "aaa" 

End Sub 

Private Sub CommandButton3_Click() 

Set UF3 = UserForm3 
Zone = "bbb" 
UF3.Show 

End Sub 

而且UserForm3: enter image description here

Public UF2 As UserForm2 

Private Sub CommandButton1_Click() 

Me.Hide 

End Sub 

Private Sub UserForm_Initialize() 

Set UF2 = UserForm2 
Label1 = UF2.Zone 

End Sub 

但是當我運行它,在標籤中UF3總是空的。

回答

1

在代碼中,您將Zone之前的Userform3Initialize事件將被調用,只是當你設置UF3(如果userform3的默認實例尚未加載其他地方)。

由於您未使用關鍵字new實例化新的用戶表單對象,因此它使用默認實例。

在您的具體情況下,您需要在設置UF3之前設置Zone,以便在Userform3中調用Initialize時區域將具有值,或者可以在調用UF3.Show之前直接將UF3.Label1設置爲正確值。

Private UF3 As UserForm5 
Public Zone As String 

Private Sub CommandButton1_Click() 
    'Either this possibility 
    Zone = "test" 
    Set UF3 = UserForm3 
    'or this one 
    UF3.Label1 = "aaa" 
    UF3.Show 
End Sub 

請注意,如果您使用的用戶窗體的默認情況下,你甚至都不需要設置它們,可以直接使用下面的代碼:

Private Sub CommandButton1_Click() 
    Userform3.Label1 = "aaa" 'If the Userform3 default instance doesn't already exists, 
          'the fist call to a method or a property will create and initialize it. 
          'So here the Initialize event of Userform3 will be called 
          'and then the value of Label1 will be changed. 
    Userform3.Show 
End Sub 

附加信息:請記住,對於用戶窗體的每個實例,初始化只會被調用一次,並且調用Me.Hide不會卸載用戶窗體,而只是「解開」它。因此,在您的原始代碼中,Userform3的label1僅在您第一次調用Set UF3 = Userform3時設置一次。如果您想更好地控制userform實例的加載和卸載情況,您可能必須使用userform的特定實例,而不是默認實例。

+0

非常感謝您的解釋。這真的很有幫助。 – Hiddenllyy

+0

對不起,我還有一個問題。我可以在'UserForm3'中定義一個'String',並且通過單擊按鈕在'UserForm2'中將「aaa」或「bbb」分發給這個'String'。我試過這個但失敗了。 – Hiddenllyy

+1

是的,你可以,你必須聲明是作爲一個公共成員變量或用戶窗體的屬性這樣做(它不能是一個私人變量,也不定義在一個子或函數) –