例: Function ステートメント

サブルーチンと関数を使用して、住宅の購入費用を次のように計算します。

Dim price As Single, message As String

Function Payment (princpl As Single, _
                  ByVal intrst As Single, _
                  ByVal term As Integer) As Single
   intrst! = intrst! / 12
   term% = term% * 12
   ' If any of the arguments are invalid, exit the function
   ' (payment will return the value 0).
   If princpl! <= 0 Or intrst! <= 0 Or term% < 1 Then _
      Exit Function
   ' The standard formula for computing the amount of the
   ' periodic payment of a loan:
   Payment = princpl! * intrst! / (1 - (intrst! + 1) ^ _
      (-term%))
End Function

Sub ComputeMortgageCosts (price As Single)
   Dim totalCost As Single, downpmt As Single
   Dim mortgage As Single, intrst As Single
   Dim monthlypmt As Single, years As Integer
EnterInfo:
   downpmt! = CSng(InputBox("How much is the down payment?"))
   ' The downpayment must be at least 10% of the price.
   If downpmt! < (0.1 * price!) Then
     MessageBox "Your down payment must be at least " _
         & Format(price! * .1, "Currency")
      GoTo EnterInfo
   Else
      mortgage! = price! - downpmt!
   End If
   intrst! = CSng(InputBox("What is the interest rate?"))
   years% = CInt(InputBox("How many years?"))
   ' Call the Payment function, which returns the
   ' monthly payment.
   monthlypmt! = Payment(mortgage!, intrst!, years%)
   totalCost! = downpmt! + (monthlypmt! * years% * 12)
   If monthlypmt! > 0 Then ' Create a multiline message.
      message$ = _  
       |Price | & Format(price!, "Currency") & |
       Down Payment: | & Format(downpmt!, "Currency") & |
       Mortgage: | & Format(mortgage!, "Currency") & |
       Interest: | & Format(intrst!, "Percent") & |
       Term: | & Str(years%) & |
       years Monthly Payment: | & Format(monthlypmt!, _   
       "Currency") & | 
       Total Cost: | & Format(monthlypmt! * years% * 12, _   
        "Currency")
   Else
      message$ = "You did not enter valid input."
   End If
End Sub

' Start here.
price! = CSng(InputBox("How much does the house cost?"))
' Call the Compute MortgageCosts sub.
ComputeMortgageCosts (price!)
' Display the message.
MessageBox message$