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 Date
End 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 + b
End Sub
Sub Test2()
 MsgBox Screen.Width * Screen.Height
End Sub

3 类模块声明和使用

3.1 类模块声明

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

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

 

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()
 MsgBox "姓名:" & mstrname & vbCrLf & "年级:" & mstrGrade
End Sub
Private Sub Class_Initialize()
 mstrGrade = "一年级"
End Sub
Private Sub Class_Terminate()
 MsgBox "objStudent对象使用的内存及系统资源已经释放"
End Sub

3.2 类模块的使用

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

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

版权声明:本文内容由网友提供,该文观点仅代表作者本人。本站(http://www.zengtui.com/)仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 3933150@qq.com 举报,一经查实,本站将立刻删除。

版权声明:本文内容由作者小航提供,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至907991599@qq.com 举报,一经查实,本站将立刻删除。如若转载,请注明出处:http://www.hangzai.com/330136.html

(0)
小航的头像小航

相关推荐