Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Cancel button in a form 1

Status
Not open for further replies.

Handford

Technical User
Oct 4, 2005
19
GB
I have a form I use to enter new data into a table. When it opens it goes to new record. I would like to add a button which allows the user to leave this form without saving the new addition (and not forcing user to enter required fields). What is easiest way of achieving this?

I am very much a VB novice and have made the rest of my database work with just macros.

I appreciate any help

Handford
 
Hi
Here is a rough idea. Most of the code below was generated by a wizard.

Create a command button and name it cmdCancel. Go to the Events tab of the property sheet and click the ellipsis (...) beside On Click. Choose Code Builder, then paste the code below between:
Private Sub cmdCancel_Click()
<code goes here>
End Sub

Please note that if you are using an autonumber and the user has entered data, the autonumber will increment.
Code:
Private Sub cmdCancel_Click()
On Error GoTo Err_cmdCancel_Click

    'Generated by Wizard
    'DoCmd.DoMenuItem acFormBar, acEditMenu, acUndo, , acMenuVer70
    If Me.Dirty Then
        DoCmd.RunCommand acCmdUndo
    End If
    DoCmd.Close
    
Exit_cmdCancel_Click:
    Exit Sub

Err_cmdCancel_Click:
    MsgBox Err.Description
    Resume Exit_cmdCancel_Click
    
End Sub
 
Mine is a different approach,
I will try to open an unbound form to do this.
a sample code is below.

Code:
Private Sub cmdSave_Click()
    Dim cn As ADODB.Connection
    Dim rs As ADODB.Recordset
    Dim strSQL As String
    Set cn = CurrentProject.Connection
    Set rs = New ADODB.Recordset
    
    strSQL = "SELECT * FROM YourTableName"
    rs.Open strSQL, cn, adOpenKeyset, adLockOptimistic
    
    rs.AddNew
    
    rs("FieldName1") = Me.TextBox1.Value
    rs("FieldName2") = Me.TextBox2.Value
    rs("FieldName3") = Me.TextBox3.Value
    
    rs.Update
    
    rs.Close
    cn.Close
    Set rs = Nothing
    Set cn = Nothing
End Sub
and a cancel button
Code:
Private Sub cmdCancel_Click()
    DoCmd.Close acForm, Me.Name
End Sub
apart this you need to verify the data entered is correct for the field that is to be. (ie Numeric, Date, Currency etc)

You can have many samples here for data validation etc.

Form - looping thru the controls faq702-5010 is one of that


________________________________________________________
Zameer Abdulla
Help to find Missing people
My father was a realistic father; not a vending machine dispense everything I demanded for!!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top