global click event handler (WithEvents) - ms-access

I am trying to create a class module that will act as a global handler for when ever someone clicks one of the sixty textboxes I have in my form. Th textboxes represent a timecard for the week displaying information as clock in, clock out, lunch start,end,duration, total daily hours under each fo the seven days of the week. When someone clicks anyone of the boxes under a day all the boxes will unlock and enable so that the user can edit the information in them.
After scouring the web for a solutio of a global click event I found that I could create a class module that would handle the event without create a click event for every single text box that calls a seperate function to handle the event. The problem I am having is that my class module doesn't seem to be handling my event and was wondering if someone could suggest a solution to my problem. FYI, All my textboxes and locked and disabled to prevent data corruption. Below is my code:
''# Class module
Option Compare Database
Option Explicit
Public WithEvents TC_txtbox As TextBox
''# Set the textbox so that its events will be handled
Public Property Set TextBox(ByVal m_tcTxtBox As TextBox)
TC_txtbox = m_tcTxtBox
End Property
''# Handle and onClick event of the
Private Sub TC_txtbox_Click()
''# Find out the controls that where clikck
Debug.Print Form_TimeCard.ActiveControl.Name
Dim ctl As Control
For Each ctl In access.Forms.Controls
Debug.Print ctl.Name
Next ctl
End Sub
Form Code
Option Compare Database
Option Explicit
''# Global Variables
Public clk_inout As Boolean
Public settings
Public weekDict
Public weekOf As Variant
Public curDay As Variant
Public txtBxCollection As Collection
''# Event Handler for when the form opens
Private Sub Form_Open(Cancel As Integer)
''# Configure varaibles
Me.TimerInterval = 60000 ''# 10 sec Interval
weekOf = getFirstDayofWeek(Date)
curDay = Date
Set weekDict = CreateObject("Scripting.Dictionary")
Set settings = CreateObject("Scripting.Dictionary")
Set txtBxCollection = New Collection
''# Load Time Card Data
Call initSettings
''# Debug.Print "Work Day Goal " & settings.Item("Work_day_goal_hrs")
Call initDict
Call initTextBoxEventHandler
Debug.Print "Collection count " & txtBxCollection.Count
Call loadDates(Date)
Call clearDay
Call selectDay(Date)
Call loadWeeksData(weekOf)
Dim ctl As Control
Set ctl = weekDict.Item(Weekday(curDay)).Item("In")
If IsDate(ctl.Value) And (Not ctl.Value = "") Then
Me.but_clk_inout.Caption = "Clock Out"
Me.but_lunch.Visible = True
clk_inout = False
Else
Me.but_clk_inout.Caption = "Clock In"
Me.but_lunch.Visible = False
clk_inout = True
End If
''# Debug.Print "Work Day Goal " & settings.Item("Salary")
End Sub
Public Sub initTextBoxEventHandler()
Dim eventHandler As TextBoxEventHandler
Set eventHandler = New TextBoxEventHandler
Debug.Print "Collection count " & txtBxCollection.Count
Set eventHandler.TextBox = Me.txt_F_in
txtBxCollection.Add eventHandler
Debug.Print "Collection count " & txtBxCollection.Count
End Sub

Are you missing a Set? The public property set should be
Public Property Set TextBox(ByVal m_tcTxtBox As TextBox)
Set TC_txtbox = m_tcTxtBox ' dont forget the Set! '
End Property

I figure out My problem in the class module where I am setting the text box I forgot to add "TC_txtbox.OnClick = "[Event Procedure]"" VBA will not fire the custom even handler in my extended textbox if [Event Procedure] is not declared in the property of the event you would like to handle

Related

MS Access Change an 'OnChange' Event programmatically in VBA

I am working on a project where I have to use MS Access and I have to make the database as loose as possible (Its weird and I dont think best practice but for now given my resources it is what I have).
Anyways I have 50 combo boxes but often have to make changes to one which would mean I have to manually change all of them. Id rather spend hour finding a programming solution then 5 minutes manually doing this.
I need to change the 'OnChange' event using VBA but my code produces an error.
Private Function RunChangePropagate()
Dim combo As ComboBox
RevealGrid
For Each combo In Me.Controls
combo.OnChange = "=ComboBox_Change()"
Next combo
ClearGrid
End Function
Error:
I have also tried making the text to change it to a Variant and then assigning the event to said Variant.
How do I go about doing this?
Thanks in advance.
This is some minimal example, that works:
Public Sub ChangeEvent()
Dim ctrl As Control
For Each ctrl In Me.Controls
If ctrl.Name = "Combo5" Then
Debug.Print ctrl.OnChange
ctrl.OnChange = "SomeProcedure"
End If
Next ctrl
End Sub
In your example you should only remove the = in the assigning. The parenthesis at the end of the assigned sub are not required.
Use WithEvents. This way, you form is completely "detached" from the class controlling (some controls of) the form.
I published an article with links and an example for anyone to study:
Create Windows Phone Colour Palette and Selector using WithEvents
The main code (code behind module and class module) is only:
Option Explicit
' Helper class for form Palette for event handling of textboxes.
' 2017-04-19. Gustav Brock, Cactus Data ApS, CPH.
' Version 1.0.0
' License: MIT.
' *
Private Const EventProcedure As String = "[Event Procedure]"
Private WithEvents ClassTextBox As Access.TextBox
Public Sub Initialize(ByRef TextBox As Access.TextBox)
Set ClassTextBox = TextBox
ClassTextBox.OnClick = EventProcedure
End Sub
Public Sub Terminate()
Set ClassTextBox = Nothing
End Sub
Private Sub ClassTextBox_Click()
' Select full content.
ClassTextBox.SelStart = 0
ClassTextBox.SelLength = Len(ClassTextBox.Value)
' Display the clicked value.
ClassTextBox.Parent!CopyClicked.Value = ClassTextBox.Value
' Copy the clicked value to the clipboard.
DoCmd.RunCommand acCmdCopy
End Sub
and:
Option Explicit
' Form to display the Windows Phone 7.5/8.0 colour theme.
' Also works as a basic example of implementing WithEvents for a form.
' 2017-04-19. Gustav Brock, Cactus Data ApS, CPH.
' Version 1.0.0
' License: MIT.
' *
Private ControlCollection As Collection
Private Sub Form_Load()
' Load events for all colour value textboxes.
Dim EventProcedure As ClassTextboxSelect
Dim Control As Access.Control
Set ControlCollection = New Collection
For Each Control In Me.Controls
If Control.ControlType = acTextBox Then
Set EventProcedure = New ClassTextboxSelect
EventProcedure.Initialize Control
ControlCollection.Add EventProcedure, Control.Name
End If
Next
Set EventProcedure = Nothing
Set Control = Nothing
End Sub
Private Sub Form_Unload(Cancel As Integer)
' Unload events for all colour value textboxes.
Dim EventProcedure As ClassTextboxSelect
For Each EventProcedure In ControlCollection
EventProcedure.Terminate
Next
Set EventProcedure = Nothing
Set ControlCollection = Nothing
End Sub
Full code is also on GitHub: VBA.ModernTheme

How best to call a public sub routine declared in a form used as the source object a subform control from the main form?

I have a form MyForm1 with a module having the method.
Public Sub CreateSQL(ProductID as variant)
Me.Recordsource = " SELECT * FROM ProductOrders " _
" WHERE ProductID = " & Nz(ProductID ,0)
Me.Requery
End Sub
I use this as a subform to a form named MyMainForm.
When I change the value of a control on MyMainForm it successfully executes the following line:
Me.Subform1.Form.CreateSQL ProductID:=Me.cboProductID
My Questions:
Why are the members not listed on the intellisense list that appears after I type Me.Subform1.Form.?
Is there a way of getting them to be listed?
Is there a property that will let me access the "Form_MyForm1" class of the form referenced in the subform control "Source object property" (ie the Me.Subform1.form ) ?
It's like I need to be able to write:
Me.Subform1.Form_MyForm1.CreateSQL ProductID:=Me.cboProductID
Does such a property already exist? If so how do I access it? Is it in the properties collection?
PS: If you need more information please see the same questions posted in a long Stack overflow question here
Harvey
Don't know.
Not that I know of.
Make the subfunction Public.
But it looks like you could save yourself a lot of trouble by using the Master/Child link option of a form and its subform control.
Instead to the mainform calling the method Me.Subform1.Form.CreateSQL
You should create an object variable in the subform that points to the main form and responds to events eg:
Dim WithEvents cvMyParentForm As Form
Property Set MyParentForm(MyParentForm As Form)
Set cvMyParentForm = MyParentForm
End Property
Property Get MyParentForm() As Form
Set MyParentForm = cvMyParentForm
End Property
When the main form opens use the Form_Open event to "initialise" the subforms
Private Sub Form_Open(Cancel As Integer)
If Me.Subform1.Form.MyParentForm Is Nothing Then
Set Me.Subform1.Form.MyParentForm = Me
End If
End Sub
then you can get the subform to respond to the FORM events that are raised by the mainform.
If you need to have the subform respond to any events that you declare in the main form you will need to chnaeg the above code to use the Form_MyMainFormname type
Dim WithEvents cvMyParentForm As Form_MyMainFormName
Property Set MyParentForm(MyParentForm As Form_MyMainFormName)
Set cvMyParentForm = MyParentForm
End Property
Property Get MyParentForm() As Form_MyMainFormName
Set MyParentForm = cvMyParentForm
End Property
Private Sub cvMyParentForm_Current()
'MsgBox "Sub form current event - does syncing"
Me.Form.Recordset.FindFirst "ID = " & Nz(cvMyParentForm.ID, 0)
If Me.Form.Recordset.NoMatch Then
MsgBox "Humph"
Else
End If
End Sub
Private Sub cvMyParentForm_MyEvent()
MsgBox "A user define event 'MyEvent' was fired on the main form"
End Sub

Refer to Form Control Without Specific Naming

I have a form with numerous images, each of which performs a series of actions when clicked. I can create a Private Sub with all of the actions for each button, however I think this is inefficient. Rather, I'd like to record all the actions in one Macro and then call this Macro when each image is clicked. To do so, I'd need the single Macro to refer to the current image selected and not refer to any image by name. Is this possible?
My current code includes the following:
Me.Image001.BorderColor = RGB(1, 1, 1)
Me.Image001.BorderWidth = 2
Me.Image001.BorderStyle = 1
I'd need to amend this so that it amends the border colour/width/style etc of whichever image is selected, and not a specific named image ('Image001').
Thanks!
You should use event sinking.
With event sinking you could bind to an event your own procedures.
You can see an example here http://p2p.wrox.com/access-vba/37472-event-triggered-when-any-control-changed.html
In simple words you create a module where you bind the event to your specific implementation . Then on the form you are interested you create a collection where you register the controls you want to "follow" the event sinking...
My sub sinking for checkboxes (i have alot)
1st a class module name SpecialEventHandler
Option Compare Database
Private WithEvents chkbx As CheckBox
Private m_Form As Form
Private Const mstrEventProcedure = "[Event Procedure]"
Public Function init(chkbox As CheckBox, frm As Form)
Set chkbx = chkbox
Set m_Form = frm
'Debug.Print frm.Name
chkbx.AfterUpdate = mstrEventProcedure
End Function
Private Sub chkbx_AfterUpdate()
'your Code here
End Sub
Private Sub Class_Terminate()
Set chkbx = Nothing
Set m_Form = Nothing
End Sub
Then on the form you want to use event sinking
Option Compare Database
Dim spEventHandler As SpecialEventHandler
Private colcheckBoxes As New Collection
Private Sub Form_Open(Cancel As Integer)
Dim ctl As Control
For Each ctl In Me.Detail.Controls
Select Case ctl.ControlType
Case acCheckBox
Set spEventHandler = New SpecialEventHandler
spEventHandler.init Controls(ctl.NAME), Me
colcheckBoxes.Add spEventHandler
End Select
Next ctl
End Sub
You could always create a Standard Sub, then call it on the click of the button. Something like
Public Sub changeColor(frm As Form, ctrl As Control)
frm.Controls(ctrl.Name).BorderColor = RGB(1, 1, 1)
frm.Controls(ctrl.Name).BorderWidth = 2
frm.Controls(ctrl.Name).BorderStyle = 1
End Sub
So when you click an image all you have to do is,
Private Sub Image001_Click()
changeColor Me, Image001
End Sub

New to classes VBA Access

I have been working on a project and have multiple tick boxes (25) and multiple labels in a form that are names SC1, SC2...SCN and Lbl1, Lbl2...LblN depending on a recordset. When I click the tickbox I want the label beside it to display some information, see below -
Private Sub SC1_Click()
If (Me!SC1) = True Then
Form.Controls("Lbl1").Caption = ("Completed by " & (Environ$("Username")))
Form.Controls("Lbl1").ForeColor = vbGreen
Else
Form.Controls("Lbl1").Caption = ("Please tick if Complete")
Form.Controls("Lbl1").ForeColor = vbBlack
End If
End Sub
My issue is I can't change the number in the Sub name so I would have to create multiple sub procedures. I think if I created a class for the tick box this would change but I am not sure how I can set up the class. I have tried the below class template but am not sure where I can change the property values in order to reach my goal. I am not sure why you would have both get and set properties in one class. Any help on this is greatly appreciated.
Option Compare Database
Option Explicit
Private pName As String
Private pCaption As String
Private pVisiblity As Boolean
Private pValue As Boolean
Public Property Get Name() As String
Name = pName
End Property
Public Property Let Name(Value As String)
pName = Value
End Property
Public Property Get Caption() As String
Caption = pCaption
End Property
Public Property Let Caption(Value As String)
pCaption = "Please Tick Box if complete"
End Property
Public Property Get Visibility() As Boolean
Visibility = pVisibility
End Property
Public Property Let Visibility(Value As Boolean)
pVisibility = True
End Property
Public Property Get Value() As Boolean
Value = pValue
End Property
Public Property Let Value(Value As Boolean)
pValue = True
End Property
There are two parts to creating and linking form controls to custom support objects (classes). In your case
Class Module: clsMyCheckbox
Option Explicit
Option Compare Database
Public WithEvents chkBox As CheckBox
Public chkLabel As Label
Private currentUser As String
Private Sub chkBox_Click()
If chkBox.Value = True Then
chkLabel.Caption = "Completed by " & currentUser
chkLabel.ForeColor = vbGreen
Else
chkLabel.Caption = "Please tick if Complete"
chkLabel.ForeColor = vbBlack
End If
End Sub
Private Sub Class_Initialize()
currentUser = Environ$("Username")
End Sub
And in your form module:
Option Explicit
Option Compare Database
Private localCheckboxes As New Collection
Private Sub Form_Load()
'--- find all the checkboxes on the form and create a
' handler object for each one
Dim ctl As Control
Dim chknum As String
Dim cbObj As clsMyCheckbox
Dim chkLbl As Label
For Each ctl In Me.Controls
If ctl.ControlType = acCheckBox Then
'--- you can filter by name if needed
If ctl.Name Like "SC*" Then
chknum = Right(ctl.Name, Len(ctl.Name) - 2)
Set chkLbl = Me.Controls.Item("Lbl" & chknum)
chkLbl.Caption = "initialized" 'optional during form load
Set cbObj = New clsMyCheckbox 'class object for this checkbox
Set cbObj.chkBox = ctl 'link the control to the object
Set cbObj.chkLabel = chkLbl 'link the label too
'--- add it to a local store so the object persists
' as long as the form is open
localCheckboxes.Add cbObj
End If
End If
Next ctl
End Sub
Private Sub Form_Unload(Cancel As Integer)
'--- guarantee the objects are destroyed with the form
Set localCheckboxes = Nothing
End Sub
I think you are going the wrong way. In Access you can't really derive your own classes for GUI control and use them on the form. For your problem, you basically have three options:
Use the default event handlers and call one custom function from each. This will improve your situation a little.
Use one custom event handler for all checkboxes, instead of the default event-handlers.
Use a class and attach an instance to each of the checkboxes you use. The class can then recieve any event from the checkbox. This is powerful but you will still need to register your class with each control and hold all you instances somewhere for this to work.
For your problem, I'd go with solution 2:
First, write a custom event handler like this in your Form-module:
Private Function chkClick(sName As String)
Debug.Print "Clicked: " & sName
Me.Controls(sName).Controls(0).Caption = "x"
End Function
Next, enter design mode of you form and go to all checkboxes. In Checkbox "SC1", you go to the "OnClick" event and enter =chkClick("SC1") as event handler instead of [Eventprocedure]. Make sure you use the correct name of the control as the parameter of the function.
Congratulations! From now on, all your checkboxes will call the same event-handler and pass their name. Since the label of a checkbox is its associated control, you get to that label from the checkbox via .Controls(0), meaning the first "sub"-control of the checkbox. This way, you don't need to know the name of the associated label at all!

Dirty event not firing on Access 2007 form

I have a bound pop up form with a Clear data button. It runs the Undo command.
The Form_Current event sets this button's enable property to False.
The Form_Dirty event sets this button's enable property to True.
The button's property is always set to False even after I enter data into the form. I think this is because my Form_Load event is populating two fields. One is passed from the main form as an OpenArgs, the other is the unique ID which is calculated based on the OpenArgs value.
Any suggestions as to how to get the Dirty event to activate under these circumstances? If not, then an alternative approach perhaps?
Thanks in advance.
Code below:
Private Sub cmdUndoChanges_Click()
CustID_temp = Me!CustID
FacNo_temp = Me!Unique_ID
DoCmd.RunCommand acCmdUndo
Me!CustID = CustID_temp
Me!Unique_ID = FacNo_temp
End Sub
Private Sub Form_Current()
Me!cmdUndoChanges.Enabled = False
End Sub
Private Sub Form_Dirty(Cancel As Integer)
Me!cmdUndoChanges.Enabled = True
End Sub
Private Sub Form_Load()
Dim test As Integer
Me!CustID = OpenArgs
test = DCount("Unique_ID", "tbl_Table2", "CustID = '" & Me!CustID & "'")
If IsNull(Me!UNIQUE_No) Then
test = test + 1
Me!Unique_ID = CustID & "-" & test
MsgBox "No Previous Data"
Else
' these will be turned back on when the user selects the
' modify data button or add new data button.
For Each ctl In Me.Controls
Select Case ctl.ControlType
Case acTextBox, acComboBox, acOptionGroup, acCheckBox
ctl.Locked = True
ctl.BackColor = 15066597
Box40.BackColor = 15066597
End Select
Next ctl
End If
MsgBox Me!Unique_ID
End Sub
Have you tried Form_BeforeInsert() instead of Form_Dirty()?
I found another case where the Form_Dirty event never fires, the hard way. I thought I'd add it here since this is the top search result for the "not firing" question.
If your Form_Load function does anything to change the value of an existing record, the form will be set to dirty immediately, apparently before the logic that fires the event begins to run. Because of that there will never be an event if other data on the form is changed.
We had a "smart" Save button that was disabled until Form_Dirty fired. After I added a fixup to Form_Load for old records with a junk field, editing those records no longer ever enabled the Save button.