Examples: Function statement

Use a sub and a function to compute the cost of buying a house as follows:

  • Ask the user for the price of the house, and call the ComputeMortgageCosts sub with price as the argument.
  • The ComputeMortgageCosts sub gathers down payment (at least 10% of cost), annual interest rate, and the term of the mortgage from the user, then calls the Payment function with three arguments. Annual interest and term (years) are passed by value rather than reference so the Payment function can adjust them to compute monthly rate and monthly payment without changing the values of these variables in the ComputeMortgageCosts sub.
  • If the user enters positive values, Payment returns the monthly payment. Otherwise, it returns 0. ComputeMortgageCosts then constructs an appropriate message.
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$