Trouble trapping 2501 error - vba

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

Related

Automation to verify user form is open and if not, close Excel using CATIA VBA

I'm working on a project to detect if a user form is open and if not, close an excel program hidden in the background. The issue I'm having is the if statement in the Function Excel_Form_Close. The if statement works independently and does what it should do but when moved into the function area, the msgbox "Entered" triggers but the If statements do not. Why would the If statement be getting skipped during the load?
Sub Macro_Timer()
CATIA.Application.OnTime Now + TimeValue("00:00:10"), "Excel_Form_Close"
End Sub
Function Excel_Form_Close()
MsgBox "Entered Excel_Form_Close"
If Currentproject.Allforms("USER_FORM").IsLoaded = False Then
Call APP_CLOSE(LIST_APP, LIST_FILE)
MsgBox "Excel Closed"
End
End If
If Currentproject.Allforms("USER_FORM").IsLoaded = True Then
MsgBox "USER FORM CURRENTLY LOADED"
Call Macro_Timer
End If
End Function
maybe bcs the end function you have on the first if statement completely shutdowns your code if no necessity so ever, you could also add only one if statement in ur function after all there is only two possibilities. Here is the possible fix.
Function Excel_Form_Close()
MsgBox "Entered Excel_Form_Close"
If Currentproject.Allforms("USER_FORM").IsLoaded = False Then
Call APP_CLOSE(LIST_APP, LIST_FILE)
MsgBox "Excel Closed"
else
MsgBox "USER FORM CURRENTLY LOADED"
Call Macro_Timer
End If

Subform blocking Recordset.AddNew (Error 3027)

Having a subform displaying the same table used in recordset makes the table read only (error 3027). Getting rid of the subform fixes the problem. Similar setup works in my other form interface.
I tried to delete the subform, which fix the accessibility problem. But that would defeat the original UX purpose.
Option Explicit
Public UnitRS As DAO.Recordset
Public ModelRS As DAO.Recordset
Public NameUnitRecords As String
Public NameModelRecords As String
Public Sub Form_Load()
'Initialization
NameUnitRecords = "tblBatteriesMainRecordsUnits"
NameModelRecords = "tblBatteriesRecordsModels"
End Sub
Private Sub SetUnitRecordsets()
'Set the path to the Battery Records table
Set UnitRS = CurrentDb.OpenRecordset(NameUnitRecords, dbOpenDynaset)
End Sub
Private Sub txtBatteryID_AfterUpdate()
'Set the recordset path for unit records
Call SetUnitRecordsets
'do a findfirst search for the Battery ID, using value from textbox txtBatteryID
UnitRS.FindFirst "[Battery ID]=" & txtBatteryID
'If no matching record, leave the other fields empty
If UnitRS.NoMatch Then
'If there is a matching record, then, grab the model number
Else
'as there is an existing record with model number, run a search on the model number and grab the model info
End If
'close recordset
UnitRS.Close
'check if the button can be enabled
End Sub
Private Sub cmbModelNumber_AfterUpdate()
'Set the recordset path for model records
'do a findfirst search for the Model Number, using value from combobox cmbModelNumber
'If no matching record, leave the other fields empty
If ModelRS.NoMatch Then
'If there is a matching record, then, grab the Model Info
Else
End If
'close recordset
'check if the button can be enabled
End Sub
Private Sub btnSaveAndCLear_Click()
Dim Response, strOldModelNumber
'Set the recordset path for unit records
Call SetUnitRecordsets
'Set the recordset path for model records
'close all related tables, queries and forms
DoCmd.Close acTable, NameUnitRecords, acSaveYes
DoCmd.Close acForm, "frmSubBatteriesMainRecordsUnits", acSaveYes
'If a new model record is required
ModelRS.FindFirst "[Model Number]='" & cmbModelNumber & "'"
If ModelRS.NoMatch Then
'msg box confirm model information
'If user chooses yes
If Response = vbYes Then
'create new model record
'this block could be done with "With...End" format for less error vulerability?
'nah, unless it is repetitively called, it's too much work to inplement just the .addnew part
'requery the two combobox to reflect newest changes
'User chooses no
Else
'popup a message telling the user the battery and model record is not logged, but don't clear the field.
Exit Sub
End If
End If
'need to find the record first, otherwise it will edit the first one
UnitRS.FindFirst "[Battery ID]=" & txtBatteryID
'store the old model number value
strOldModelNumber = UnitRS("Model Number")
'New record
If UnitRS.NoMatch Then
'create a new battery record
UnitRS.AddNew
UnitRS("Battery ID") = Me.txtBatteryID
'If this is an edit on existing record
Else
'if the new value is the same as the old one
If strOldModelNumber = cmbModelNumber Then
'msgbox the same value, no change is done to the database
MsgBox "the data is the same as the old record, no change is made to the record", vbInformation, "Same data"
Exit Sub
Else
'msg box confirm edit
Response = MsgBox("Please confirm edit on existing record: " & Chr(13) & Chr(10) & "BatteryID: " & txtBatteryID & Chr(13) & Chr(10) & "Model Number: " & cmbModelNumber, vbYesNo, "New Model Record Dectected")
'If user chooses yes
If Response = vbYes Then
'goto edit mode
UnitRS.Edit
'if user chooses no
Else
'msgbox notify the user nothing is changed in the database
MsgBox "Battery and Model record not logged, you may retry logging", vbInformation, "Record not logged"
Exit Sub
End If
End If
End If
'both changes the model number and comment field anyway
UnitRS("Model Number") = Me.cmbModelNumber
UnitRS("Comment") = Me.txtComment
'commit update
UnitRS.Update
UnitRS.Close
'clear all flieds
'reset all locks
'requery the sub form to reflect the newest changes
Me.subFrmBatteryRecords.Requery
End Sub
What I would like to achieve is to have a display in the form interface to show the content of the actual record table, so that the user knows what is in the table.
There is nothing wrong with my code. There is a property option in the form object, it's called "record lock", somehow mine had "All Records" selected. By making it "No locks", the accessibility problem is gone.

MS Access vba save button error 3021

For various reasons, I want to set up a custom button on my forms to save the current record. I use a navigation form and want to trigger the same process (integrity-checks, user input etc.) whenever the entry is saved, thus whenever the user presses the "save"-button or switches to another form. The user will conditionally be asked to confirm the process and is thus able to cancel it as well.
Everything is running smoothly with one really odd and annoying exception: Whenever I click the save button on a new record and prompt a message within the "BeforeUpdate" event, I receive
RTE 3021 ("no current record")
Without the MsgBox, everything is fine. Even more strange:
When I trigger the save process by switching to another form using the navigation form (or simply press "outside" the form used for data entry), everything is fine as well.
Here is a minimalistic example (similar results with DoCmd.Save, Requery or acCmdSaveRecord):
Private Sub vt_save_Click()
Me.Dirty = False
End Sub
Private Form_BeforeUpdate(Cancel As Integer)
Cancel = True
MsgBox "Test"
End Sub
Any ideas? I simply can't wrap my head around that error.
You could maybe try to run a query using the values in the form while checking if the record exists or not.
Is there a primary key on the table? if so, the primary key will be your focal point.
Private Sub vt_Save_Click()
dim rst as DAO>Recordset
Dim strSQL as String
Dim strID as string
strID = me.YourPrimaryKeyField
strSQL = "SELECT * " & _
"FROM YourTableName " & _
"WHERE (((YourTableName.YourFieldName) =" & me.PrimaryKeyField & "));"
set rst = currentdb.openrecordset(strsql)
if rst.recordcount = 0 then
currentdb.execute "INSERT INTO YourTableName ( List All Fields to Add ) " & _
"SELECT List All Field controls with values to add;"
End IF
'Anything else you want the code to do from here
EndCode:
If not rst is nothing then
rst.close
set rst = nothing
End IF
End Sub
Repeat this process for the Form_LostFocus() event. If you want to make it easier, make this code a module and call within both event triggers on your form.
If this doesn't work please let me know and I will be happy to further assist.
The most straight forward and reasonable solution is to use an Error Handler - which I ignored so far tenaciously.
Private Sub save_Click()
On Error GoTo Err_Handler
Me.Dirty = False
Exit_Here:
Exit Sub
Err_Handler:
If Err.Number = 2101 Then
'ignore or message
Else
MsgBox Err.Description
End If
Resume Exit_Here
End Sub

Read-Only and undo properties MS Access (VBA)

I have been surfing the wed looking for an answer to what I thought it was a pretty simple question, for a newbie like me.. But havent found any so here I am!. To keep things simple, i'll attach the two bits of my code that are giving me a bit of a headache. What I intend to do is to switch from a Read-Only mode to a Write Allowed state by clicking a button. In order to do so, I want the routine to check for changes on the record and, if there are any ask the user to decide whether to save the changes or discard them.. While testing this particular button, I found out something quite "funny".. It seems to work well when no changes are introduced. Switches perfectly from read-only to write-allow states. However, when in write-allow and changes have been made, if the "Save option" has been selected/clicked then it does not lock the content although all the other subroutines and changes are implemented.
My other problem, closely related to this, is that I cant find a way to set a "saving point" for the undo option. I would like to find a way to "save a record" so when the undo button is pressed doesnt undo all the changes that the record has suffered since the database has been firstly opened (as its currently happening), but since the button has been pressed. I tried the DoCmd Save function but is not behaving as I was expecting (Note: the last 'else' has been my last try to this problem but, again, its not working as expected)
Many thanks for all your future collaboration,
Alex
Private Sub Command28_Click()
If Form_AODNewRecord.AllowAdditions = True Then
Call isModified_Save
Form_AODNewRecord.AllowAdditions = False
Form_AODNewRecord.AllowEdits = False
Form_AODNewRecord.AllowDeletions = False
MsgBox "Read Only. Addition, Edits and Deletions are now locked"
Command28.Caption = "LOCKED"
Else
Form_AODNewRecord.AllowAdditions = True
Form_AODNewRecord.AllowEdits = True
Form_AODNewRecord.AllowDeletions = True
MsgBox "New records, edits and deletions are now allowed"
Command28.Caption = "Lock mode OFF"
End If
MsgBox Form_AODNewRecord.AllowAdditions
End Sub
Sub isModified_Save()
If Form_AODNewRecord.Dirty Then
Dim strMsg As String, strTitle As String
strMsg = "You have edited this record. Do you want to save the changes?"
strTitle = "Save Record?"
If MsgBox(strMsg, vbQuestion + vbYesNo, strTitle) = vbNo Then
Me.Undo
Else
DoCmd.OpenTable "AOD Type", acViewPreview, acReadOnly
DoCmd.Save acTable, "AOD Type"
DoCmd.Close acTable, "AOD Type", acSaveYes
End If
End If
End Sub
I think you want the following code. You cannot open a table that the form is bound to and affect the form, when you open the table, you have two different instances and they do not affect one another.
An odd side effect of running a macro in Office applications is that it clears the Undo list, so I created a small macro that just shows a message "Undo cleared" and that is exactly what it does!
As an aside, rename your control with meaningful names, such as cmdLock, rather than Command28, you will thank yourself later.
Private Sub Command28_Click()
If Me.AllowAdditions = True Then
Call isModified_Save
Me.AllowAdditions = False
Me.AllowEdits = False
Me.AllowDeletions = False
MsgBox "Read Only. Addition, Edits and Deletions are now locked"
Command28.Caption = "LOCKED"
Else
Me.AllowAdditions = True
Me.AllowEdits = True
Me.AllowDeletions = True
MsgBox "New records, edits and deletions are now allowed"
Command28.Caption = "Lock mode OFF"
End If
''MsgBox Me.AllowAdditions
End Sub
Sub isModified_Save()
If Me.Dirty Then
Dim strMsg As String, strTitle As String
strMsg = "You have edited this record. Do you want to save the changes?"
strTitle = "Save Record?"
If MsgBox(strMsg, vbQuestion + vbYesNo, strTitle) = vbNo Then
Me.Undo
Else
''Save record
Me.Dirty = False
''Clear undo list
DoCmd.RunMacro "ClearUndo"
End If
End If
End Sub

editing value in sql server 2005 using vb6 causing the program to hang

I searched about editing value on the net and I did find it, but when I executed it, it returns no error and indeed it inputs the data into sql server but vb6 hangs and needs to be terminated.
It's a hotel system where I updated room status to 'Occupied'.
Private Sub cmdUpdate_Click()
Me.AdodcRoomStatus.Refresh
With Me.AdodcRoomStatus
.Recordset.MoveFirst
Do Until .Recordset.EOF
On Error Resume Next
If (.Recordset.Fields![RoomNo] = Me.cRoomNo) Then
.Recordset.Fields![RoomStatus].Value = "Occupied"
'.Recordset.Fields("RoomStatus").Value = Me.cOccupied
.Recordset.Update
Else
.Recordset.MoveNext
End If
Loop
MsgBox "Changing Room Status Success", vbInformation
End With
End Sub
Coding where i add checkin here, if it can help
Private Sub cmdAdd_Click()
Me.AdodcCheckIn.Refresh
With Me.AdodcCheckIn.Recordset
.AddNew
.Fields![Cust_IC] = Me.cIdenfitication
.Fields![Check_In_Date] = Me.cDateArrive
.Fields![RoomNo] = Me.cRoomNo
.Update
Me.AdodcCheckIn.Refresh
MsgBox "Guests Are Checked In", vbInformation
End With
End Sub
Result is : Guests are checked in,data inputted. And then it goes to update room Status. It hangs there but the value is changed to 'Occupied' in Sql server.
Any help is appreciated.
There seems to be a logical error. In the cmdUpdate_Click function, when the record is updated , there's no movenext OR exit loop. Use either of the 2 and it should stop going into hang state!
Private Sub cmdUpdate_Click()
Me.AdodcRoomStatus.Refresh
With Me.AdodcRoomStatus
.Recordset.MoveFirst
Do Until .Recordset.EOF
On Error Resume Next
If (.Recordset.Fields![RoomNo] = Me.cRoomNo) Then
.Recordset.Fields![RoomStatus].Value = "Occupied"
'.Recordset.Fields("RoomStatus").Value = Me.cOccupied
.Recordset.Update
.Recordset.MoveNext
Else
.Recordset.MoveNext
End If
Loop
MsgBox "Changing Room Status Success", vbInformation
End With
End Sub