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
Related
This code is for a login form I have setup to enter the front end copy of a database. In one database it works like a charm. I imported the form and corresponding objects to another database and it appears to be not recognizing my password when I enter it. I just keep getting the message box I have popping up that says, "Incorrect password". Any help figuring this out would be greatly apprecaited.
The SQL statement that drives the cboUser combo box on the login form is:
SELECT tblUser.UserID, [FName] & " " & [LName] AS Fullname,
tblUser.Password, tblUser.PWReset, tblUser.AccessLevelID
FROM tblUser ORDER BY tblUser.LName, tblUser.FName;
.
Private Sub OkBTN_Click()
Static intIncorrectCount As Integer
Dim AuthorityNumber As Integer
'Dim rs As Recordset
'TempVars("Username") = Me.cboUser.Value
'Column references for cbouser row source reference
'UserID = 0
'FullName = 1
'Password = 2
'PWReset = 3
'AccessLevelID = 4
'Set rs = CurrentDb.OpenRecordset("UserNameQuery", dbOpenSnapshot)
'N = Nz(DLookup("Fullname", "UserNameQuery", "Fullname=""" & Me.cboUser & """"), " ")
'Check that User is selected
If IsNull(Me.cboUser) Then
MsgBox "You forgot To Select your name from the drop down menu!", vbCritical
Me.cboUser.SetFocus
Else
'Check for correct password
If Me.txtPassword = Me.cboUser.Column(2) Then
'Check if password needs to be reset
If Me.cboUser.Column(3) Then
DoCmd.OpenForm "frmPasswordChange", , , "[UserID] = " & Me.cboUser
End If
Me.Visible = FALSE
intIncorrectCount = 0
'Main menu after correct login based on AuthorityNumber
If Me.cboUser.Column(4) = 5 Then
DoCmd.OpenForm "SRL1MainMenu"
'Forms!AMSReportForm!L2Menubtn.Visible = False
Forms!SRL1MainMenu!FullNameLoggedIn = Forms!frmLogin!cboUser.Column(1)
Else
DoCmd.OpenForm "L2MainMenu2"
'Forms!AMSReportForm!L2Menubtn.Visible = True
Forms!L2MainMenu2!FullNameLoggedIn = Forms!frmLogin!cboUser.Column(1)
End If
'Failed login attempt limitation
ElseIf intIncorrectCount > 1 Then
MsgBox "Too many failed login attempts. Click OK To Set New password", vbOK + vbExclamation
DoCmd.OpenForm "frmPasswordChange", , , "[UserID] = " & Me.cboUser
'DoCmd.Close acForm, "frmLogin"
Else
MsgBox "Incorrect password", vbOKOnly + vbExclamation
Me.txtPassword = Null
Me.txtPassword.SetFocus
intIncorrectCount = intIncorrectCount + 1
End If
End If
End Sub
First, #Andre is probably right - you may have to apply brackets to "Password".
Next, this may not perform a case sensitive comparison:
If Me.txtPassword = Me.cboUser.Column(2) Then
Use StrComp to do that:
If StrComp(Me!txtPassword.Value, Me!cboUser.Column(2), vbBinaryCompare) = 0 Then
Finally, you should never store plain passwords; store a hash value instead. It isn't that difficult, if you study my latest article:
Storing passwords in VBA using the Microsoft NG Cryptography (CNG) API
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
I would like to know what the preferred function to put in a code string immediately after a user selects a selection box control of a record so that his selection is acknowleged and included as "true". In short, I have a form where the user uses a selection box to indicate which records to select and then executes a command where I have code that should copy and paste the records he selected. Unfortunately, the last record selected, upon running executing the copy/paste command is not recognised. I understand that I probably need to add a function such as ' go-to the next record' however I am not sure if this is the best way or if there is a more standard way that programmers use to not lose the last record selected. Below is the code I am currently using which currently does not pick up the last record selected by the user.
Private Sub Comando99_Click()
If CurrentRecord = Recordset.RecordCount And CurrentRecord <> 1 Then
DoCmd.GoToRecord , "", acFirst
Else
DoCmd.GoToRecord , "", acNext
End If
Dim intAnswer As Integer
On Error GoTo HandleError
intAnswer = _
MsgBox("Are you sure you want to add these dependencies to your dependency project tracker?", _
vbQuestion + vbYesNo, "Add Dependencies")
If intAnswer = vbYes Then
st_sql = "INSERT INTO [tblDependencies] ( [Description] )SELECT [tblDependencyTypeListing].[Dependency (General)] FROM [tblDependencyTypeListing] WHERE ((([tblDependencyTypeListing].[ToIncludeInProject])=True))"
Application.DoCmd.RunSQL (st_sql)
st_sql = "UPDATE[tblDependencies],[tblHoldingProjectid]SET[tblDependencies].[ID Project]=[tblholdingprojectid].[ID_Project]where([tbldependencies].[ID Project])=0 and ([tblholdingprojectid].[ID_Project])is not null"
Application.DoCmd.RunSQL (st_sql)
st_sql = "UPDATE[tblDependencies]SET[tblDependencies].[Automatic date of entry]=now() where([tblDependencies].[Automatic date of entry])is null"
Application.DoCmd.RunSQL (st_sql)
st_sql = "UPDATE[tblContacts],[tblDependencies]SET[tblDependencies].[Automatic user entry]=[tblContacts].[Complete name]where([tblContacts].[In use])is not null and([tblDependencies].[Automatic user entry])is null"
Application.DoCmd.RunSQL (st_sql)
st_sql = "UPDATE[tblDependencytypelisting]SET[tblDependencytypelisting].[toincludeinproject]=null"
Application.DoCmd.RunSQL (st_sql)
Me.Refresh
End If
ExitHere:
Exit Sub
HandleError:
MsgBox "Error is " & Err.Description
Resume ExitHere
End Sub
Problem is resolved by entering the following IF statement at the beginning of the routine to ensure that prior to running the code, ACCESS moves to the next record to ensure that it acknowledges the last modification made
If CurrentRecord = Recordset.RecordCount And CurrentRecord <> 1 Then
DoCmd.GoToRecord , "", acFirst
Else
DoCmd.GoToRecord , "", acNext
End If
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