VBA Function With Examples


Example

As stated above Functions are smaller procedures that contain small pieces of code which may be repetitive inside a Procedure.

Functions are used to reduce redundancy in code.

Similar to a Procedure, A function can be declared with or without an arguments list.

Function is declared as a return type, as all functions return a value. The Name and the Return Variable of a function are the Same.

  1. Function With Parameter:

     Function check_even(i as integer) as boolean
     if (i mod  2) = 0 then
     check_even = True
     else
     check_even=False
     end if
     end Function
    
  2. Function Without Parameter:

     Function greet() as String
     greet= "Hello Coder!"
     end Function
    

The Function can be called in various ways inside a function. Since a Function declared with a return type is basically a variable. it is used similar to a variable.

Functional Calls:

    call greet() 'Similar to a Procedural call just allows the Procedure to use the
                 'variable greet 
    string_1=greet() 'The Return value of the function is used for variable
                     'assignment

Further the function can also be used as conditions for if and other conditional statements.

      for i = 1 to 10
      if check_even(i) then
      msgbox i & " is Even"
      else
      msgbox i & " is Odd"
      end if
      next i

Further more Functions can have modifiers such as By ref and By val for their arguments.