您的位置 首页 php

VBA|四种过程:Sub、Function、Property、Event及传值和传址

过程是构成程序的一个模块,往往用来完成一个相对独立的功能。过程可以使程序更清晰、更具结构性。 VBA 具有四种过程:Sub过程、 Function 函数、Property属性过程和Event事件过程。

一.Sub 过程

Sub 过程的参数有两种传递方式:按值传递(ByVal)和按地址传递(ByRef)。如下例:

	Sub password (ByVal x as integer, ByRef y as integer)
	 If y = 100 Then y = x + y 
	 Else y = x - y
	 x = x + 100
	End Sub
	Sub call_password ()
	 Dim x1 as integer
	 Dim y1 as integer
	 x1 = 12
	 y1 = 100
	 Call password (x1,y1) ‘调用过程方式:1. Call 过程名(参数1, 参数 2…) ; 2. 过 程名 参数 1, 参数 2…
	  Debug .print x1,y1 ‘结果是 12、112,y1 按地址传递改变了值,而 x1 按值传递,未改变原值
	End Sub 
 

传值和传址各有优势或适用场合,传值的函数的封装程度更高,更安全。传址的空间和时间效率更高,因为另外使用内存空间与赋值都是有时间和空间上的性能损耗的,特别是当使用复合类型,数据量大时。

二.Function 函数

函数实际是实现一种映射,它通过一定的映射规则,完成运算并返回结果。参数传递也两种:按值传递(ByVal)和按地址传递(ByRef)。如下例:

	Function password(ByVal x As Integer, ByRef y As Integer) As Boolean
	 If y = 100 Then
	 y = x + y
	 Else
	 x = x + 100
	 End If
	 If y <> 100 Then
	 password = True
	 Else: password = False
	 End If
	End Function
	 
	Sub call_password()
	 Dim x1 As Integer
	 Dim y1 As Integer
	 x1 = 12
	 y1 = 100
	 If password(x1, y1) Then '调用函数:1. 作为一个表达式放在 = 右端 ; 2. 作为参数使用
	 Debug.Print x1
	 Debug.Print y1
	 End If
	End Sub
	输出:12 112 
 

三.Property 属性过程和 Event 事件过程

这是 VB 在对象功能上添加的两个过程,与对象特征密切相关,也是 VBA 比较重要组成,技术比较复杂,可以参考相关书籍。

	‘类模块:ClsStudent
	‘类属性
	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
 

-End-

文章来源:智云一二三科技

文章标题:VBA|四种过程:Sub、Function、Property、Event及传值和传址

文章地址:https://www.zhihuclub.com/77781.shtml

关于作者: 智云科技

热门文章

网站地图