第七章  过程
双击滚屏  关闭窗口

 

7.1 Sub 过程

  7.1.1 事件过程与通用过程
  7.1.2 通用过程的创建
  7.1.3 通用过程的调用

使用“过程”是实现结构化程序设计思想的重要方法。

在 VB 中,根据过程是否返回值,分为子程序过程( Sub 过程)和函数过程( Function 过程)两种。

7.1 Sub 过程

VB 的 Sub 过程分为事件过程和通用过程两大类。

7.1.1 事件过程与通用过程

1. 事件过程:

事件过程是当发生某个事件时,对该事件作出响应的程序段。事件过程由 VB 自行声明,用户不能增加或删除。

事件过程有以下几种情形

◇控件事件过程,其语法格式如下 :

Private Sub < 控件名 > _ < 事件名 > ( [< 形参表 >] )

[< 语句组 >]

End Sub

◇窗体事件过程,其语法格式如下 :

Private Sub Form _ < 事件名 > ( [< 形参表 >] )

[< 语句组 >]

End Sub

◇ MDI 窗体事件过程,其语法格式如下:

Private Sub MDIForm _ < 事件名 > ( [< 形参表 >] )

[< 语句组 >]

End Sub

2. 通用过程

通用过程只能由事件过程调用,不与特定的事件联系。目的是为了减少编写重复代码。存储在窗体或标准模块中。

7.1.2 通用过程的创建

通用过程的创建:

1. 在 “ 代码 ” 编辑窗口中输入

[Private|Public][Static] Sub < 过程名 > ( [< 形参表 >] )

[< 语句组 >]

[Exit Sub]

[< 语句组 >]

End Sub

2. 使用添加过程对话框

①打开要添加过程的代码编辑窗口,如下图:

 

 

                     

②选择 “ 工具 ”\“ 添加过程 ” 命令。

③在 “ 添加过程 ” 对话框中选择有关选项即可,如下图:

                    


说明:

◇在过程内,不能再定义过程,可以调用其他 Sub 过程或 Function 过程。

◇ < 形参表 > 中的参数语法为:

[[Optional][ByVal|ByRef]|ParamArray]< 变量名 >[()][As< 类型 >][=< 缺省值 >]…

 

7.1.3 通用过程的调用

通用过程的调用有两种调用方法:

•  使用 Call 语句: Call < 过程名 > ( [< 实参表 >] )

•  直接使用过程名: < 过程名 > [< 实参表 >]

说明:

◇ < 实参表 > 是实际参数,参数之间用逗号分隔。

◇使用 Call 关键字,过程名后必须加括号,若有参数,须放在括号中。

◇省略 Call 关键字,过程名后不能加括号,若有参数,直接跟在过程名后,参数与过程名之间用空格分隔。

示例: M=40

Stars M

Call Stars (M)

实际参数可以是常量、变量、表达式。

例 1 :一个窗口包含三个命令按钮, 编制程序完成单击 Command1 使 Command2 不能使用,单击 Command2 使 Command1 不能使用,单击 Command3 使 Command1 和 Command2 都可用。

程序代码:

Public Sub button(char As Object)

Select Case char

Case Command1

Command2.Enabled = False

Case Command2

Command1.Enabled = False

Case Command3

Command1.Enabled = True

Command2.Enabled = True

End Select

End Sub

Sub Command1_Click()

button Command1

End Sub

 

Private Sub Command2_Click()

button Command2

End Sub

 

Private Sub Command3_Click()

button Command3

End Sub

 

执行结果:

                      

例 2 :计算阶乘 5! 、 6! 、 8! ,以及阶乘和 5!+6!+8! 。

程序代码:

Sub fact(m As Integer, t As Long)

Dim i As Integer

t = 1

For i = 1 To m

t = t * i

Next i

End Sub

 

Private Sub Command1_Click(Index As Integer)

Dim a As Integer, b As Integer, c As Integer

Dim s As Long, tot As Long

n = Index

Select Case n

Case 0

a = 5:Call fact(a, tot):Label1.Caption = a & "!=" & tot

Case 1

a = 6:Call fact(a, tot):Label1.Caption = a & "!=" & tot

Case 2

a = 8:Call fact(a, tot):Label1.Caption = a & "!=" & tot

Case 3

a = 5: b = 6: c = 8:Call fact(a, tot): s = tot

Call fact(b, tot): s = s + tot:Call fact(c, tot):s = s + tot

Label1.Caption = a & "!+" & b & "!+" & c & "!=" & s

End Select

End Sub

 

执行结果:

                        


 
双击滚屏  关闭窗口
 
版权所有数学与信息科学学院