類模塊兒和一般常用的控件一樣都是一種對象,具有事件、屬性等性質(zhì)。因此學(xué)會創(chuàng)建類模塊兒對象,在編程中是非常重要的。
下面的自定義模塊兒實(shí)現(xiàn): 增加一個(gè)text屬性;并自動驗(yàn)證前后兩次字符串變量是否一致的功能。 在testClass模塊二中添加如下代碼: Option Explicit '增加一個(gè)驗(yàn)證字符串事件 Public Event PropertyChanged(ByVal PropName As String, ByVal oldValue As String, ByVal newValue As String) '聲明變量 Private m_Text As String '聲明內(nèi)部屬性 'Public Property Get Text() As String 'Text = m_Text 'End Property ━━━━━━━━━━━━━━━━━━━━━━━━━ '添加事件的調(diào)用 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() '實(shí)例化對象變量,并進(jìn)行兩次賦值 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 |
|