Error handling stopping after first loop through For Each loop - ms-access

So I have already solved this problem, though I don't understand why my solution was required. I wanted to make a way to check properties on all forms and all controls within my database so I came up with the following code:
Public Function CheckPropertyAllForms()
Dim obj As Object
Dim ctl As Control
Dim blnFound As Boolean
For Each obj In CurrentProject.AllForms
DoCmd.OpenForm obj.Name, acDesign, , , , acHidden
blnFound = False
For Each ctl In Forms(obj.Name).Controls
On Error GoTo Next_Control
If Nz(ctl.ControlSource, "") <> "" Then
If ctl.ControlSource = "Certain_Field" Then
blnFound = True
End If
End If
Next_Control:
Next ctl
If blnFound = True Then
Debug.Print obj.Name
End If
DoCmd.Close acForm, obj.Name
Next obj
End Function
However this code would only work once, the second time around it would display the error as if error handling was turned off. So I updated it to this:
Public Function CheckPropertyAllForms()
Dim obj As Object
Dim ctl As Control
Dim blnFound As Boolean
For Each obj In CurrentProject.AllForms
DoCmd.OpenForm obj.Name, acDesign, , , , acHidden
blnFound = False
For Each ctl In Forms(obj.Name).Controls
On Error GoTo Err_Handler
If Nz(ctl.ControlSource, "") <> "" Then
If ctl.ControlSource = "Certain_Field" Then
blnFound = True
End If
End If
Next_Control:
Next ctl
If blnFound = True Then
Debug.Print obj.Name
End If
DoCmd.Close acForm, obj.Name
Next obj
Exit_Handler:
Exit Function
Err_Handler:
Resume Next_Control
End Function
Which works exactly how I want it to, however I couldn't find an answer online as to WHY this was happening with my first set of code. Could someone let me know what is happening with my first version of this function to cause the error handling to quit?
Edit: I should also point out that clearly the error handling will be needed because not all controls have a control source. Additionally I don't have a control type check because this function gets updated when a different property is going to be checked.

Along with your On Error statement, you need to have an On Error GoTo 0 statement, too. In your case, it would probably go right before your Next_Control and you could actually get rid of that so your loop would look like this:
For Each ctl In Forms(obj.Name).Controls
On Error Resume Next
If Nz(ctl.ControlSource, "") <> "" Then
If ctl.ControlSource = "Certain_Field" Then
blnFound = True
End If
End If
On Error GoTo 0
Next ctl
The reason for this is that in your first case, the error handler never clears the error object, and there can only be one error active at a time. When an error is active, and another error raises, the handler fails.

Related

DoEvent() Returns 0 BUT Run-time Error 2585 This action can't be carried out while processing a form or report event

This code was running without a hitch, but now getting Error 2585.
I have looked at Gustav's answer and Gord Thompson's answer but unless I am missing something (quite possible!) the first does not work and the second seems inapplicable. I saw on another site a suggestion that there might be a duplicate record ID, but I check for that possibility.
I put a call to DoEvent() in response to this error but it returns zero. I also wait for 10 seconds to let other processes run. Still receive the error.
Private Sub SaveData_Click()
Dim myForm As Form
Dim myTextBox As TextBox
Dim myDate As Date
Dim myResponse As Integer
If IsNull(Forms!Ecoli_Data!DateCollected.Value) Then
myReponse = myResponse = MsgBox("You have not entered all the required data. You may quit data entry by hitting 'Cancel'", vbOKOnly, "No Sample Date")
Forms!Ecoli_Data.SetFocus
Forms!Ecoli_Data!Collected_By.SetFocus
GoTo endOfSub
End If
If Me.Dirty Then Me.Dirty = False
myDate = Me.DateCollected.Value
Dim yearAsString As String, monthAsString As String, dayAsString As String, clientInitial As String
Dim reportNumberText As String
reportNumberText = Me!SampleNumber.Value
Debug.Print "reportNumberText = " & reportNumberText
Debug.Print "CollectedBy Index: " & Me!Collected_By & " Employee Name: " & DLookup("CollectedBy", "Data_Lookup", Me.Collected_By)
Dim whereString As String
whereString = "SampleNumber=" & "'" & reportNumberText & "'"
Debug.Print whereString
On Error GoTo errorHandling
DoCmd.OpenReport "ECOLI_Laboratory_Report", acViewPreview, , whereString
DoCmd.PrintOut
DoCmd.Close acReport, "ECOLI_Laboratory_Report", acSaveNo
Dim eventsOpen As Integer
eventsOpen = DoEvents()
Debug.Print "Number of Open Events = " & DoEvents()
Dim PauseTime, Start, Finish, TotalTime
PauseTime = 10 ' Set duration.
Start = Timer ' Set start time.
Do While Timer < Start + PauseTime
DoEvents ' Yield to other processes.
Loop
Finish = Timer ' Set end time.
TotalTime = Finish - Start ' Calculate total time.
myResponse = MsgBox("Processing Report Took " & TotalTime & " seconds.", vbOKOnly)
myResponse = MsgBox("Do you want to add more data?", vbYesNo, "What Next?")
If myResponse = vbYes Then
DoCmd.Close acForm, "ECOLI_Data", acSaveYes
Error Generated By Line Above and occurs whether response Y or N to MsgBox.
DoCmd.OpenForm "ECOLI_Data", acNormal, , , acFormAdd
DoCmd.GoToRecord , , acNewRec
Else
DoCmd.Close acForm, "ECOLI_Data", acSaveYes
End If
Exit Sub
errorHandling:
If Err.Number = 2501 Then
myResponse = MsgBox("Printing Job Cancelled", vbOkayOnly, "Report Not Printed")
ElseIf Err.Number = 0 Then
'Do nothing
Else
Debug.Print "Error Number: " & Err.Number & ": " & Err.Description
myResponse = MsgBox("An Error occurred: " & Err.Description, vbOKOnly, "Error #" & Err.Number)
End If
If Application.CurrentProject.AllForms("ECOLI_Data").IsLoaded Then DoCmd.Close acForm, "ECOLI_Data", acSaveNo
If Application.CurrentProject.AllReports("ECOLI_Laboratory_Report").IsLoaded Then DoCmd.Close acReport, "ECOLI_Laboratory_Report", acSaveNo
endOfSub:
End Sub
Any idea on what am I missing here? Thanks.
I can't replicate the problem, but the following might help:
I assume you run into troubles because you're closing and opening the form in the same operation. To avoid doing this, you can open up a second copy of the form, and close the form once the second copy is open. This avoids that issue.
To open a second copy of the form:
Public Myself As Form
Public Sub CopyMe()
Dim myCopy As New Form_CopyForm
myCopy.Visible = True
Set myCopy.Myself = myCopy
End Sub
(CopyForm is the form name)
To close a form that may or may not be a form created by this function
Public Sub CloseMe()
If Myself Is Nothing Then
DoCmd.Close acForm, Me.Name
Else
Set Myself = Nothing
End If
End Sub
More information on having multiple variants of the same form open can be found here, but my approach differs from the approach suggested here, and doesn't require a second object to hold references and manage copies.
This line of code
`DoCmd.Close acForm, "ECOLI_Data", acSaveYes`
doesn't save the record you are on, it just saves any changes to the form design.
You should probably use
If Me.Dirty Then Me.dirty = False
to force a save of the current record if any data has changed.

The IF....then statement in Access VBA

I am testing my understanding on the if then statement, I wrote a little thing down below but when I hit run, nothing happened. I was expecting a msgbox will appear asking me if I want to quit or not and giving me choices to choose. Did I miss anything please. Thanks
Sub testifthenelse(bQuit As Boolean)
Dim s As String
s = "Do you want to quit?"
If MsgBox(s, vbYesNo, "Quite?") = vbYes Then
bQuit = True
Else
bQuit = False
End If
End Sub
you must call it from another sub:
Sub main()
Dim bQuit As Boolean
testifthenelse bQuit
End Sub
while, if you want to run and test it "by itself" then make the argument optional
Sub testifthenelse(Optional bQuit As Variant)
Dim s As String
s = "Do you want to quit?"
If MsgBox(s, vbYesNo, "Quite?") = vbYes Then
bQuit = True
Else
bQuit = False
End If
End Sub

Microsoft Access runtime error DoCmd.GoToRecord , , acNext

I have been trying to get a set of buttons beneath a form for the simplicity for the users. Only the issue i get with the scripting is that i am not able to get the next record button to work. Here I get a Runtime Error 2105.
What it is suppose to do is show only the next existing record, but instead is gives a runtime error and skips all the other records and goes to the last one.
Any ideas of what i am doing wrong?
If Me.ActiveXBestEl92.Enabled = False Then
Me.ActiveXBestEl92.Enabled = True
End If
With Recordset
If .AbsolutePosition = .RecordCount Then
Me.ActiveXBestEl93.Enabled = False
Else
DoCmd.GoToRecord , , acNext
End If
End With
Exit_Next_Record:
Me.ActiveXBestEl93.Enabled = False
Exit Sub
Err_Next_Record:
MsgBox Err.Description
Resume Exit_Next_Record
Thanks in advance
Try this:
With Me.RecordsetClone
If .AbsolutePosition = .RecordCount Then
Me!ActiveXBestEl93.Enabled = False
Else
.MoveNext
End If
End With
or this:
With Me.RecordsetClone
If Me.CurrentRecord = .RecordCount Then
Me!ActiveXBestEl93.Enabled = False
Else
.MoveNext
End If
End With

Access VBA - All checkboxes on form have been checked

I am relatively new to Access VBA and have a form that has around 30 checkboxes on it. When saving the form I want to ensure that all checkboxes have been ticked (set to true). The tickboxes have all got names SC1, SC2....SCN Is there a way to loop through each control and see if it has been set to true?
This is what I have tried but it doesnt seem to read the tickbox -
Private Sub Validate_Data(rstTop)
Dim n As Integer
Dim count As Integer
count = 0
For n = 1 To rstTop
If Form.Controls("SC" & n).Value = False Then
count = count + 1
End If
Next
If count <> 0 Then
MsgBox "Not all Questions have been ticked, please tick and add comments", vbInformation, _
"More information Required"
Else
End If
End Sub
Give this a try, it worked for me.
Option Compare Database
Option Explicit
Private Function Validate_Data() As Boolean
Dim ctl As Control
Validate_Data = True 'initialize
For Each ctl In Me.Form.Controls
If ctl.ControlType = acCheckBox Then
If (ctl.Name Like "SC*") And (ctl.Value = False) Then
MsgBox "Not all Questions have been ticked, please tick and add comments", vbInformation, _
"More information Required"
Validate_Data = False 'something isnt checked
Exit Function
End If
End If
Next ctl
End Function
Private Sub cmdGo_Click()
Validate_Data
End Sub

Creating a Calendar in Access 2010

I have been desperately trying to find a way to make a calendar in Access. I know it can be done, as I've seen wonderful examples, but I don't know how. (Also, my VB knowledge is minimal.)
Basically, I want the calendar to show a range of dates of when a program (we call them capsules) has been checked out, and when it will be returned.
DateReserve - the Date a capsule has been reserved
DateReturn - the Date when the capsule needs to be returned.
For example, if Capsule A is reserved on 6/1/2014 and will return 6/14/2014, I want the calendar to visually show that Capsule A will be unavailable during this time period. That way, we don't accidentally double-book a capsule.
Through one of my many google searches, I did find VB code that pulls up a very nice looking calendar. I just can't get the code right to visually show what dates a capsule will be unavailable.
Below is one of the sections of code I can't get to work right:
Private Sub OpenContinuousForm(ctlName As String)
Dim ctlValue As Integer
Dim DaysOfMonth As Long
Dim DateReturn As Date
Dim DateShipOut As Date
Dim DateRangeForProgram As String
DateRangeForProgram = (DateDiff("n", [DateReturn], [DateShipOut]))
On Error GoTo ErrorHandler
ctlValue = Me.Controls(ctlName).Tag
DaysOfMonth = MyArray(ctlValue - 1, 0)
DoCmd.OpenForm "frmCapsulesSchedule", acNormal, , [DateRangeForProgram] = DaysOfMonth
ExitSub:
Exit Sub
ErrorHandler:
MsgBox "DATE SHIP OUT FAILED.", , "Error!!!"
Resume ExitSub
End Sub
Please let me know if you need further information from me.
Here is the code I used for the calendar; Anywhere you see 'Teachers,' 'Schools,' or 'Capsules' would be where you'd put your own information:
Option Compare Database
Option Explicit
Private intYear As Integer
Private intMonth As Integer
Private lngFirstDayOfMonth As Long
Private intLastDayOfLastMonth As Integer
Private intFirstWeekday As Integer
Private intDaysInMonth As Integer
Private strFormReference As String
Private MyArray() As Variant
Private Sub cboMonth_Click()
On Error GoTo Errorhandler
Call Main
ExitSub:
Exit Sub
Errorhandler:
MsgBox "There has been an error. Please reload the form.", , "Error"
Resume ExitSub
End Sub
Private Sub cboYear_AfterUpdate()
On Error GoTo Errorhandler
Call Main
ExitSub:
Exit Sub
Errorhandler:
MsgBox "There has been an error. Please reload the form.", , "Error"
Resume ExitSub
End Sub
Private Sub Form_Load()
On Error GoTo Errorhandler
'Set the month and date to this current month and date
With Me
.cboMonth = Month(Date)
.cboYear = Year(Date)
End With
Call Main
ExitSub:
Exit Sub
Errorhandler:
MsgBox "There has been an error. Please reload the form.", , "Error"
Resume ExitSub
End Sub
Public Sub InitVariables()
On Error GoTo Errorhandler
intYear = Me.cboYear
intMonth = Me.cboMonth
lngFirstDayOfMonth = CLng(DateSerial(intYear, intMonth, 1))
intFirstWeekday = getFirstWeekday(lngFirstDayOfMonth)
intDaysInMonth = getDaysInMonth(lngFirstDayOfMonth)
'This is where you add the reference for the form
'It is used in case we wish to add the module to a subform
ExitSub:
Exit Sub
Errorhandler:
MsgBox "There has been an error. Please reload the form.", , "Error"
Resume ExitSub
End Sub
Public Sub Main()
On Error GoTo Errorhandler
Call InitVariables
Call InitArray
Call LoadArray
Call PrintArray
ExitSub:
Exit Sub
Errorhandler:
MsgBox "There has been an error. Please reload the form.", , "Error"
Resume ExitSub
End Sub
Public Sub InitArray()
'First column will add all dates of the array
'Second column will add visible property
'Third column will hold the string variable
Dim i As Integer
On Error GoTo Errorhandler
ReDim MyArray(0 To 41, 0 To 3)
For i = 0 To 41
MyArray(i, 0) = lngFirstDayOfMonth + 1 - intFirstWeekday + i
If Month(MyArray(i, 0)) = intMonth Then
MyArray(i, 1) = True
'This works out the days of the month
MyArray(i, 2) = i + 2 - intFirstWeekday & vbNewLine
Else
MyArray(i, 1) = False
End If
Next i
ExitSub:
Exit Sub
Errorhandler:
MsgBox "There has been an error. Please reload the form.", , "Error"
Resume ExitSub
End Sub
Public Sub LoadArray()
'This sub loads an array with the relevant variables from a query
Dim db As Database
Dim rs As Recordset
Dim rsFiltered As Recordset
Dim strQuery As String
Dim i As Integer
On Error GoTo ErrorHandler1
strQuery = "Select * FROM [qryDatesYearsCapsules2]"
Set db = CurrentDb
Set rs = db.OpenRecordset(strQuery)
With rs
If Not rs.BOF And Not rs.EOF Then
'Ensures the recordset contains records
On Error GoTo ErrorHandler2
For i = 0 To UBound(MyArray)
'Will loop through the array and use dates to filter down the query
'It firsts checks that the second column has true for its visible property
If MyArray(i, 1) = True Then
.Filter = "[NewDate]=" & MyArray(i, 0)
'To filter you must open a secondary recordset and
'Use that as the basis for a query
'This makes sense as you are building a query on a query
Set rsFiltered = .OpenRecordset
If Not rsFiltered.BOF And Not rsFiltered.EOF Then
'If the recordset is not empty then you are able
'to extract the text from the values provided
Do While Not rsFiltered.EOF = True
MyArray(i, 2) = MyArray(i, 2) & rsFiltered!CapsuleSet
' MyArray(i, 2) = MyArray(i, 2) & vbNewLine & rsFiltered!Teacher
MyArray(i, 2) = MyArray(i, 2) & vbNewLine & rsFiltered!School
' MyArray(i, 2) = MyArray(i, 2) & " - " & rsFiltered!NewDate
MyArray(i, 2) = MyArray(i, 2) & vbNewLine & vbNewLine
rsFiltered.MoveNext
Loop
End If
End If
Next i
End If
.Close
End With
ExitSub:
Set db = Nothing
Set rs = Nothing
Exit Sub
ErrorHandler1:
MsgBox "There has been an error. Please reload the form.", , "Error"
Resume ExitSub
ErrorHandler2:
MsgBox "There has been an error. Please reload the form.", , "Error"
Resume ExitSub
End Sub
Public Sub PrintArray()
Dim strTextBox As String
Dim i As Integer
On Error GoTo Errorhandler
For i = 0 To 41
strTextBox = "txt" & CStr(i + 1)
With Me
Controls(strTextBox) = ""
Controls(strTextBox).tag = i + 1
Controls(strTextBox) = MyArray(i, 2)
'Debug.Print strTextBox
'MyArray(i, 2)
End With
Next i
ExitSub:
Exit Sub
Errorhandler:
MsgBox "There has been an error. Please reload the form.", , "Error"
Resume ExitSub
End Sub
Private Sub OpenContinuousForm(ctlName As String)
Dim ctlValue As Integer
Dim DayOfMonth As Long
On Error GoTo Errorhandler
ctlValue = Me.Controls(ctlName).tag
DayOfMonth = MyArray(ctlValue - 1, 0)
DoCmd.OpenForm "frmClassDataEntry", acNormal, , "[NewDate]=" & DayOfMonth, , acDialog
ExitSub:
Exit Sub
Errorhandler:
MsgBox "There has been an error. Please reload the form.", , "Error"
Resume ExitSub
End Sub
Private Sub txt1_Click()
On Error GoTo Errorhandler
If Me.ActiveControl.Text <> "" Then
Call OpenContinuousForm(Me.ActiveControl.Name)
End If
ExitSub:
Exit Sub
Errorhandler:
MsgBox "There has been an error. Please reload form."
Resume ExitSub
End Sub
'Repeat the code for txt1_Click() all the ways to txt42_Click()
Private Sub Format()
Dim ctl As Control
Dim lngBackColor As Long
For Each ctl In Me.Detail.Controls
If DCount("*", "lstCapsules", "[Capsule]='" & ctl.Value & "'") = 0 Then
lngBackColor = 16777215
Else
lngBackColor = DLookup("Background", "lstCapsules", "[Capsule]='" & ctl.Value & "'")
End If
ctl.BackColor = lngBackColor
Next ctl
Set ctl = Nothing
End Sub
I also have a module called modFunctions:
Option Compare Database
Option Explicit
Public Function getFirstWeekday(lngFirstDayOfMonth As Long) As Integer
On Error GoTo Errorhandler
getFirstWeekday = -1
getFirstWeekday = Weekday(lngFirstDayOfMonth, vbMonday)
ExitFunction:
Exit Function
Errorhandler:
getFirstWeekday = 0
MsgBox "There has been an error. Please reload the form.", , "Error"
Resume ExitFunction
End Function
Public Function getDaysInMonth(lngFirstDayOfMonth As Long) As Integer
On Error GoTo Errorhandler
getDaysInMonth = -1
getDaysInMonth = DateDiff("d", lngFirstDayOfMonth, DateAdd("m", 1, lngFirstDayOfMonth))
ExitFunction:
Exit Function
Errorhandler:
getDaysInMonth = 0
MsgBox "Something is wrong with the DATES!.", , "Date Error"
Resume ExitFunction
End Function
There is a very useful youtube video I came across by Access All In One. Here is a link to the database used in the example
Your syntax in the Where condition of the openform command is incorrect.
It should be "[DateRangeForProgram]=" & DaysOfMonth, if the field your using to filter the form's recordsource is [DateRangeForProgram].
Also, if you're trying to open the form to multiple days, you should likely be using the Between operator. The datediff function's first argument specifies an interval, and your interval is minutes.
You should post the rest of the code so the entire scenario is clear.