Difference Between Functions & Subroutines in Visual Basic

104 32

    Definition

    • A subroutine is composed of a series of Visual Basic statements, enclosed by the "Sub" and "End Sub" statements. A function procedure is also composed of a series of Visual Basic statements, but it must be enclosed by the "Function" and "End Function" statements. All executable code must be inside both a subroutine and a function procedure. Both of them can be defined in modules, classes, and structures.

    Declaration

    • You declare a subroutine in a way similar to how you would declare a variable, by specifying the parameter name and data type. You can specify the parameter passing mechanism such as "ByVal" or "ByRef." Each parameter is treated as a local variable to the subroutine, meaning that the lifetime of the parameter is the same as that of the procedure. In a function, you can declare the data type of the value it returns such as "Integer" or "Double." If you don't specify the "returntype," the function will return an "Object" data type.

    Returning Data

    • In VB, you can pass an argument to a procedure (subroutine or function) by value or by reference by specifying the "ByVal" or "ByRef" keywords. By default a subroutine and a function treat their arguments as by value, which means that the procedure cannot modify the contents of the variable element in the calling code. A function will return a value by assigning the value to the function name, or include it in the "Return" statement. A subroutine normally doesn't return a value, but you can define an argument as "ByRef" to return a value as a parameter.

    Example

    • The following is an example of a subroutine:

      Sub tellOperator(ByVal task As String)

      Dim stamp As Date

      stamp = TimeOfDay()

      MsgBox("Starting " & task & " at " & CStr(stamp))

      End Sub

      The following is an example of a function:

      Function myFunction(ByVal j As Integer) As Double

      Return 3.87 * j

      End Function

Source...
Subscribe to our newsletter
Sign up here to get the latest news, updates and special offers delivered directly to your inbox.
You can unsubscribe at any time

Leave A Reply

Your email address will not be published.