On Jan 23, 3:25 am, "Rico" <y...@me.com> wrote:
> I have an issue that I'm actually dealing with in a VB6 app, but was
> wondering if someone here happens to have an answer for this that I could
> port to the VB6 app.
>
> Is there a way to call an event from a string? I know I've seen code
> that looks similar to the following;
>
> Controls(control.name)("Validate") or
> Controls(control.name).Events("Validate")
>
> ...at some point in my travels, but can't recall what the syntax was. The
> reason I'm looking to do this is because the validate events on each field
> are validating the data entered, setting the class properties and upon
> leaving the form, are saving the values to the database through the
> class.save method. The problem is when someone clicks on the "X" to close
> the form down, the validate event does not fire.
Within scope, you can call the event handler using its name and
supplying any parameters e.g.
Option Explicit
Private Sub Text1_Validate(Cancel As Boolean)
' Validation code here
End Sub
Private Sub Form_QueryUnload(Cancel As Integer, UnloadMode As Integer)
Dim bCancel As Boolean
Text1_Validate bCancel
Cancel = bCancel
End Sub
An event handler is scoped as Private by default but there is nothing
(bar good software engineering principles <g>) preventing you from
changing it to Public.
Perhaps a better approach would be to have a separate Validate routine
that is called from all appropriate events e.g.
Option Explicit
Private Sub Text1_Validate(Cancel As Boolean)
Cancel = ValidateText1
End Sub
Private Sub Form_QueryUnload(Cancel As Integer, UnloadMode As Integer)
Cancel = ValidateText1
End Sub
Private Function ValidateText1() As Boolean
' Validation code here
End Function
Obviously, such an approach does not scale well e.g. you need a
dedicated routine for each control (and remember to call them all) or
an all-singing-all-dancing routine which could be a maintenance
headache. How you solve the perceived problem depends on the amount of
significance of the validation routines, the potential for code reuse,
coder skill level, personal style, etc but there are lot's of
possibilities (VBA6 has a CallByName method if your personal style is
'quick and dirty' <g>).
Jamie.
--
|