类模块儿和一般常用的控件一样都是一种对象,具有事件、属性等性质。因此学会创建类模块儿对象,在编程中是非常重要的。
下面的自定义模块儿实现:
增加一个text属性;并自动验证前后两次字符串变量是否一致的功能。
在testClass模块二中添加如下代码:
Option Explicit
'增加一个验证字符串事件
Public Event PropertyChanged(ByVal PropName As String, ByVal oldValue As String, ByVal newValue As String)
'声明变量
Private m_Text As String
'声明内部属性
'Public Property Get Text() As String
' Text = m_Text
'End Property
'添加事件的调用
Public Property Let Text(ByVal n_Text As String)
If n_Text <> m_Text Then
Dim oldText As String
oldText = m_Text
m_Text = n_Text
RaiseEvent PropertyChanged("Text", oldText, n_Text)
End If
End Property
在窗体中添加如下代码:
Option Explicit
'声明具有事件的对象
Public WithEvents oTest As testClass
Private Sub Form_Load()
'实例化对象变量,并进行两次赋值
Set oTest = New testClass
oTest.Text = "123"
oTest.Text = "456"
End Sub
Private Sub otest_propertychanged(ByVal PropName As String, ByVal oldValue As String, ByVal newValue As String)
' MsgBox "oTest的属性" & PropName & "从" & oldValue & "变成" & newValue & " 了!"
MsgBox "otest的属性" & PropName & "从 “ " & oldValue & "” 变成 “" & newValue & "” 了!"
End Sub