验证完成后自动关闭用户表单

时间:2019-01-31 11:24:11

标签: excel vba forms userform

我已经创建了一个登录屏幕,以便在输入有效密码的情况下对excel工作簿进行身份验证。

代码如下:

Private Sub CommandButton1_Click()
 name_selected = ComboBox1.Text
 pwd_entered = TextBox2.Text
 validation_sheet = "Z"
 act_p_col_num = 3
 Application.Visible = True

 For validation_check = 2 To Worksheets(validation_sheet).Cells(Rows.Count, 1).End(xlUp).Row - 1
    If (Worksheets(validation_sheet).Cells(validation_check, 1) = name_selected) Then
        bk_pd = Worksheets(validation_sheet).Cells(validation_check, act_p_col_num).Value
        If (bk_pd = pwd_entered) Then
            Worksheets("INDIVIDUAL_TRACKER").Select
            MsgBox ("Authentication successful")
            UserForm1.Hide
            'Set UserForm1.Visible = False

        Else
            Application.Visible = False
            MsgBox ("Please enter a valid password! Account will be locked after 3 tries")
            TextBox2.Text = ""
        End If
    End If
 Next validation_check
End Sub

无论如何,也使用unload me命令和userform1.hide尝试过此代码,这仍然抛出运行时错误424,需要对象。

我的目标是在认证通过后进入工作簿,userform应该自动关闭。

有人可以帮助我解决这个问题吗?

2 个答案:

答案 0 :(得分:2)

我的猜测是for循环的下一次迭代实际上是导致问题的原因。表单卸载后,您尝试在if语句上访问TextBox。

尝试添加该行

Exit For

Unload Me

之后

PS:尚未解锁评论,很抱歉,如果只是作为答案而发布作为答案...

答案 1 :(得分:1)

重新组合application.visible=True行已解决了该目的。在正确的位置使用它可以使其正常工作。使用Exit For已成为一个附加优势。

Private Sub CommandButton1_Click()
 name_selected = ComboBox1.Text
 pwd_entered = TextBox2.Text
 validation_sheet = "Z"
 act_p_col_num = 3
 Application.Visible = True

 For validation_check = 2 To Worksheets(validation_sheet).Cells(Rows.Count, 1).End(xlUp).Row - 1
    If (Worksheets(validation_sheet).Cells(validation_check, 1) = name_selected) Then
        bk_pd = Worksheets(validation_sheet).Cells(validation_check, act_p_col_num).Value
        If (bk_pd = pwd_entered) Then
            Unload Me

            'UserForm1.Hide
            'Set UserForm1.Visible = False
            Application.Visible = True
            Worksheets("INDIVIDUAL_TRACKER").Select
            MsgBox ("Authentication successful")
            Exit For
        Else
            'Application.Visible = False
            MsgBox ("Please enter a valid password! Account will be locked after 3 tries")
            TextBox2.Text = ""
        End If
    End If
 Next validation_check
End Sub

感谢大家 ,他为这个问题提供了一些启示。这是一个很好的集思广益。谢谢大家。这个问题现在已经解决。