确定单击哪个命令按钮以打开用户窗体

Determine which command button was clicked to open userform

我在 userform1 上有两个命令按钮(cmd1cmd2),单击时每个按钮都显示相同的用户表单(userform2)。在 initializeload 子项中,是否可以确定在 userform1 上单击了哪个命令按钮,从而以不同方式显示表单?我想象 initializeload sub on userform2 中的代码具有以下骨架:

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 的事件处理程序中,但是,如果可以使用上述方法,它将变得更加简单和清洁工。

UserForm1中使用Public Variable然后在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

你也可以不使用 public 变量。

我不会展示您可以简单地在单元格中或隐藏单元格中写入内容的示例 sheet,而是直接传递所需信息。

这次whatsclicked是userform2中一个label的名字,

在 userform1 中,在调用 userform2 之前:

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

当然,您必须向用户隐藏点击内容的文本(与字体或背景颜色相同...)