圖14.1
函數的基本語法如下:
Public Function functionName (Arg As dataType,..........) As dataType
或
Private Function functionName (Arg As dataType,..........) As dataType
* Public表明該函數是適用於整個程序,
Private 則表明該函數適用於某個模塊或子程序。
圖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.TextFutureVal = FV(PresentVal, interest, period)
LblFV.Caption=FutureVal
End Sub
範例 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 SelectEnd Function
Private Sub compute_Click()
Lbl.Caption = grade(txtMark)
End Sub