This documentation is archived and is not being maintained.

Creating Methods

This content is no longer actively maintained. It is provided as is, for anyone who may still be using these technologies, with no warranties or claims of accuracy with regard to the most recent product version or service release.

A method performs an action on or with an object. Any public Sub or Function procedure that you add to a class module becomes a method of the object. If a method is a Sub procedure, it does not return a value; if it is a Function procedure, it returns a value.

For example, the following procedure is the Multiply method for a hypothetical object named Calculator:

Public Function Multiply(ParamArray avarOperands() As Variant) As Variant
   ' Multiplies the set of numbers passed in to the procedure.
   Dim lngCount      As Long
   Dim dblResult   As Double
   Dim varElement   As Variant
   
   ' Initialize result to 1, since multiplying by 0 would
   ' return 0.
   dblResult = 1
   ' Loop through parameter array, from lower bound to upper
   ' bound.
   For lngCount = LBound(avarOperands) To UBound(avarOperands)
      ' Store value of element.
      varElement = avarOperands(lngCount)
      ' Check whether element is numeric.
      If IsNumeric(varElement) Then
         ' Multiply result by element.
         dblResult = dblResult * varElement
      Else
         ' Return Null if any element is not numeric.
         Multiply = Null
         GoTo Multiply_End
      End If
   Next

   Multiply = dblResult
   
Multiply_End:
   Exit Function
End Function

To call this method, create a new object of type Calculator, and pass in the values that you want to multiply, as shown in the following code fragment:

Dim calCalc As New Calculator
   
Debug.Print calCalc.Multiply(2.5, 2.5, 2.5)

See Also

Why Build Your Own Objects? | Basic Class Concepts | Creating Property Procedures | Creating Events and Event Procedures | Extending Objects Through Interfaces | Designing Object Models | Creating Custom Objects for Web Pages

Show: