Re: How can I define a "Change" event for a variable?
- From: "MikeD" <nobody@xxxxxxxxxxx>
- Date: Fri, 1 Dec 2006 19:51:58 -0500
"Javad" <Javad@xxxxxxxxx> wrote in message news:umfA49ZFHHA.5000@xxxxxxxxxxxxxxxxxxxxxxx
Hello
I have a variable such as "Num1", and now I want whenever the value of this variable changes, something happens. For example something like this:
Public Sub Num1_Change()
MsgBox "Number 1 Changed"
End Sub
How can I do such a thing?
One way to "fake" it would be to add a textbox to the form and make it invisible. Instead of assigning the value to a variable, assign it to the invisible textbox. You can then use the textbox's Change event.
OR, and this is what I'd do, make the variable a property. That way, you can have a Property Let procedure that is going to execute everytime you make an assignment to the property. You can write whatever code you want in the Property Let procedure. Here's an example. Just copy and paste this into General Declarations of a form (and excuse the use of the InputBox function; this is, afterall, only a simple example):
-----BEGIN CODE
Option Explicit
Private m_lNum1 As Long
Public Property Get Num1() As Variant
Num1 = m_lNum1
End Property
Public Property Let Num1(ByVal NewValue As Variant)
Dim lTemp As Long
On Error GoTo EH
lTemp = CLng(NewValue)
If lTemp <> m_lNum1 Then
MsgBox "Value assigned to Num1 property has changed"
m_lNum1 = lTemp
End If
Exit Property
EH:
MsgBox Err.Description
End Property
Private Sub Form_Click()
Dim sNum As String
sNum = InputBox$("Enter a NUMBER", , Num1)
Num1 = sNum
End Sub
-----END CODE
Now, something to clarify....even though the PROPERTY is a Variant, its member variable (the variable used to store the property's value) only allows a Long and therefore an error (which gets handled) will occur if anything that can't be converted to a Long is assigned to the property. The reason for doing this is so that the Property Let procedure itself handles any "non-valid" assignment to it. That may or may not be the way to want to deal with non-valid values for the property. I just thought I'd demo it that way. The data type for the Get and Let procedures could just as well be Long (it has to be the same for both procedures, though). You'd then deal with any assignment error differently (for example, in the procedure which makes the assignment, beneficial if you want to handle the error differently in different procedures). Also, note that the property is public (both the Get and the Let) so it's "fully" accessible to other modules in the project as long as those other modules qualify it using a reference to the form.
--
Mike
Microsoft MVP Visual Basic
.
- References:
- Prev by Date: Re: Simple VB Database Application
- Next by Date: Re: Make sure file path is there
- Previous by thread: Re: How can I define a "Change" event for a variable?
- Next by thread: Re: seeking guidance to solve compatibility problems in automated buil
- Index(es):