确定单击了哪个命令按钮以打开userform

时间:2015-01-19 04:23:53

标签: vba excel-vba userform excel

cmd1上有两个命令按钮(cmd2userform1),点击后每个按钮显示相同的用户形式(userform2)。在initializeload子内,是否可以确定userform1上单击了哪个命令按钮,从而以不同方式显示表单?我想象initialize上的loaduserform2子中的代码具有以下骨架:

if (cmd1 was clicked)
' do stuff relating to 1
elseif (cmd2 was clicked)
' do stuff relating to 2
else
' error handling
End if

各自" stuff"可以移动到cmd1cmd2的事件处理程序中,但是,如果可以使用上述方法,它将更简单,更清晰。

2 个答案:

答案 0 :(得分:2)

Public Variable中使用UserForm1,然后在UserForm2_Initialize Event中进行测试 UserForm1中的内容如下:

Public whatsclicked As String
Private Sub CommandButton1_Click()
    whatsclicked = "CommandButton1"
    UserForm2.Show
End Sub

Private Sub CommandButton2_Click()
    whatsclicked = "CommandButton2"
    UserForm2.Show
End Sub

然后在UserForm2中:

Private Sub UserForm_Initialize()
    Select Case UserForm1.whatsclicked
    Case "CommandButton1": MsgBox "CommandButton1 loaded form."
    Case "CommandButton2": MsgBox "CommandButton2 loaded form."
    Case Else 'Do something else
    End Select
End Sub

答案 1 :(得分:0)

你也可以在没有公共变量的情况下这样做。

我不会展示一个例子,你可以简单地在单元格或隐藏的工作表中写一些东西,而不是直接传递想要的信息。

这次whatsclicked是userform2中标签的名称,

在调用userform2:

之前,在userform1中

Private Sub CommandButton1_Click()
load UserForm2
with UserForm2
    .whatsclicked.caption= "CommandButton1"
    .Show
end with
End Sub

Private Sub CommandButton2_Click()
load UserForm2
with UserForm2
    .whatsclicked.caption= "CommandButton2"
    .Show
end with
End Sub

当然,你必须隐藏用户的文字(与字体或背景相同的颜色......)