Reputation: 179
I've met a problem when I with to use buttons to transfer values between Userformes (UF2 and UF3).
My purpose is to use different buttons to change the content in the label of the userform3. For example, if I click 'aaa to 3', then userform3 shows up and the text in the label will be 'aaa'.
and the code is 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
Public UF2 As UserForm2
Private Sub CommandButton1_Click()
Me.Hide
End Sub
Private Sub UserForm_Initialize()
Set UF2 = UserForm2
Label1 = UF2.Zone
End Sub
But when I run it, the label in UF3 is always empty.
Upvotes: 0
Views: 40
Reputation: 3188
In your code, the Initialize
event of Userform3
will be called before you set the Zone
, just when you set UF3 (if the default instance of userform3 is not already loaded somewhere else).
Since you are not using the keyword new
to instantiate new userforms objects, it uses the default instance.
In your particular case, you need either to set Zone before setting UF3, so that Zone will have a value when Initialize is called in Userform3, or you can directly set UF3.Label1 to the correct value before calling UF3.Show.
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
Note that if you are using default instances of the userforms you don't even need to set them and can directly use the following code:
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
Additional info: Remember that Initialize will only be called once for each instance of an userform, and that calling Me.Hide
does not unload the userform but only "unshow" it. So in your original code the label1 of Userform3 was set only once the first time you called Set UF3 = Userform3
. You may have to used specific instances of the userform instead of the default one if you want to have a better control on when the userform's instances are loaded and unloaded.
Upvotes: 1