Check if a Textbox is empty when closing form (1 Viewer)

Runes

Registered User.
Local time
Yesterday, 19:12
Joined
Feb 11, 2010
Messages
20
Hi
Can someone help me with a VBA code that will check if a Textbox1 in Form1 is empty / null when you click the close button? If the specific Texbox1 is empty/null a message box with a text pop up and when you click OK you are redirected to the form. You can’t close the form if Textbox1 is empty/null.
Thank you
 

Ranman256

Well-known member
Local time
Yesterday, 22:12
Joined
Apr 9, 2015
Messages
4,339
Code:
 sub btnClose_Click
  
if isnull([FONT=Calibri]Textbox1 ) then[/FONT]
 [FONT=Calibri]     msgbox "you cant close the form yet"[/FONT]
[FONT=Calibri]else[/FONT]
 [FONT=Calibri]      docmd.close[/FONT]
[FONT=Calibri]endif[/FONT]
 [FONT=Calibri]end sub[/FONT]
 

arnelgp

..forever waiting... waiting for jellybean!
Local time
Today, 10:12
Joined
May 7, 2009
Messages
19,231
You can’t close the form if Textbox1 is empty/null.
Code:
Private Sub btnClose_Click()
    On Error GoTo err_handler
    DoCmd.Close acForm, Me.Name
continue_here:
    Exit Sub
err_handler:
    If Err.Number = 2501 Then
    Else
        MsgBox Err.Number & ", " & Err.Description
    End If
    Resume continue_here:
    Resume
End Sub

Private Sub Form_Unload(Cancel As Integer)
    If Trim(Me.Textbox1 & "") = "" Then
        MsgBox "You must supply value to Textbox1."
        Cancel = True
    End If
 End Sub
note that this will prevent the form from closing if Textbox1 is not filled in even clicking on the "x" button.
 

Runes

Registered User.
Local time
Yesterday, 19:12
Joined
Feb 11, 2010
Messages
20
arnelgp

Should i put the name of the form after Me. in this line?
DoCmd.Close acForm, Me.Name

If i don't, nothing happend when I Close the form With empty textbox. If I change it to Me.NameOfForm, then I got this error

Run-time error '2498': An expression you entered is the wrong data type for one of the arguments.
 

arnelgp

..forever waiting... waiting for jellybean!
Local time
Today, 10:12
Joined
May 7, 2009
Messages
19,231
mr.runes, no, you don't have to put the name of the form.
Me refers to the form object. and Me.Name, we are telling access to get the name of the form for us. (.Name is property of the form).
 

Users who are viewing this thread

Top Bottom