My excel userform becomes unresponsive the next time I load it - excel

I have two forms, a login form to authenticate users to enter the system and a main form to work with if the authentication is successful. I work with an access database to search for the valid users and also to populate lists in the main form.
And here is the code for that:
Private Sub CancelCommandButton_Click()
CloseDatabase
Unload Me
End Sub
Private Sub ConfirmCommandButton_Click()
...
End Sub
Private Sub UserForm_Initialize()
ConnectDatabase
End Sub
Private Sub OpenMainForm()
Unload Me
MainForm.Show
End Sub
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
If CloseMode = vbFormControlMenu Then
Cancel = True
End If
End Sub
And here is the code for managing main form load-up and close:
Public Sub UpdateControls()
PopulateUserList
End Sub
Private Sub UserForm_Activate()
sTag = Split(Me.Tag, "|")
If sTag(0) <> "1" Then
Me.MainFormMultiPage.Pages(0).Enabled = False
Me.MainFormMultiPage.Value = 1
Else
Me.MainFormMultiPage.Pages(0).Enabled = True
Me.MainFormMultiPage.Value = 0
UpdateControls
End If
UserLabel1.Caption = sTag(1)
UserLabel2.Caption = sTag(1)
UserLabel3.Caption = sTag(1)
End Sub
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
If CloseMode = vbFormControlMenu Then
' Tip: If you want to prevent closing UserForm by Close (×) button in the right-top corner of the UserForm, just uncomment the following line:
' Cancel = True
Dim answer As Integer
answer = MsgBox("ÂíÇ ãØãÆäíÏ ˜å ãí ÎæÇåíÏ ÇÒ ÓÇãÇäå ÎÇÑÌ ÔæíÏ¿", vbYesNo + vbQuestion, "ÎÑæÌ ÇÒ ÓÇãÇäå")
If answer = vbYes Then
CloseDatabase
Else
Cancel = True
End If
End If
End Sub
Private Sub UserForm_Terminate()
loginForm.Show
End Sub
When I close the main form by clicking 'X' button, the login form reappears and the main form is closed; But when I login again (preferably using the same credentials) the main form is displayed but totally unresponsive (No list population, 'X' button doesn't work or any other controls in the form).
What should I do? Does the code in the UserForm_CloseQuery() unload the main form and all of its macros and I can't get the required events back to function or am I missing something?
It's not a time I started coding VBA and I can't make the head or tail of it easily when new problems arise. Any help would be appreciated. Thanks

Assuming your forms are modal, change the login form code to:
Private Sub OpenMainForm()
Me.Hide
MainForm.Show
Me.Show
End Sub
and remove the Userform_Terminate code from the main form. That will mean that the login form automatically shows when the main form is closed.

Related

How to pass variable from Form to Workbook VBA

I want to keep a variable from Form to Workbook Events, it works from Form to Module, but doesn't work from Form to Workbook Event, the Variable "Salvar" stay as "Empty" rather than "True"...
'WorkBook Event
Public Salvar As Boolean
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
UserForm_Salvar.Show 'Calls "Private Sub Botao_Salvar_Click()"
If SaveAsUI = True Then
If Salvar = True Then
Cancel = False
Salvar = False
Else
Cancel = True
End If
End If
End Sub
'UserForm
Private Sub Botao_Salvar_Click()
Dim PassWord As Variant
PassWord = Senha_TextBox
If PassWord = 123 Then
Unload UserForm_Salvar
Salvar = True
End If
End Sub 'Go back to "Workbook_BeforeSave"
You don't really need a global variable if you declare the form as an object, which is the better practice anyway, and then handle it correctly. Use any of the form's properties or the form's controls' properties to convey the message. I recommend to use the Tag property. Here is the code in the worksheet's module. Observe that I named the form FrmSalvar.
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
' 091
Dim Form As FrmSalvar
If SaveAsUI = True Then
Set Form = New FrmSalvar ' create a new instance of the form
With Form
.Show ' the Form takes control
' code resumes here with Form hidden but still in memory
Cancel = (Val(.Tag) <> True) ' True = -1
End With
Unload Form ' only now the form is destroyed
Set Form = Nothing
End If
End Sub
and the code in the Form's code sheet.
Private Sub Botao_Salver_Click()
' 091
Dim PassWord As String ' Textboxes handle text = strings
PassWord = Senha_TextBox.Value ' this is a string, even if numeric
If PassWord = "123" Then
Me.Tag = -1 ' write something to the Tag property
Else
MsgBox "The password is incorrect", vbInformation, "Access denied"
End If
Me.Hide ' hide the form
End Sub
The line Cancel = (Val(.Tag) <> True) in the BeforeSave procedure will crash if the user closed the form using the X button. This is because that button effectively unloads the form before your code can do it. In your system, that action should be paramount to "no password". Therefore this code will remedy the situation.
On Error Resume Next
Cancel = (Val(.Tag) <> True)
If Err.Number Then Cancel = True
That's a more dignified exit than gathering your skirts and fleeing the scene in panic. However, there is also a method by which you can simply not allow the form to be closed that way. I use the two event procedures below in most of my forms.
Private Sub CmdCancel_Click()
' 091
Me.Hide
End Sub
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
' 091
Cancel = (CloseMode <> vbFormCode)
If Cancel Then CmdCancel_Click
End Sub
Read up about the QueryClose event here. In its above incarnation it just cancels what the user pressed and suggests alternative code which could be simply Me.Hide. I have Me.Hide in the procedure that responds to the Cancel button on my form and I rather invoke that procedure than allowing a second cancel exit from the form in my code. In this way there are just two exits from my form, with OK or with Cancel. Pressing the X is handled in the same way as when Cancel was pressed. Either way, the Me.Tag is preserved until the bitter end.
Change the value of Salvar before Unloading the UserForm.
If PassWord = 123 Then
Salvar = True
Unload UserForm_Salvar
End If

Problem with showing a UserForm after termination

1st, what i want to do:
I have a main UserForm, on that form i have a button to show secondary UserForm. When i click on that button, i want main form to be hidden. When i'm done with with work on the secondary form, i want to close it and show the main form again.
2nd, what i have so far (relevant code):
Main form code:
Private Sub createFastButton_Click()
Me.Hide
formSec.Show
End Sub
Secondary form code:
Private Sub cancelButton_Click()
Me.Hide
formMain.Show
End Sub
Private Sub UserForm_Terminate()
formMain.Show
End Sub
3rd, the problem:
If i use ControlButtons to navigate between forms, all works as intended. But if i use the "X" close window button on the secondary form and try to open it again from main form, it loses all functionality (main form works fine). It just shows the secondary form as i see it, when i use "View Object" in VBA editor. None of the buttons work and none of the intended boxes and labels are filled. Even the "X" button doesn't work. For me it seems obvious, that the problem is with unloading of secondary form. I tried to replace Me.Hide in secondary form with Unload Me and exactly same thing happens, as if i press the "X" button. So i need to do something with Sub UserForm_Terminate(), i tried to add Me.Hide there and as expected, it did nothing.
I there a solution to my problem?
Thx in advance.
main routine, calling Main Form:
With New formMain
.Show
End With
main form, calling secondary form
Private Sub createFastButton_Click()
Me.Hide
With New formSec
.Show
End With
Me.Show
End Sub
secondary form
Private Sub cancelButton_Click()
Me.Hide
End Sub
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
If CloseMode = VbQueryClose.vbFormControlMenu Then Cancel = True
End Sub
no need for UserForm_Terminate() in secondary form, unless for unsaid needs
Clicking the "X" raises a QueryClose event that you need to handle, e.g.:
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
If CloseMode = VbQueryClose.vbFormControlMenu Then
Cancel = True
Me.Hide
' Add more code here to respond to form close event
End If
End Sub
See here for a very helpful explanation.

UserForm_Initialize() is automatically called when a form variable is accessed in other module

I am trying to get value of some publicly declared userform variable into other module written in other sheets.
first myform.show function initialize the form and set i = 0. But when I closed the form using x button and used the queryclosed function to update the value of i and control return to Myform.val = 10 line then userform_initialize() function is again called and the condition becomes false becoze it again set the i to 0. I don't know why this is happening. Any help please.
my sheet module code is as follows:
Sub myModule()
Myform.Show
If Myform.val=10 then
msg "Hi"
End if
End sub
and Myform code is as follows:
Public i as integer
Private Sub UserForm_Initialize()
i = 0
End sub
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
If CloseMode <> 1 Then
i = 10
End If
End Sub
I want the above if condtion to be true if form is closed using x button and false if form is closed using commandbutton.
I'd like to suggest a few changes. All are not necessary, but it'll help you keep the code neater.
First, use an instance of the form, rather than the form. Second, use properties instead of global variables. Third, if you unload your form, you can't access its values anymore.
The module
Sub myModule()
Dim MyFormInstance As MyForm
Set MyFormInstance = New MyForm
MyFormInstance.Show
If MyFormInstance.Val = 10 Then
MsgBox "Hi"
End If
Unload MyFormInstance
End Sub
And the form
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
If CloseMode <> 1 Then
Cancel = 1
Me.Hide
i = 10
End If
End Sub
Property Get Val() As Integer
Val = i
End Property
Private Sub btnClose_Click()
i = 20
Me.Hide
End Sub

Stop in Close and Open userforms _VBA

I created two forms. Pressing the button 1 opens the form number 2. By closing the form number 2, the form number 1 is displayed. But this action is only done once and it stops for the second time and almost does not work. Where does the code have a problem?
code Userform1:
Private Sub ShowUserform2_Click()
UserForm1.Hide
Unload UserForm1
UserForm2.Show
End Sub
Code userform2:
Private Sub UserForm_Terminate()
UserForm2.Hide
Unload UserForm2
UserForm1.Show
End Sub
Skip the formName.Hide lines. They are unnecessary.
After the Unload formName statements add:
Set formName = Nothing
Also, make the otherForm.Show line precede the above two lines.
Try this code:
code Userform1:
Private Sub ShowUserform2_Click()
UserForm1.Hide
UserForm2.Show
End Sub
Code userform2:
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
UserForm1.Show
End Sub

Command Still Executes Despite Cancel Button

I have a button the executes a user form to display with a required password before executing the buttons command, however when the user form is displaying it freezes the rest of the sheet. On the user Form a I created a cancel button so that the user can exit out of the UserForm should he not know the password and use the other buttons I have on the sheet. When the user clicks the cancel button, it still executes the command even though he/she did not put a password in. The user Form works properly when you enter the correct password/incorrect password, its only when you click cancel that it does not work. Could any on please offer any help? see my code below for the button and the code for my cancel button
Sub Feeder_Schedule()
UserForm1.Show
If Sheets("Bulk_Data").Visible = xlVeryHidden Then
Sheets("Bulk_Data").Visible = True
End If
Sheets("Bulk_Data").Select
Sheets("Home").Visible = xlVeryHidden
End Sub
code for the Cancel button
Private Sub CommandButton1_Click()
Unload Me
End Sub
If you want to make it right change/add to your code of the userform
Option Explicit
' USERFORM CODE
Private m_Cancelled As Boolean
' Returns the cancelled value to the calling procedure
Public Property Get Cancelled() As Variant
Cancelled = m_Cancelled
End Property
Private Sub buttonCancel_Click()
' Hide the Userform and set cancelled to true
Hide
m_Cancelled = True
End Sub
' Handle user clicking on the X button
Private Sub UserForm_QueryClose(Cancel As Integer _
, CloseMode As Integer)
' Prevent the form being unloaded
If CloseMode = vbFormControlMenu Then Cancel = True
' Hide the Userform and set cancelled to true
Hide
m_Cancelled = True
End Sub
Your code could then look like that
Sub Feeder_Schedule()
Dim frm As UserForm1
Set frm = New UserForm1
frm.Show
If Not frm.Cancelled Then
If Sheets("Bulk_Data").Visible = xlVeryHidden Then
Sheets("Bulk_Data").Visible = True
End If
Sheets("Bulk_Data").Select
Sheets("Home").Visible = xlVeryHidden
End If
End Sub

Resources