I have created a form where I enter in faculty information and I made error messages appear if certain fields are missing.
However, as soon as I click save, the form saves the entry like I wanted, but also immediately generates the error messages I created, even though I didn't have a chance to enter anything new into the fields. My code is this...
' Click event for Save button
Private Sub cmdSave_Click()
' ToDo fix the labels in this function so they match the function name. Just cosmetic.
On Error GoTo Add_Faculty_Click_Err
On Error Resume Next
DoCmd.GoToRecord , "", acNewRec
' Error handling for FirstName
Dim OKToSave As Boolean
OKToSave = True
If Not SomethingIn(Me.FirstName) Then ' Null
Beep
MsgBox "A first name is required", vbOKOnly, "Missing Information"
OKToSave = False
End If
If Not SomethingIn(Me.Combo17) Then
Beep
MsgBox "A department is required", vbOKOnly, "Missing Information"
OKToSave = False
End If
If Not SomethingIn(Me.LastName) Then
Beep
MsgBox "A last name is required", vbOKOnly, "Missing Information"
OKToSave = False
End If
If Not SomethingIn(Me.Text19) Then
Beep
MsgBox "A user name is required", vbOKOnly, "Missing Information"
OKToSave = False
Else
Dim myUserName As String
myUserName = "UserName = " + Chr(34) + Me.Text19 + Chr(34)
If DLookup("UserName", "tFaculty", myUserName) <> Null Then
MsgBox "User name already on file", vbOKOnly, "User name already on file."
OKToSave = False
End If
End If
If OKToSave Then
' If we get this far, all data is valid and it's time to save
DoCmd.RunCommand acCmdSaveRecord
' ToDo refresh and synch combo box
Me.cbFacultyID = Me.FacultyID
' ToDo hide save and cancel buttons
Me.cmdSave.Visible = False
Me.cmdCancel.Visible = False
' ToDo show Add and delete buttons
Me.[Add Faculty].Visible = True
Me.Delete.Visible = True
End If
Add_Faculty_Click_Exit:
Exit Sub
Add_Faculty_Click_Err:
Resume Add_Faculty_Click_Exit
End Sub
I thought I fixed things with the OKToSave portion, but its not working. What is causing this?
The very first thing your handler does is move to a new record:
DoCmd.GoToRecord , "", acNewRec
That saves the record. Nothing after that matters. So remove that line.
Replace the line:
DoCmd.RunCommand acCmdSaveRecord
With this instead:
Me.Dirty = False
DoCmd.GoToRecord , "", acNewRec
This will make it so you won't save and move the current record until it's OKToSave
Related
Im trying to do some error handling for my code and I want my custom error message to appear if the user is trying to enter an already existing record. Access gives its own standard error message indicating a duplicate record, but I want mine displayed instead. The issue is the part of the code where I have my custom error message isn't being reached, therefore giving me the default message.
The name of the textbox is "DepartmentCode", the name of the table its being drawn from is "tDepartment" and the column name is "DepartmentCode"
My code is this...
Private Sub bAddDepartment_Click()
On Error GoTo bAddDepartment_Click_Err
Dim OKToSave As Boolean
OKToSave = True
If Not SomethingIn(Me.DepartmentCode) Then ' Null
Beep
MsgBox "A department code is required", vbOKOnly, "Missing Information"
OKToSave = False
Else
Dim myDepartmentCode As String
myDepartmentCode = "DepartmentCode = " + Chr(34) + Me.DepartmentCode + Chr(34)
If DLookup("DepartmentCode", "tDepartment", myDepartmentCode) <> Null Then
MsgBox "Department already on file", vbOKOnly, "Department already on file."
OKToSave = False
End If
End If
If OKToSave Then
' If we get this far, all data is valid and it's time to save
Me.Dirty = False
DoCmd.GoToRecord , "", acNewRec
End If
bAddDepartment_Click_Exit:
Exit Sub
bAddDepartment_Click_Err:
Resume bAddDepartment_Click_Exit
End Sub
The part not being reached is If DLookup("DepartmentCode", "tDepartment", myDepartmentCode) <> Null Then
Why is this happening?
Debugging VBA Code <-- to see which lines are actually executed.
If DLookup("DepartmentCode", "tDepartment", myDepartmentCode) <> Null Then
You can't compare to Null like that. Try this in the Immediate Window:
? ("foo" <> Null)
Null
Use IsNull()
If Not IsNull(DLookup("DepartmentCode", "tDepartment", myDepartmentCode)) Then
or if empty strings are also possible, use Nz()
If Nz(DLookup("DepartmentCode", "tDepartment", myDepartmentCode), "") <> "" Then
Hi I am working on patient management tool where in i wanted to have patient engagement status fields as open,close and reopen. when i change the closed patient to reopen it should add it as new record instead of updating the current record. I have tried to do it in the "cmdsave" to check for status and then add as new or update.
the issue is whenever i changed the combo box, the value is getting saved in the table even before i clicked the save command.
Private Sub CmdSaveEng_Click()
On Error GoTo CmdSaveEng_Click_Err
On Error Resume Next
Call checkReopenexists
If pExists = False Then
saved = True
Call addNewRecord
Me.CmdSaveEng.Enabled = False
saved = False
Exit Sub
Else
saved = True
DoCmd.RunCommand acCmdSaveRecord
Me.CmdSaveEng.Enabled = False
saved = False
If (MacroError <> 0) Then
Beep
MsgBox MacroError.Description, vbOKOnly, ""
End If
Beep
MsgBox "Data Saved Successfully", vbInformation, "Save"
End If
CmdSaveEng_Click_Exit:
Exit Sub
CmdSaveEng_Click_Err:
MsgBox Error$
Resume CmdSaveEng_Click_Exit
End Sub
You can't do it that way.
Create a button that will create a copy of the current record, then move to the copied record for further editing:
Copy record to new record
Please, HELP
I have a login form where Combo box contains 3 fields (EmployeeID, Employee Name: [FirstName] & " " & [LastName], JobTitle - qry picked). In dropdown list is only one field shown (properties set 0', 1', 0' width). Also frmLogin contains a text box to enter a password and there are two hidden text boxes (Name and JobTitle for other functions to perform). When I choose the UserName, hidden boxes are populated; however, when I enter password, the popup window shows up with Run-time error ‘2471’ - The expression you entered as a query parameter produced the following error: ‘admin’.
Here is a code to log in.
Private Sub cmdLogin_Click()
If IsNull(Me.cboLoginName) Or Me.cboLoginName = "" Then
MsgBox "You must select an employee name.", vbOKOnly, "Required data"
Me.cboLoginName.SetFocus
Exit Sub
End If
If IsNull(Me.tbxPassword) Or Me.tbxPassword = "" Then
MsgBox "You must enter a password", vbOKOnly, "Required data"
Me.tbxPassword.SetFocus
Exit Sub
End If
'next line is highlighted as error
If Me.tbxPassword.Value = DLookup("Password", "tblEmployees", "[EmployeeID]=" & Me.cboLoginName.Value) Then
Me.Visible = False
DoCmd.OpenForm "frmEntry"
Else
MsgBox "Invalid employee name / password combination. Please try again.", vbOKOnly, "Invalid Entry!"
Me.tbxPassword.SetFocus
End If
End Sub
Query for the combobox
Since I don't know the rowsource of your combobox or the number of columns your control specifies, paste the following code before your DLookup and see which column you should be using:
Dim i As Integer
For i = 0 To Me.cboLoginName.ColumnCount
Debug.Print "Column " & i & " contains '" & Me.cboLoginName.Column(i) & "'"
Next i
I am trying to check if the password is the same or not (in terms of caps too) using vb.net. But the line
result = String.Compare(actPassword,userPassword)
keep giving error "Compile Error: Expected:("
Private Sub Login_Click()
'Check to see if data is entered into the UserName combo box
If IsNull(Me.cmbLoginID) Or Me.cmbLoginID = "" Then
MsgBox "You must enter a User Name.", vbOKOnly, "Required Data"
Me.cmbLoginID.SetFocus
Exit Sub
End If
'Check to see if data is entered into the password box
If IsNull(Me.txtPW) Or Me.txtPW = "" Then
MsgBox "You must enter a Password.", vbOKOnly, "Required Data"
Me.txtPW.SetFocus
Exit Sub
End If
'Check value of password in tblEmployees to see if this matches value chosen in combo box
Dim userPassword As String
Dim actPassword As String
Dim result As Integer
userPassword = txtPW.Text
actPassword = DLookup("EmpPassword", "Employee", "EmployeeID='" + Me.cmbLoginID.Value + "'")
result = String.Compare(actPassword,userPassword)
If result = -1 Then
'Close logon form and open splash screen
DoCmd.Close acForm, "Login", acSaveNo
DoCmd.OpenForm "HomePage"
Else
MsgBox "Password Invalid. Please Try Again", vbCritical + vbOKOnly, "Invalid Entry!"
Me.txtPW.SetFocus
End If
'If User Enters incorrect password 3 times database will shutdown
intLogonAttempts = intLogonAttempts + 1
If intLogonAttempts > 3 Then
MsgBox "You do not have access to this database. Please contact your system administrator.", vbCritical, "Restricted Access!"
Application.Quit
End If
End Sub
That's because there is no String.Compare() in VBA (There is in VB.NET)
Also, please note VB.NET is not VBA
Use StrComp
Use StrComp
result = StrComp(actPassword, userPassword, vbTextCompare)
While String.Compare() exists in VB.Net, I don't think it does in VBA. In any case, what you're doing is wrong anyway.
String.Compare can return any integer and it will only return zero if they match. Your particular test (comparing against -1) is only checking one possibility, that the actual password is less than the desired one, and it's only checking for one of the possible negative values.
You would be better off in that case with something like:
if result <> 0 Then
However, if you just want to compare two strings for equality in VBA (rather than figure out the relative ordering), you can just use:
if actPassword = userPassword Then
I am sending data from frmSearchEmployeeWorksheets to frmStatsCorr which runs a query (qryStatsCorr). On frmStatsCorr I am checking to make sure the query returns records otherwise I will Msg the user and return to the search form. My problem is that I am having problems 'ignoring' the 2501 caused by the DoCmd.OpenForm ("frmStatsCorr") which I learned here on Stackoverflow...
What am I doing wrong that is causing me major Access VBA Frustration??
This is the sub on the Search form (frmSearchEmployeeWorksheets):
Private Sub btnSearch_Click()
' I only change focus to force the updated data to submit to query
Me.[txtEmployee].SetFocus
Me.txtShift.SetFocus
If txtUnit = "7" Then
'First close the form in order to update
DoCmd.Close acForm, "frmStatsCorr"
' Open Stats form
On Error GoTo myErr
**DoCmd.OpenForm ("frmStatsCorr") 'causes error**
End If
myExit:
Exit Sub
myErr:
Echo True
If Err.Number = 2501 Then GoTo myExit
MsgBox Err.Description
GoTo myExit
End Sub
In frmStatsCorr I simply check to make sure the query returns records if not I inform the user, close the form, and return to the frmSearchEmployeeWorksheets
Private Sub Form_Load()
If strFormStatus = "view" Then
If DCount("*", "qryStatsCorr") = 0 Then
MsgBox "Your search does not produce any results. Try a different search.", vbOKOnly
DoCmd.Close
DoCmd.OpenForm ("frmSearchEmployeeWorksheets")
Exit Sub
End If
txtDay = WeekdayName(Weekday(Me.WorkDate)) 'This line returns an error so I check for an empty query and return to the search form.
Me.[WorkDate].SetFocus
Me.txtUnit.Enabled = False...
I'm unsure how well I understand your code or the logic behind it. My hunch is you should check the DCount result from btnSearch_Click, and not fiddle with closing then re-opening frmStatsCorr, and having frmStatsCorr close itself when it contains no data. Just do not open frmStatsCorr when it will not contain data.
If the current form (frmSearchEmployeeWorksheets) which holds your btnSearch_Click procedure contains unsaved data changes, you can save them with Me.Dirty = False
Private Sub btnSearch_Click()
Dim strPrompt As String
If Me.Dirty Then ' unsaved data changes
Me.Dirty = False ' save them
End If
If Me.txtUnit = "7" Then
If DCount("*", "qryStatsCorr") = 0 Then
strPrompt = "Your search does not produce any results. " & _
"Try a different search."
MsgBox strPrompt, vbOKOnly
Else
' if frmStatsCorr is open, just Requery
' else open frmStatsCorr
If CurrentProject.AllForms("frmStatsCorr").IsLoaded Then
Forms("frmStatsCorr").Requery
Else
DoCmd.OpenForm "frmStatsCorr"
End If
' uncomment next line to close current form
'DoCmd.Close acForm, Me.Name
End If
End If
End Sub
If frmStatsCorr is open and you need to check whether it is in Design View, examine its CurrentView property.
Forms("frmStatsCorr").CurrentView ' Design View = 0
I suggested that approach because I suspected frmStatsCorr's Form_Load may trigger the 2501 error when it closes itself. But I'm not certain that's the cause of the error and I'm not motivated enough to set up a test.
If you still have 2501 errors with the approach I suggested, there are two other possible causes I've encountered:
corruption
broken references