2016-10-19 37 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

是的,你可以,你必须声明是作为一个公共成员变量或用户窗体的属性这样做(它不能是一个私人变量,也不定义在一个子或函数) –