第14课: VB的用户定义函数
时间:2014-07-19 17:01 来源: 我爱IT技术网 作者:山风
14.1 建立用户定义的VB 函数
函数的一般格式如下:
Public Function functionName (Arg As dataType,..........) As dataType
或
Private Function functionName (Arg As dataType,..........) As dataType
* Public表明该函数是适用于整个程式,
Private 则表明该函数只适用于某个模块或子程序。
范例 14.1
在这个范例里,用户可以计算某数额金钱的未来值(FutureValue, FV), 输出屏幕如图14.1 所示。

图14.1
程式码
- Public Function FV(PV As Variant, i As Variant, n As Variant) As Variant
- '计算未来值(FV-Future Value)的公式
- 'PV 代表 Present Value (现值)
- FV = PV * (1 + i / 100) ^ n
- End Function
- Private Sub compute_Click()
- Dim FutureVal As Variant
- Dim PresentVal As Variant
- Dim interest As Variant
- Dim period As Variant
- PresentVal = TxtPV.Text
- interest = TxtRate.Text
- period = TxtYears.Text
- FutureVal = FV(PresentVal, interest, period)
- LblFV.Caption=FutureVal
- End Sub
范例 14.2
以下函数将自动计算学生获得的考试分数和等级,输出屏幕如图14.2 所示。

图14.2
程式码
- Public Function grade(mark As Variant) As String
- Select Case mark
- Case Is >= 80
- grade = "A"
- Case Is >= 70
- grade = "B"
- Case Is >= 60
- grade = "C"
- Case Is >= 50
- grade = "D"
- Case Is >= 40
- grade = "E"
- Case Else
- grade = "F"
- End Select
- End Function
- Private Sub compute_Click()
- Lbl.Caption = grade(txtMark)
- End Sub
- 评论列表(网友评论仅供网友表达个人看法,并不表明本站同意其观点或证实其描述)
-
