新建From1(窗体),新建Command1(按钮CommandButton),代码:
Private Sub Command1_Click()
'声明 初始化
Dim x As clsStudent
Set x = New clsStudent
x.name = "Red"
Debug.Print x.name
Call x.ShowInfo
Set x = Nothing
End Sub
新建类模块 clsStudent.cls,代码:
Private mstrname As String
Private mstrGrade As String
'类方法
Public Property Get name() As String
name = mstrname
End Property
Public Property Let name(ByVal strName As String)
mstrname = strName
End Property
Public Property Get Grade() As String
Grade = mstrGrade
End Property
Public Property Let Grade(ByVal strGrade As String)
mstrGrade = strGrade
End Property
Public Sub ShowInfo()
Debug.Print "姓名:" & mstrname & vbCrLf & "年级:" & mstrGrade
End Sub
'类事件
Private Sub Class_Initialize()
mstrGrade = "一年级"
End Sub
Private Sub Class_Terminate()
Debug.Print "objStudent对象使用的内存及系统资源已经释放"
End Sub
运行结果:
Red
姓名:Red
年级:一年级
objStudent对象使用的内存及系统资源已经释放