Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VBA Form doesn't shows second time

Tags:

vba

userform

I've got a problem with my VBA Login Form which should protect my book. I've created LoginPage and 2 login forms: for a student and for a teacher. They are similar in use, but does not work correctly.

If I chose "Log as a Teacher" button but then decided to close this window for logging by a student, QueryClose method should work. But this works once. And in the LoginPage when I press CommandButton TeacherForm shows only once too. So as you have already understood I need to switch easily between these forms.

My code(LoginPage) is:

Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
If CloseMode = vbFormControlMenu Then
Cancel = True
ActiveWorkbook.Saved = True
Application.Quit
End If
End Sub

Private Sub TeacherLogin_Click()
Unload Me
Load TeacherForm
TeacherForm.Show
End Sub

TeacherForm:

Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
If CloseMode = 0 Then
    Cancel = True
    Me.Hide
    Unload Me
    Load LoginPage
    LoginPage.Show
End If
End Sub
Private Sub PTTB_Change()
PTTB.PasswordChar = "*"
End Sub
Private Sub SubmitTeacher_Click()
If LTTB.Value = "User" Then
    If PTTB.Value = "SuperUser" Then
        MsgBox ("Access granted!")
    Else
        MsgBox ("Access denied!")
    End If
Else
    MsgBox ("Access denied!")
End If
End Sub

Help me if I do something wrong. Thanks

like image 848
vakhanal1ya Avatar asked Sep 06 '26 08:09

vakhanal1ya


1 Answers

The issue is that you are unloading the Form's Default Instance. You should be instantiating new instances of the Userforms and hiding them instead of unloading them. This article explains it best Rubberduck VBA: UserForm1.Show.

Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
    If CloseMode = vbFormControlMenu Then
        Cancel = True
        ActiveWorkbook.Saved = True
        Application.Quit
    End If
End Sub

Private Sub TeacherLogin_Click()
    Dim Form As TeacherForm
    Set Form = New TeacherForm
    Form.Show
End Sub

Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
    If CloseMode = 0 Then
        Cancel = True
        Me.Hide
        Dim Form As LoginPage
        Set Form = New LoginPage
        Form.Show
    End If
End Sub

Private Sub PTTB_Change()
    PTTB.PasswordChar = "*"
End Sub

Private Sub SubmitTeacher_Click()
    If LTTB.Value = "User" Then
        If PTTB.Value = "SuperUser" Then
            MsgBox ("Access granted!")
        Else
            MsgBox ("Access denied!")
        End If
    Else
        MsgBox ("Access denied!")
    End If
End Sub

You should consider downloading Rubberduck VBA, its Free The code formatting feature will save you a ton of time.

like image 59
TinMan Avatar answered Sep 10 '26 23:09

TinMan