定义方法的基本语法: Private/Publc Property Get <读属性过程名> As <属性返回值类型>; Private/Public Property Let <写属性过程名>(ByVal 变量名 As 返回值类型); Private/Publc Function <函数名> As <函数返回值类型>; get: 将模块中的私有变量的值赋给属性过程,通常称为读; Let: 通过属性过程给模块中的私有变量值赋,通常称为写。
代码部分: Public Property Get GetName() As String GetName = FName End Property Public Property Let SetName(ByVal Name As String) FName = Name End Property Public Property Get GetMath() As Single GetMath = FMath End Property Public Property Let SetMath(ByVal Math As Single) FMath = Math End Property Public Property Get GetEnglish() As Single GetEnglish = FEnglish End Property Public Property Let SetEnglish(ByVal English As Single) FEnglish = English End Property Public Function Total() As Single ''''计算总成绩函数 Total = GetMath + GetEnglish End Function
4.2.给模块中四个私有变量赋值的单击事件 Private Sub ComSetValues_Click() If Val(txtMath.Text) >= 0 And Val(txtMath.Text) <= 100 And Val(txtEN.Text) >= 0 And Val(txtEN.Text) <= 100 Then With Score .SetName = txtName.Text .SetMath = Val(txtMath.Text) .SetEnglish = Val(txtEN.Text) End With txtName.Text = "" txtMath.Text = "" txtEN.Text = "" Print "姓名:" & Score.GetName & "数学:" & Score.GetMath & "英语:" & Score.GetEnglish Else MsgBox "成绩的取值范围:[0,100]", 64, "提示" End If End Sub
4.3.查询各科成绩及总分的单击事件 Private Sub ComSearch_Click() SearchKey = InputBox("请输入您要查询的姓名关键字:", "查询") If word = Score.GetName Then txtTotal.Text = Score.Total txtName.Text = Score.GetName txtMath.Text = Score.GetMath txtEN.Text = Score.GetEnglish txtTotal.Visible = True labTotal.Visible = True Else MsgBox "抱歉!无此记录!", 64, "提示" End If End Sub
4.4.窗口载入事件 Private Sub Form_Load() txtTotal.Visible = False labTotal.Visible = False End Sub
4.5窗口关闭事件,在这里我们将释放对象变量,否则将会发生存储器泄露 Private Sub Form_Unload(Cancel As Integer) Set Score = Nothing End Sub