VBA中的四类模块:“标准模块”、Microsoft Excel工作簿和工作表对象、窗体、类模块。(VBE→插入菜单)
1 自定义过程A Sub is a procedure that performs a specific task but does not return a specific value. Sub是执行特定任务但不返回特定值的过程。 Sub ProcedureName ([argument_list]) [statements]End Sub If no access modifier is specified, a procedure is Public by default. 如果未指定访问修饰符,则默认情况下,过程是公共的。 demo code:
2 自定义函数A Function is a procedure that is given data and returns a value, ideally without global or module-scope sideeffects. 函数是一个给定数据并返回值的过程,理想情况下没有全局或模块范围的副作用。 Function ProcedureName ([argument_list]) [As ReturnType] [statements]End Function 实例代码:
3 自定义类型和枚举VBA中,自定义类型相当于C语言中的结构体,枚举类型也与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 EnumPublic Enum Screen Width = 1366 Height = 768End 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 4 自定义类VBA虽是基于对象的语言,但也可以自定义类。 VBA中, 类模块相当于C语言中的类,类模板要单独放到类模块中(自定义类型和子过程放在模块中),类模板的名称就是类的名称,可以做为新的类型进行声明和定义。 Alt+F11→“插入”→“类模块”→在“属性”窗口中修改类的名称为'clsADO'。
A Property is a procedure that encapsulates module data. A property can have up to 3 accessors: Get to return a value or object reference, Let to assign a value, and/or Set to assign an object reference. 属性是封装模块数据的过程。一个属性最多可以有3个访问器:Get以返回值或对象引用,Let以指定值,和/或Set以指定对象引用。 Property Get|Let|Set PropertyName([argument_list]) [As ReturnType] [statements]End Property Properties are usually used in class modules (although they are allowed in standard modules as well), exposing accessor to data that is otherwise inaccessible to the calling code. A property that only exposes a Get accessor is 'read-only'; a property that would only expose a Let and/or Set accessor is 'write-only'. Write-only properties are not considered a good programming practice - if the client code can write a value, it should be able to read it back. 属性通常在类模块中使用(尽管在标准模块中也允许使用),对访问者暴露调用代码无法访问的数据。仅公开Get访问器的属性为“只读”;仅公开Let和/或Set访问器的属性为“只写”。只写属性被认为不是一种好的编程实践——如果客户机代码可以写一个值,它应该能够读回它。 A Function or Property Get procedure can (and should!) return a value to its caller. This is done by assigning the identifier of the procedure: 函数或Property Get过程可以(而且应该!)将值返回给其调用者。这是通过给过程的标识符赋值来完成的:
Any public Sub, Function, or Property inside a class module can be called by preceding the call with an object reference: 通过在调用之前使用对象引用,可以调用类模块中的任何公共子、函数或属性: Object.Procedure -End- |
|