英文VB教程 簡體Visual Basic教程 繁體Visual Basic教程

第14課: VB的用户定義函數


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 所示。

 

程式碼

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





版权所有©2008 Dr.Liew Voon Kiong。保留所有权利 。联系我们: VB面子书

[Privacy Policy]