【问题标题】:Determine which command button was clicked to open userform确定单击哪个命令按钮以打开用户窗体
【发布时间】:2015-01-20 07:01:12
【问题描述】:

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

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

【问题讨论】:

标签: vba excel userform


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

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

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

    在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
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-11
      • 1970-01-01
      • 2015-04-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多