Function (VBA)

From StudyWiki

Jump to: navigation, search

This page is about functions in VBA, for general information on functions, see Function


Function Definition

   Function <function name>( <parameter list> ) As <data type>
       
       <function body>
       
       <function name> = <result> 'This line returns the value of the function
       
   End Function


<function name>
the name of the function.
<parameter list>
A list of parameters the function takes.
<data type>
The data type of the function's result.
<function body>
a series of statements and expressions performing the function.
<result>
the result of the function.


Naming Conventions

  • must begin with a letter (a-z or A-Z) or an underscore
  • cannot contain a period (.) or a special character
  • must not contain a space
  • must not exceed 255 characters.
    • You should keep the function's name as short as possible
  • must be unique in the same scope
  • The name should be meaningful
  • where functions perform actions that can be represented with a verb, use that verb to name it.
  • Start each word in the name with a capital letter. E.g. CalculateInterest

Calling Functions

  • Call the function by its name, followed by it's argument list in brackets.
  • Because functions return results, when you call them you must assign the result to something.
  • For Example:

   variable1 = Function1(argument1, argument2)