Streamlining Form Module Code in Standalone Class Module.
Reminder Popup Form.
Understanding the significance of reminders is paramount. When it comes to important occasions such as a family member's or a friend's birthday, adequate preparation time is crucial. Being notified at least two days beforehand, we don't overlook these events amidst our busy schedules and other pressing commitments.
When considering business-related activities, let's examine the Inventory System's advance notification of the Pharmacy's re-order status as an example. It's imperative to print a list of medicines that fall below the minimum stock level or reach reorder levels on the 25th of each month to facilitate stock replenishment by placing orders in advance.
Seasonal demand requires higher stock levels of certain medicines during winter. By reviewing usage patterns from previous years, we can identify high-demand medicines and place advance orders with suppliers to ensure adequate availability before the season begins.
Tasks that require advanced alerts or scheduled notifications can be programmed to trigger a pop-up form or report with the relevant information, ensuring timely attention and prompt action. The Birthday Experiment.
Here, we will demonstrate this feature using the Employees table, which has been extended with two additional fields: BirthDate and BFlag. The BirthDate field contains the assumed date of birth for each employee. For calculation purposes, the day and month of birth are combined with the current year (e.g., 14-March-1961 becomes 14-March-2024) to determine the birthdate. The logical field BFlag is updated to True once the birthday greeting has been printed from the alert pop-up form.
The Alerts are programmed to run in three stages:
- A pop-up form appears 48 hours before the individual's birthday and recurs again on the eve of the celebration.
The pop-up form will display on the birthday when the database is accessed. A straightforward birthday greeting card in PDF format is generated directly from the pop-up. Upon completing the card printing process, the Employees Table field BFlag is marked to True, ensuring that the pop-up won't reappear during subsequent database openings.
- If the Birthday Greetings are not printed and the BFlag Field is not set to True, then the alert pop-up will appear for the next two days after the due date, indicating overdue case(s).
Initially, we establish an input Query named Birthday_RemData that includes a new column to record each employee's birthdate for the Current Year, sourced from the actual BirthDate field in the Employees1 table. The Birthday_RemData Query is the foundational dataset for categorizing data into the above three categories for pop-up forms.
The Employees1 Table Image.
The Employees1 Table image is shown below, with the required Fields for ready reference.
Reminder: Data Filtering Queries.
The SQL of the Input Query, with the current year Date of Birth, is calculated for each Employee, from the actual Date of Birth in the Table given below:
Query Name: BirthDay_RemData (Birthday Reminder Input Data).
SELECT Employees1.EmployeeID,
[FirstName] & " " & [LastName] AS Name,
Employees1.BirthDate,
Employees1.BFlag,
DateDiff("yyyy",[birthdate],Date()) AS Age,
DateValue(Format([BirthDate],"dd/mm") & "-" & CStr(Year(Date()))) AS DueDate
FROM Employees1;
1. Query: RemindQ1_OnDate - to filter data for the Popup on the actual BirthDay:
SELECT BirthDay_RemData.* FROM BirthDay_RemData WHERE (((BirthDay_RemData.DueDate)=Date()) AND ((BirthDay_RemData.BFlag)=False));
2. Query: RemindQ2_Advance - to filter data for the Popup that appears two days before the BirthDay:
SELECT BirthDay_RemData.* FROM BirthDay_RemData WHERE (((BirthDay_RemData.BFlag)=False) AND (([DueDate]-1)=Date())) OR (((BirthDay_RemData.BFlag)=False) AND (([DueDate]-2)=Date()));
3. Query: RemindQ3_OverDue - to filter data for the Popup that appears two days after the BirthDay, if the birthday card is not printed on the Birthday.:
SELECT BirthDay_RemData.* FROM BirthDay_RemData WHERE (((BirthDay_RemData.BFlag)=False) AND (([DueDate]+1)=Date())) OR (((BirthDay_RemData.BFlag)=False) AND (([DueDate]+2)=Date()));
The RemindQ1_OnDate Query is the source Data of the Reminder1 Popup Form. The Reminder2 and Reminder3 Forms are linked to the RemindQ2_Advance and RemindQ3_Overdue Queries, respectively. All three are Tabular Forms.
Reminder: POPUP Forms.
1. The Reminder1 Popup Form Image is given below for reference.
The employee records with birthdays matching today’s date will be displayed on the Form, showing their actual date of birth and the birthday for the current year in separate columns. You can print the greeting card by clicking the “Print PDF Greeting” Command Button. The default path of the greeting’s target location can be temporarily altered directly in the text box. You can make the change permanent in the Default Value Property of the text box in the design view.
The Advance and Overdue Reminder Popups may show differently in Day/Month in both columns. The Printing option is not available in the Advanced and Overdue Popup Forms Footer Section.
The Greetings PDF file will be saved to the path indicated in the TextBox in the Footer Section of the Form. The path displayed in the TextBox is set in the TextBox Default Value Property, which you can modify to save it to your preferred path.
The Sample Greetings Card.
The sample Greetings Card image is given below for reference.
The other two Popup Form Images are given below for information.
2. Alert about upcoming Birthdays:
3. Alerts about the missed Birthday Celebrations:
How do the Popup Form(s) open automatically if the Employee's Date of Birth meets any of the criteria specified above?
It is easy; when the database is open, it checks for records in the three Queries (i.e., RemindQ1_OnDate, RemindQ2_Advance, and RemindQ3_OverDue) and opens the Alert Form linked to the Queries. For this purpose, a small Function is created in the Standard Module.
The VBA Code of the Checkpopup() Function.
Public Function Checkpopup()
'========================================================
'Project: Reminder Popup Form
'Author : a.p.r. pillai
'Date : March, 2024
'Rights : All Rights(c) Reserved by www.msaccesstips.com
'Remarks: Opens up preset Reminder Popup Form(s)
' : on pre-scheuled Date/Month
'Example: Employees' Date-of-Birth Reminder.
'========================================================
Dim i, j, k As Integer
i = DCount("*", "RemindQ1_OnDate")
If i > 0 Then
DoCmd.OpenForm "Reminder1", acNormal
End If
j = DCount("*", "RemindQ2_Advance")
If j > 0 Then
DoCmd.OpenForm "Reminder2", acNormal
End If
k = DCount("*", "RemindQ3_OverDue")
If k > 0 Then
DoCmd.OpenForm "Reminder3", acNormal
End If
End Function
Running the Popup Forms.
Now all we need to do is call this Function immediately after opening the Database. The first choice to create a Macro named AutoExec (the Auto Execute Macro) and call the Function using the RunCode Command. The name of the Macro must be AutoExec to run immediately when the Database is open. Another option is to drag this Macro, place it on the Desktop as a Shortcut. Double-click on it to open the Database and run the Macro.
Another option is to run the Function from the Form_Load() Event Subroutine of the first Form that opens when the database is open.
If there is no urgency, call the Function when the Employees Form is open; then PopUp Form(s) will appear if any of the three data-filtering Queries, or all of them, have data after a brief 3-second delay.
This is good for experimenting with this trick and learning to devise a better method for Advanced Alerts, on-the-day or Overdue Alerts in your other Projects.
The Employee Form-based Popup.
There are three employee Forms for each Reminder category. All of them can be opened from a small Main Form. The Image of the Main Form is given below.
The Employees Form Image of the First Option:
When you open this Form, there is a delay of about 3 seconds; the Reminder1_OnDate Popup Form will open with the Employees' Records having their BirthDate today. If there are no records, the [Open Reminder] Command Button is disabled. If the pop-up doesn't appear, change the BirthDate of one or two employees to match the Day and Month (don't change the year) to match the current Date.
If you close the Reminder Form by mistake, use the CommandButton that opens the Reminder Form.
There are two other Forms for experimenting with Reminders of forthcoming or overdue Reminder setups.
Streamlining VBA Event Subroutine Codes.
Now coming to the Streamlined VBA Coding Part, there are three Employee Forms with two CommandButtons. The Employee information is for display purposes only. If you plan to edit the employee's Birthdate through this Form, you are welcome, but the validation check is not performed, and full responsibility is yours. All three Forms are linked to the same Employees1 Table.
Since all three forms have two command buttons each, we need only one CommandButton Wrapper Class to handle the Events of Command Button Clicks. But we will use three different Class_Init() Interface Classes (Intermediary Class) to create separate Instances for all three Employee Forms, so that their Identity References will remain separately in memory. The 3-second TimerInterval running Subroutine is also run from within this Class Module and then opens the Popup Form.
The Command Button Wrapper Class: Rm1_cmdButton - Employee Forms.
Option Compare Database
Option Explicit
Private WithEvents cmd As Access.CommandButton
Private mfrm As Form
Dim t As Integer
'========================================================
'Project: Reminder Popup Form
'Author : a.p.r. pillai
'Date : March, 2024
'Rights : All Rights(c) Reserved by www.msaccesstips.com
'Remarks: Opens up preset Reminder Popup Form(s)
' : on pre-scheuled Date/Month
'Example: Employees' Date-of-Birth Reminder.
'========================================================
Public Property Get m_Frm() As Access.Form
Set m_Frm = mfrm
End Property
Public Property Set m_Frm(ByRef vfrm As Access.Form)
Set mfrm = vfrm
End Property
Public Property Get m_cmd() As Access.CommandButton
Set m_cmd = cmd
End Property
Public Property Set m_cmd(ByRef vcmd As Access.CommandButton)
Set cmd = vcmd
End Property
Private Sub cmd_Click()
Select Case cmd.Name
Case "cmdReminder1"
DoCmd.OpenForm "Reminder1", acNormal
Case "cmdReminder2"
DoCmd.OpenForm "Reminder2", acNormal
Case "cmdReminder3"
DoCmd.OpenForm "Reminder3", acNormal
Case "cmdExit1"
DoCmd.Close acForm, "Employees1"
Case "cmdExit2"
DoCmd.Close acForm, "Employees2"
Case "cmdExit3"
DoCmd.Close acForm, "Employees3"
End Select
End Sub
We need only one Click-Event Subroutine in the Class Module to handle the Command Button Clicks from all three Forms. The Code is not messy and remains clean and directly accessible, rather than through the Form Design View. The Event Procedure Code is self-explanatory.
Three different Interface Class Modules for different Employee Forms. We don't create Instances of the Interface Class. Hence, we need to create three different Interface Classes. Moreover, it runs the TimerInterval Subroutine for three different Forms.
Interface Class of Employees1 Form: Rm1_Init Class VBA Code.
Option Compare Database
Option Explicit
Private cmd As Rm1_CmdButton
Private WithEvents frm As Form
Private Coll As New Collection
Dim t As Integer
'========================================================
'Project: Reminder Popup Form
'Author : a.p.r. pillai
'Date : March, 2024
'Rights : All Rights(c) Reserved by www.msaccesstips.com
'Remarks: Opens up preset Reminder Popup Form(s)
' : on pre-scheuled Date/Month
'Example: Employees' Date-of-Birth Reminder.
'========================================================
Public Property Get m_Frm() As Form
Set m_Frm = frm
End Property
Public Property Set m_Frm(ByRef vfrm As Form)
Set frm = vfrm
Call Class_Init
End Property
Private Sub Class_Init()
Dim ctl As Control
Const EP = "[Event Procedure]"
frm.OnTimer = EP
For Each ctl In frm.Controls
Select Case TypeName(ctl)
Case "CommandButton"
Select Case ctl.Name
Case "cmdReminder1", "cmdExit1"
Set cmd = New Rm1_CmdButton
Set cmd.m_Frm = frm
Set cmd.m_cmd = ctl
cmd.m_cmd.OnClick = EP
Coll.Add cmd
Set cmd = Nothing
End Select
End Select
Next
t = 0
frm.TimerInterval = 1000
End Sub
Private Sub frm_Timer()
Dim icount As Long
On Error GoTo frmTimer_Err
t = t + 1
If t = 3 Then
frm.TimerInterval = 0
icount = DCount("*", "RemindQ1_OnDate")
If icount > 0 Then
t = 0
frm.cmdReminder1.Enabled = True
Call PopupOpen("Reminder1")
Else
frm.cmdReminder1.Enabled = False
frm.Requery
End If
End If
frmTimer_Exit:
Exit Sub
frmTimer_Err:
MsgBox Err.Description, , "frmTimer()"
Resume frmTimer_Exit
End Sub
Private Sub Class_Terminate()
Do While Coll.Count > 0
Coll.Remove 1
Loop
End Sub
This class module is declared within the Employee1 Form Module, where a reference to the Employee1 form is passed to the `frm` object. The `Class_Initialize` procedure is then invoked. At the beginning of this procedure, the Employee1 Form's Timer event is enabled, followed by the creation of Command Button instances and the initialization of their event handling procedures.
The Timer Interval is set to 1000 milliseconds (1 second), and the Timer event runs for three consecutive intervals (3 seconds). After this 3-second delay, the record count of the `ReminderQ1_OnDate` query is retrieved. If the record count is greater than 0, the `Reminder1_OnDate` popup form is opened to display the corresponding reminder records.
Interface Class of Employees2 Form: Rm2_Init Class.
Option Compare Database
Option Explicit
Private cmd As Rm1_CmdButton
Private WithEvents frm As Form
Private Coll As New Collection
Dim t As Integer
'========================================================
'Project: Reminder Popup Form
'Author : a.p.r. pillai
'Date : March, 2024
'Rights : All Rights(c) Reserved by www.msaccesstips.com
'Remarks: Opens up preset Reminder Popup Form(s)
' : on pre-scheuled Date/Month
'Example: Employees' Date-of-Birth Reminder.
'========================================================
Public Property Get m_Frm() As Form
Set m_Frm = frm
End Property
Public Property Set m_Frm(ByRef vfrm As Form)
Set frm = vfrm
Call Class_Init
End Property
Private Sub Class_Init()
Dim ctl As Control
Const EP = "[Event Procedure]"
frm.OnTimer = EP
For Each ctl In frm.Controls
Select Case TypeName(ctl)
Case "CommandButton"
Select Case ctl.Name
Case "cmdReminder2", "cmdExit2"
Set cmd = New Rm1_CmdButton
Set cmd.m_Frm = frm
Set cmd.m_cmd = ctl
cmd.m_cmd.OnClick = EP
Coll.Add cmd
Set cmd = Nothing
End Select
End Select
Next
t = 0
frm.TimerInterval = 1000
End Sub
Private Sub frm_Timer()
Dim icount As Long
On Error GoTo frmTimer_Err
t = t + 1
If t = 3 Then
frm.TimerInterval = 0
icount = DCount("*", "RemindQ2_Advance")
If icount > 0 Then
t = 0
frm.cmdReminder2.Enabled = True
frm.Requery
Call PopupOpen("Reminder2")
Else
frm.cmdReminder2.Enabled = False
frm.Requery
End If
End If
frmTimer_Exit:
Exit Sub
frmTimer_Err:
MsgBox Err.Description, , "frmTimer()"
Resume frmTimer_Exit
End Sub
Private Sub Class_Terminate()
Do While Coll.Count > 0
Coll.Remove 1
Loop
End Sub
The only difference in this Module is the query name and CommandButton Names. We use the same Rm1_CmdButton Wrapper Class.
Rm3_Init Interface Class also has the same VBA Code with different Query and Command Button Names.
Option Compare Database
Option Explicit
Private cmd As Rm1_CmdButton
Private WithEvents frm As Form
Private Coll As New Collection
Dim t As Integer
'========================================================
'Project: Reminder Popup Form
'Author : a.p.r. pillai
'Date : March, 2024
'Rights : All Rights(c) Reserved by www.msaccesstips.com
'Remarks: Opens up preset Reminder Popup Form(s)
' : on pre-scheuled Date/Month
'Example: Employees' Date-of-Birth Reminder.
'========================================================
Public Property Get m_Frm() As Form
Set m_Frm = frm
End Property
Public Property Set m_Frm(ByRef vfrm As Form)
Set frm = vfrm
Call Class_Init
End Property
Private Sub Class_Init()
Dim ctl As Control
Const EP = "[Event Procedure]"
'frm.OnTimer = EP
For Each ctl In frm.Controls
Select Case TypeName(ctl)
Case "CommandButton"
Select Case ctl.Name
Case "cmdReminder3", "cmdExit3"
Set cmd = New Rm1_CmdButton
Set cmd.m_Frm = frm
cmd.m_Frm.OnTimer = EP
Set cmd.m_cmd = ctl
cmd.m_cmd.OnClick = EP
Coll.Add cmd
Set cmd = Nothing
End Select
End Select
Next
t = 0
frm.TimerInterval = 1000
End Sub
Private Sub frm_Timer()
Dim icount As Long
'On Error GoTo frmTimer_Err
t = t + 1
If t = 3 Then
frm.TimerInterval = 0
icount = DCount("*", "RemindQ3_OverDue")
If icount > 0 Then
t = 0
frm.cmdReminder3.Enabled = True
frm.Requery
Call PopupOpen("Reminder3")
Else
frm.cmdReminder3.Enabled = False
frm.Requery
End If
End If
frmTimer_Exit:
Exit Sub
frmTimer_Err:
MsgBox Err.Description, , "frmTimer()"
Resume frmTimer_Exit
End Sub
Private Sub Class_Terminate()
Do While Coll.Count > 0
Coll.Remove 1
Loop
End Sub
The Popup Forms' Wrapper Class and Interface Class Module VBA Code.
Only one Wrapper Class Module and one Interface Class are required for all three Popup Forms to handle the Event Procedures of Command Buttons. All three Forms have only Command Button click events handled in the Wrapper Class Sub_CmdButton and Interface Class Module.
The Sub_CmdButton Wrapper Class Module VBA Code.
Option Compare Database
Option Explicit
Private WithEvents cmd As Access.CommandButton
Private frm As Form
'========================================================
'Project: Reminder Popup Form
'Author : a.p.r. pillai
'Date : March, 2024
'Rights : All Rights(c) Reserved by www.msaccesstips.com
'Remarks: Opens up preset Reminder Popup Form(s)
' : on pre-scheuled Date/Month
'Example: Employees' Date-of-Birth Reminder.
'========================================================
Public Property Get m_Frm() As Access.Form
Set m_Frm = frm
End Property
Public Property Set m_Frm(ByRef vfrm As Access.Form)
Set frm = vfrm
End Property
Public Property Get m_cmd() As Access.CommandButton
Set m_cmd = cmd
End Property
Public Property Set m_cmd(ByRef vcmd As Access.CommandButton)
Set cmd = vcmd
End Property
Private Sub cmd_Click()
Select Case cmd.Name
Case "cmdPrint1"
Call GreetingsPrint
Case "cmdCancel1"
DoCmd.Close acForm, "Reminder1"
Case "cmdCancel2"
DoCmd.Close acForm, "Reminder2"
Case "cmdCancel3"
DoCmd.Close acForm, "Reminder3"
End Select
End Sub
Private Sub GreetingsPrint()
Dim strSQL As String
Dim db As DAO.Database
Dim rst As DAO.Recordset
Dim qryDef As DAO.QueryDef
Dim EID As Integer
Dim OutFile As String
'On Error GoTo GreetingsPrint_Err
Set db = CurrentDb
Set rst = db.OpenRecordset("RemindQ1_OnDate", dbOpenDynaset)
rst.MoveLast
rst.MoveFirst
Do While Not rst.EOF And Not rst.BOF
EID = rst![EmployeeID]
strSQL = "SELECT RemindQ1_OnDate.* FROM RemindQ1_OnDate "
strSQL = strSQL & "WHERE (((RemindQ1_OnDate.EmployeeID)= "
strSQL = strSQL & EID & "));"
Set qryDef = db.QueryDefs("BirthDayQ1OnDate_PDF")
qryDef.SQL = strSQL
db.QueryDefs.Refresh
DoCmd.OpenReport "Greetings1_PDF", acViewPreview
If MsgBox("Birthday Greetings Print Initiated, Proceed?", vbYesNo, "Greetings Print()") = vbNo Then
DoCmd.Close acReport, "Greetings1_PDF"
Exit Sub
End If
DoCmd.Close acReport, "Greetings1_PDF"
OutFile = frm!Path & DLookup("Name", "BirthdayQ1OnDate_PDF", "EmployeeID = " & EID) & ".pdf"
DoCmd.OutputTo acOutputReport, "Greetings1_PDF", "PDFFormat(*.pdf)", OutFile, False, "", 0, acExportQualityPrint
rst.MoveNext
Loop
rst.Close
Set rst = Nothing
Set db = Nothing
DoCmd.SetWarnings False
'Delete earlier saved records
DoCmd.OpenQuery "BirthDayReminder1_Del", acViewNormal
'Add latest records
DoCmd.OpenQuery "BDay_SavedQ1", acViewNormal
'Flag the Employee Record as Greetings Printed
'Reset the floags on January 1st, Next Year
DoCmd.OpenQuery "BirthDayQ_UpdateFlag1", acViewNormal
DoCmd.SetWarnings True
MsgBox "Greetings PDFs are saved in Path: " & frm!Path
GreetingsPrint_Exit:
Exit Sub
GreetingsPrint_Err:
MsgBox Err & ": " & Err.Description, , "GreetingsPrint_Click()"
Resume GreetingsPrint_Exit
End Sub
In the cmd_Click() Event Subroutine, the cmdPrint1 Command Button Click on the Reminder1 Form calls the GreetingsPrint() Subroutine, and prints the Birthday Greetings in PDF format. It updates the Employees1 Table, marking the BFlag logical Field as True to prevent it from appearing in the Employee record again in the Popup Form. The Greetings will be printed separately for each Employee Record.
After printing the Popup Form, the records will be saved into a separate temporary Table: Birthday_Reminder1.
The Sub_Init Interface Class Module VBA Code.
Option Compare Database
Option Explicit
Private cmd As Sub_CmdButton
Private frm As Form
Private Coll As New Collection
Public Property Get m_Frm() As Form
Set m_Frm = frm
End Property
Public Property Set m_Frm(ByRef vfrm As Form)
Set frm = vfrm
Call Class_Init
End Property
Private Sub Class_Init()
Dim ctl As Control
Const EP = "[Event Procedure]"
'Set frm2 = frm.BReminderSub1.Form
For Each ctl In frm.Controls
Select Case TypeName(ctl)
Case "CommandButton"
Select Case ctl.Name
Case "cmdPrint1", "cmdCancel1", _
"cmdCancel2", "cmdCancel3"
Set cmd = New Sub_CmdButton
Set cmd.m_Frm = frm
Set cmd.m_cmd = ctl
cmd.m_cmd.OnClick = EP
Coll.Add cmd
Set cmd = Nothing
End Select
End Select
Next
End Sub
Private Sub Class_Terminate()
Do While Coll.Count > 0
Coll.Remove 1
Loop
End Sub
All three Popup Forms: Reminder1, Reminder2, and Reminder3 have Command Buttons with unique Names to Close the Forms, and all of them are included in the Class_Init() Subroutine. Because of their unique names, we could handle their Event Procedures in a Single Wrapper Class Module.
Even though the Code requirement is simple, the Standalone Class Module VBA Coding gives you much flexibility for maintaining Code in a centralized location. It needs only one Click Event Subroutine for several CommandButton Click Events.
Demo Database Download
- Re-using Form Module VBA Coding for New Projects.
- Defining Custom Events in Microsoft Access Part Two
- Objects and Their Built-in Events Part 3.
- Standalone Class Module and Events - Part Four
- Several TextBoxes and Event Capturing Part Five
- Class Objects and Wrapper Classes - Part Six
- Form Module vs. Reusable Class Module Coding Demo - Part Seven
- Collection Object replaces Class Object Array - Part Eight
- Reusability of Streamlined VBA Code - Part Nine
- Organizing Wrapper Classes for Different Forms - Part Ten
- ComboBox and Option-Group Wrapper Classes - Part Eleven
- Report Module Code in Class Module - Part Twelve
- Hiding Report Lines Conditionally - Part 13.
- Form Report Detail Sections Event Handling - Part 14.
- New Custom-Made Form Wizard VBA - Part 15.
- New Custom-Made Report Wizard - Part 16.
- Streamlining VBA External Files List in Hyperlinks-17
- Streamlining Event Procedures 3D-Text Wizard-18
- Streamlining Form Module VBA RGBColor Wizard-19
- Form VBA Structured Coding Numbers to Words Converter-20
- Form VBA Structured Coding Access Users-Group Europe Presentation-21
- The Event Firing Mechanism in Access Objects-22
- One TextBox and Three Wrapper Class Instances-23
- Streamlining Code Synchronized Floating Popup Form-24
- Streamlining Code Compacting/Repair Database-25
- Streamlining Code Remainder Popup Form-26
- Streamlining Code Editing Data in Zoom-in Control-27
- Streamlining Code Filter By Character and Sort-28
- Table Query Records in Collection Object-29
- Class for All Data Entry Editing Forms-30
- Wrapper Class Module Creation Wizard-31
- wrapper-class-template-wizard-v2
















No comments:
Post a Comment
Comments subject to moderation before publishing.