vba类模块是做什么用的 分享vba类模块完全教程

vba类模块是做什么用的 分享vba类模块完全教程

VBA中,自定义类型相当于C语言中的结构体,枚举类型也与C语言中的枚举类型相似。自定义类型和枚举类型放到模块的子过程的前面即可。

VBA中, 类模块相当于C语言中的类,类模板要单独放到类模块中(自定义类型和子过程放在模块中),类模板的名称就是类的名称,可以做为新的类型进行声明和定义。

1 自定义类型的声明和使用

1.1 自定义类型的声明

Public Type Car Name As String Price As Currency Length As Single ShouDongDang As Boolean ProductionDate As DateEnd Type

1.2 自定义类型的使用

Sub Test1() Dim MyCar As Car, YourCar As Car With MyCar .Name = "桑塔纳" .Price = 300000@ .Length = 4.2 .ShouDongDang = False .ProductionDate = #7/8/2015# End With With YourCar .Name = "大众" .Price = 80000@ .Length = 4.5 .ShouDongDang = True .ProductionDate = #2/18/2015# End With MsgBox "两辆车总价值:" & (MyCar.Price + YourCar.Price)End Sub
2 自定义枚举类型的声明和使用

2.1 自定义枚举类型的声明

Public Enum JapaneseWeekDay

月曜日

火曜日

水曜日

木曜日

金曜日

土曜日

日曜日

End Enum

Public Enum Screen

Width = 1366

Height = 768

End Enum

2.2自定义枚举类型的使用

Sub Test1() Dim a As Long, b As Long a = JapaneseWeekDay.金曜日 b = JapaneseWeekDay.土曜日 MsgBox a + bEnd SubSub Test2() MsgBox Screen.Width * Screen.HeightEnd Sub
3 类模块声明和使用

3.1 类模块声明

菜单:插入→插入类模板clsStudent:

Private mstrname As StringPrivate mstrGrade As StringPublic Property Get name() As String name = mstrnameEnd PropertyPublic Property Let name(ByVal strName As String) mstrname = strNameEnd PropertyPublic Property Get Grade() As String Grade = mstrGradeEnd PropertyPublic Property Let Grade(ByVal strGrade As String) mstrGrade = strGradeEnd PropertyPublic Sub ShowInfo() MsgBox "姓名:" & mstrname & vbCrLf & "年级:" & mstrGradeEnd SubPrivate Sub Class_Initialize() mstrGrade = "一年级"End SubPrivate Sub Class_Terminate() MsgBox "objStudent对象使用的内存及系统资源已经释放"End Sub

3.2 类模块的使用

Public Sub TestclsStudent() Dim objStudent As New clsStudent objStudent.name = "张三" objStudent.ShowInfo Set objStudent = NothingEnd Sub