The OpenForm was cancelled error has reoccurred - vba

The OpenForm has reoccurred in my application. I have decompiled/compact and repaired twice.
Code throwing error:
'Open Menu form
DoCmd.OpenForm "Menu", acNormal, , , , acWindowNormal
The first time I encountered this error, I solved it by changing:
DoCmd.OpenForm "Menu", acNormal, "", "", , acNormal
to
DoCmd.OpenForm "Menu", acNormal, , , , acWindowNormal.
This is my procedure that suffers the exception:
Private Sub Login(recordSet As DAO.recordSet, PERSAL As String, Password As String)
On Error GoTo Login_ErrHandler
'Check to see if the recordset actually contains rows
If Not (recordSet.EOF And recordSet.BOF) Then
recordSet.MoveFirst 'Unnecessary in this case, but still a good habit
'See if credentials match data
Do
If (recordSet!User_ID = PERSAL And recordSet!Password = Password) Then
'Open Menu form
DoCmd.OpenForm "Menu"
' Form_Menu.op
recordSet.Close 'Close the recordset
Set recordSet = Nothing 'Clean up
'Close Login form
DoCmd.Close acForm, "Login"
Exit Do
End If
recordSet.MoveNext
If (recordSet.EOF Or recordSet.BOF) Then
MsgBox "Your credentials are incorrect or you are not registered."
Exit Do
End If
Loop
'Match the values entered for PERSAL nr. and password fields with a row in User table
Else
MsgBox "There are no records in the recordset."
recordSet.Close 'Close the recordset
Set recordSet = Nothing 'Clean up
End If
Form_Login.txtUser_ID.SetFocus
Login_ErrHandler:
If Err = 2501 Then
'MsgBox "No data to display"
DoCmd.Hourglass False
Resume Login_ErrHandler
' Else
' MsgBox Err.Description, vbCritical
End If
End Sub
How do I fix this error this time around?

Create a parameterized query with the following SQL:
PARAMETERS [prmUserId] Text ( 255 ), [prmPassword] Text ( 255 );
SELECT User_ID, Password
FROM YOUR_TABLE_NAME
WHERE ((([User_ID])=[prmUserId]) AND (([Password])=[prmPassword]));
Assuming the code is behind the Login Form:
Private Sub Login(ByVal PERSAL As String, ByVal Password As String)
On Error GoTo Login_ErrHandler
Dim qdf As DAO.QueryDef
Set qdf = CurrentDb().QueryDefs("YourQueryName") 'Change to your query name
qdf.Parameters("[prmUserId]").Value = PERSAL
qdf.Parameters("[prmPassword]").Value = Password
Dim rs As DAO.recordSet
Set rs = qdf.OpenRecordset()
'No records
If rs.EOF Then
MsgBox "Your credentials are incorrect or you are not registered."
Me.txtUser_ID.SetFocus
GoTo Leave
End If
'User found
'Close Login Form
DoCmd.Close acForm, Me.Name, acSavePrompt
'Open Form
DoCmd.OpenForm "Menu", acNormal, , , acFormPropertySettings, acWindowNormal
Leave:
On Error Resume Next
rs.Close
Set rs = Nothing
qdf.Close
Set qdf = Nothing
On Error GoTo 0
Exit Sub
Login_ErrHandler:
MsgBox Err.Number & " - " & Err.Description, vbCritical
Resume Leave
End Sub

Related

MS Access: Trying to create an error if there is a duplicate record but code flags everything

I have a form that if a duplicate record is entered, the form creates an error message and prevents the record from being entered. However, my code is popping up the error message no matter what I'm putting in. My code is this...
Private Sub cmdSave_Click()
' ToDo fix the labels in this function so they match the function name. Just cosmetic.
On Error GoTo Add_CmdSave_Click_Err
On Error Resume Next
' ToDo fix the labels in this function so they match the function name. Just cosmetic.
On Error GoTo Add_CmdSave_Click_Err
On Error Resume Next
Me.cbCompletedTrainingID = Me.IntermediateID
'
Dim OKToSave As Boolean
OKToSave = True
If Not SomethingIn(Me.[fIntermediate FacultyID]) Then ' Null
Beep
MsgBox "A faculty member is required", vbOKOnly, "Missing Information"
OKToSave = False
End If
If Not SomethingIn(Me.[fIntermediate TrainingID]) Then
Beep
MsgBox "A training is required", vbOKOnly, "Missing Information"
OKToSave = False
Else
Dim rs As Object
Set rs = Me.Recordset.Clone
rs.FindFirst "[IntermediateID] = " & Me.[fIntermediate FacultyID] And Me.[fIntermediate TrainingID]
If Not rs.EOF Then
Beep
MsgBox "This person has already completed this training", vbOKOnly, "Duplicate Training Completion"
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
Add_CmdSave_Click_Exit:
Exit Sub
Add_CmdSave_Click_Err:
Resume Add_CmdSave_Click_Exit
End Sub
The issue, from my standpoint, lies in this part...
Dim rs As Object
Set rs = Me.Recordset.Clone
rs.FindFirst "[IntermediateID] = " & Me.[fIntermediate FacultyID] And Me.[fIntermediate TrainingID]
If Not rs.EOF Then
Beep
MsgBox "This person has already completed this training", vbOKOnly, "Duplicate Training Completion"
OKToSave = False
End If
What am I doing wrong?
Have a look at How to debug dynamic SQL in VBA.
This line makes no sense as it is:
rs.FindFirst "[IntermediateID] = " & Me.[fIntermediate FacultyID] And Me.[fIntermediate TrainingID]
You probably want something like
S = "[IntermediateID] = " & Me.[fIntermediate FacultyID] & " And [TrainingID] = " & Me.[fIntermediate TrainingID]
Debug.Print S ' Ctrl+G shows the output
rs.FindFirst S
Also, remove all these On Error Resume Next - this will happily ignore any errors, making debugging nearly impossible.
Also useful: Debugging VBA Code
And there is more: If Recordset.FindFirst doesn't find a match, it doesn't trigger .EOF. It sets the .NoMatch property.
rs.FindFirst S
If rs.NoMatch Then
' all is good, proceed to save
Else
' record exists
End If
This should work as intended:
Dim rs As DAO.Recordset
Dim Criteria As String
Set rs = Me.RecordsetClone
Criteria = "[IntermediateID] = " & Me![fIntermediate FacultyID].Value & " And [TrainingID] = " & Me![fIntermediate TrainingID].Value & ""
Debug.Print OKToSave, Criteria
rs.FindFirst Criteria
If Not rs.NoMatch Then
Beep
MsgBox "This person has already completed this training", vbInformation + vbOKOnly, "Duplicate Training Completion"
OKToSave = False
End If
rs.Close
Debug.Print OKToSave

How to handle errors on broken table links

I have recently updated my linked tables to use UNC links. However when I test the front end using a machine which does not have the mapped drives,
my error handling procedure fails in line Set rs = CurrentDb.OpenRecordset("SELECT ItemName FROM tblDonatedItems") with error number 3044
Is there a way of trapping the error so that the procedure can keep running? Please see below:
Private Sub Form_Load()
On Error Resume Next
Dim rs As DAO.Recordset
Set rs = CurrentDb.OpenRecordset("SELECT ItemName FROM tblDonatedItems")
If Err.Number <> 0 Then
MsgBox "Error Number: " & Err.Number & " " & Err.Description & " Please link to backend file!", , "Locate backend file"
Call AttachDataFile
End If
rs.Close
Set rs = Nothing
DoCmd.Close acForm, Me.Name
DoCmd.OpenForm "frmSplash"
End Sub
I have also tried this without success:
Private Sub Form_Load()
On Error GoTo ErrorHandler
Dim rs As DAO.Recordset
Set rs = CurrentDb.OpenRecordset("SELECT ItemName FROM tblDonatedItems")
ErrorHandler:
If Err.Number <> 0 Then
MsgBox "Error Number: " & Err.Number & " " & Err.Description & " Please link to backend file!", , "Locate backend file"
Call AttachDataFile
rs.Close
Set rs = Nothing
DoCmd.Close acForm, Me.Name
DoCmd.OpenForm "frmSplash"
Else: MsgBox ("Error! Please email: info#abc.com Quoting Error Number: " & " Err.Number"), vbCritical
DoCmd.OpenForm "frmSplash"
End If
End Sub

Show Login name on welcome form

I have made a database in VBA access. I want to display login name on welcome form. Please guide me in this regard. I m trying to pass username from login form to welcome form through public variable but not working. My code is as under:-
Login Form Code
enter code here
Public strUserID As String
Private Sub cmdLogin_Click()
Dim db As DAO.Database
Dim rst As DAO.Recordset
Dim strSQL As String
If IsNull(Me.txtLoginID) Or Me.txtLoginID = "" Then
MsgBox "Enter user Name.....", vbInformation, "Whiz Alert!"
Me.txtLoginID.SetFocus
Exit Sub
End If
If IsNull(Me.txtPassword) Or Me.txtPassword = "" Then
MsgBox "Enter Password.....", vbInformation, "Whiz Alert!"
Me.txtPassword.SetFocus
Exit Sub
End If
strSQL = "SELECT UserID FROM User WHERE LoginID = """ & Me.txtLoginID.Value & """ AND Password = """ & Me.txtPassword.Value & """"
Set db = CurrentDb
Set rst = db.OpenRecordset(strSQL)
If rst.EOF Then
MsgBox "Incorrect Username/Password.", vbCritical, "Login Error"
Me.txtLoginID.SetFocus
Else
DoCmd.Close acForm, "Index", acSaveYes
DoCmd.OpenForm "HomePage", acNormal, , , , acWindowNormal
DoCmd.Close acForm, "UserLoginForm", acSaveYes
End If
Set db = Nothing
Set rst = Nothing
End Sub
Private Sub txtLoginID_AfterUpdate()
strUserID = Me.txtLoginID
End Sub
Welcome form Code
Private Sub Form_Current()
Me.txtUser = UserLoginForm.strUserID
End Sub
I would move the login operation to a separate function and act according to the return value.
A simple login method which returns True if login was successful, or False if it wasn't. No need to open a recordset here, a simple DCount() will do.
Public Function TryToLogin(ByVal Username As Variant, ByVal Password As Variant) As Boolean
On Error GoTo Trap
'validation
Select Case True
Case IsNull(Username):
MsgBox "Enter user Name.....", vbInformation, "Whiz Alert!"
GoTo Leave
Case IsNull(Password):
MsgBox "Enter Password.....", vbInformation, "Whiz Alert!"
GoTo Leave
End Select
'credentials correct?
If DCount("UserID", "User", "LoginID='" & Username & "' AND Password='" & Password & "'") = 0 Then
MsgBox "Incorrect Username/Password.", vbExclamation, "Login Error"
GoTo Leave
End If
'login successful
TryToLogin = True
Leave:
On Error GoTo 0
Exit Function
Trap:
MsgBox Err.Description, vbCritical
Resume Leave
End Function
The method (I assume a button click event) to call the login function. Check the return value and act based on it. If successful, you can pass the Username using the form's OpenArgs parameter. I presume the welcome form is the homepage?
Private Sub Button_Click()
If Not TryToLogin(txtLoginID.Value, txtPassword.Value) Then Exit Sub
With DoCmd
.Close acForm, "Index", acSaveYes
.OpenForm "HomePage", acNormal, , , , acWindowNormal, txtLoginID.Value
.Close acForm, "UserLoginForm", acSaveYes
End With
End Sub
Lastly, handle the OpenArgs in the welcome form's Load() event.
Private Sub Form_Load()
If Not IsNull(OpenArgs) Then
'the OpenArgs now holds the username.
End If
End Sub

Run-Time Error 3008 when trying to run a delete query. Error is saying that the table records it is trying to delete is already open?

This code below is giving me a runtime error stating the table is already open by another user, when I am trying to execute a delete query. It is only giving me this error on this delete query when I am trying to run it strictly through vba, but if i try to run it manually It works as it is designed too? Also, if I comment out this delete query I end up having no issues?
Private Sub Command27_Click()
Dim dbs As dao.Database
Dim Response As Integer
Dim strSQL As String
Dim Query1 As String
Dim LTotal As String
Dim Excel_App As Excel.Application 'Creates Blank Excel File
Dim strTable As String ' Table in access
LTotal = DCount("*", "tbPrintCenter03 RequestedToPrint", "Assigned= True")
Select Case MsgBox("There are (" & LTotal & ") record(s) selected to be
printed." & vbNewLine & " Do you wish to continue?", vbQuestion + vbYesNo,
"Mark as Printed?")
'If yes is Clicked
Case vbYes
Assigned = True 'Changes from false to True
Assigned_User52 = fOSUserName 'Assigns their 5&2
Assigned_Date = Date + Time 'Gets timestamp
'Updates the Global Table in SQL
DoCmd.SetWarnings False
DoCmd.OpenQuery "Qry_UpdateMasterfrom04", acViewNormal, acEdit
DoCmd.OpenQuery "Qry_AppendTo05Que", acViewNormal, acEdit
DoCmd.OpenQuery "Qry_DeletePrinted", acViewNormal, acEdit
''Run-Time error 3006 is happening on this line of code
DoCmd.Close acForm, "tbPrintCenter_Main", acSaveYes 'Save and Close
DoCmd.OpenForm ("tbPrintCenter_Main") 'Opens Form
'-------------------------------------------------------------------------------
'Reference Only
' DoCmd.GoToRecord , , acNext 'Goes to next record
' ' DoCmd.GoToRecord , , acNext
'-------------------------------------------------------------------------------
strTable = "tbPrintCenter05Que" 'Access Table I am trying to copy
Set Excel_App = CreateObject("Excel.Application")
Set dbs = CurrentDb
Dim rs As dao.Recordset
Set rs = dbs.OpenRecordset(strTable)
Excel_App.Visible = True
Dim wkb As Excel.Workbook
Set wkb = Excel_App.Workbooks.Add
Dim rg As Excel.Range
Dim i As Long
' Add the headings
For i = 0 To rs.Fields.Count - 1
wkb.Sheets(1).Cells(1, i + 1).Value = rs.Fields(i).Name
Next i
Set rg = wkb.Sheets(1).Cells(2, 1)
rg.CopyFromRecordset rs
' make pretty
rg.CurrentRegion.EntireColumn.AutoFit
DoCmd.OpenQuery "Qry_DeleteRecordsFrom05", acViewNormal, acEdit
Response = MsgBox("Updated to an assigned user!", vbInformation + vbOKOnly)
'MsgBox Update Complete
DoCmd.SetWarnings True
Exit Sub
'If no is clicked
Case vbNo
Response = MsgBox("No actions are performed!", vbInformation)
Exit Sub
End Select
End Sub
Following the link provided you will see the code I am using bits and pieces ofr on. Any advice?
https://stackoverflow.com/a/58732371/10226211

MS Access: Calling VBA function in form event property (like On Dbl Click) - refers to object closed or doesn't exist

I have taken a macro that was embedded and converted it into vba so I can call it on different forms when needed. The form I am using is an employee list form and I am using it on the first name. I have tried calling the function by putting =MyFunction() and I get the object is closed or doesn't exist.
It works as an embedded macro; however, when I try to use it as a standalone I get an error and when I converted it I get the above error.
Function Copy_Of_CompID_Fields()
On Error GoTo Copy_Of_CompID_Fields_Err
With CodeContextObject
On Error Resume Next
If (Eval("[Forms].[Dirty]")) Then
DoCmd.RunCommand acCmdSaveRecord
End If
If (.MacroError.Number <> 0) Then
Beep
MsgBox .MacroError.Description, vbOKOnly, ""
Exit Function
End If
On Error GoTo 0
If (IsNull(.New_Id)) Then
Exit Function
End If
If (.CreatedDate < #5/1/2019#) Then
DoCmd.OpenForm "Employee Details", acNormal, "", "[ID]='" & .ID & "'", , acNormal
Else
DoCmd.OpenForm "Employee Details", acNormal, "", "[New_Id]=" & .ID, , acNormal
End If
TempVars.Add "CurrentID", .ID
DoCmd.Requery ""
DoCmd.SearchForRecord , "", acFirst, "[ID]='" & TempVars!CurrentID & "'"
TempVars.Remove "CurrentID"
End With
Copy_Of_CompID_Fields_Exit:
Exit Function
Copy_Of_CompID_Fields_Err:
MsgBox Error$
Resume Copy_Of_CompID_Fields_Exit
End Function