How To Create a User Defined Function in Microsoft Excel

Tags
 
spreadsheet, function, user, Microsoft, microsoft excel, Defined, ms office, 2003 microsoft office, microsoft office, microsoft office 2000, microsoft office 97, microsoft office professional, microsoft office student, microsoft office suite, microsoft tutorials, microsoft videos, ms office tutorial, office professional, office small business, office tutorial, windows office, excel tricks, microsoft office tutorial, excel tips, excel tutorial, excel video, how to excel, ms excel, Spreadsheets, 2000 microsoft office, 2003 excel microsoft, 2003 ms office, 2003 office, excel help, excel how to, excel learning, excel microsoft, excel powerpoint, excel spreadsheet, excel training, excel tutorials, excel videos, excel workbook, how to microsoft office, how to ms office, how to use excel, learn excel, learn microsoft excel, learning excel, microsoft excel help, microsoft excel spreadsheet, microsoft excel tutorial, microsoft excel video, microsoft office 1997, microsoft office 2003, microsoft office academic, microsoft office help, microsoft office how to, microsoft office lesson, microsoft office pro, microsoft office video, microsoft tutorial, microsoft video, ms office 1997, ms office 2000, ms office 2003, ms office 97, ms office academic, ms office help, ms office pro, ms office professional, ms office student, ms office suite, office 2000, office 97, office help, office pro, office tutorials, spreadsheet help, spreadsheet tutorial, spreadsheet tutorials, using excel, excel user defined, user defined, user defined excel, user defined function, user defined help, user defined lesson, user defined tutorial, how to, Software How To Articles, MS Office How To Articles
Published 8/26/09 3 months ago | Views 91 Grade C     Software / MS Office
Create a User Defined Function in Microsoft Excel

This article was provided by wikiHow, a wiki building the world's largest, highest quality how-to manual. Please edit this article and find author credits at the original wikiHow article on how to create a user defined function in microsoft excel. Content on wikiHow can be shared under a Creative Commons License.

Grade C Views 91
Last edited 2 months ago

Even when Excel has a lot, probably hundreds, of built in functions like SUM, VLOOKUP, LEFT, and so on, once you start using Excel for more complicated tasks, you will often find that you need a function that doesn't exist. Don't worry, you're not lost at all, all you need is to create the function yourself.

Step 1  

Create a new workbook or open the workbook in which you want to use your newly created User Defined Function (UDF).

Step 2  

Open the Visual Basic Editor which is built into Microsoft Excel by going to Tools->Macro->Visual Basic Editor (or pressing Alt+F11).

 

Step 3  

Add a new Module to your workbook by clicking in the button shown. You can create the user defined function in the Worksheet itself without adding a new module, but that will make you unable to use the function in other worksheets of the same workbook.

 

Step 4  

Create the "header" or "prototype" of your function. It has to have the following structure: public function TheNameOfYourFunction (param1 As type1, param2 As type2 ) As returnType
It can have as many parameters as you want, and their type can be any of Excel's basic data types or object types as Range. You may think of parameters as the "operands" your function will act upon. For example, when you say SIN(45) to calculate the Sine of 45 degree, 45 will be taken as a parameter. Then the code of your function will use that value to calculate something else and present the result.

Step 5  

Add the code of the function making sure you 1) use the values provided by the parameters; 2) assign the result to the name of the function; and 3) close the function with "end function".
Learning to program in VBA or in any other language can take some time and a detailed tutorial. However, functions usually have small code blocks and use very few features of a language. The more useful elements of the VBA language are:
 

  1. The If block, which allows you to execute a part of the code only if a condition is met. For example:

    Public Function CourseResult(grade As Integer) As String

      If grade >= 5 Then

        CourseResult = "Approved"

      Else

        CourseResult = "Rejected"

      End If

    End Function
    Notice the elements in an If code block: IF condition THEN code ELSE code END IF. The Else keyword along with the second part of the code are optional.
  2. The Do block, which executes a part of the code While or Until a condition is met. For example:Public Function IsPrime(value As Integer) As Boolean

      Dim i As Integer

      i = 2

      IsPrime = True

      Do

        If value / i = Int(value / i) Then

          IsPrime = False

        End If

        i = i + 1

      Loop While i < value And IsPrime = True

    End Function
    Notice the elements again: DO code LOOP WHILE/UNTIL condition. Notice also the second line in which a variable is "declared". You can add variables to your code so you can use them later. Variables act as temporary values inside the code. Finally, notice the declaration of the function as BOOLEAN, which is a datatype that allows only the TRUE and FALSE values. This method of determining if a number is prime is by far not the optimal, but I've left it that way to make the code easier to read.
  3. The For block, which executes a part of the code a specified number of times. For example:Public Function Factorial(value As Integer) As Long

      Dim result As Long

      Dim i As Integer

      If value = 0 Then

        result = 0

      ElseIf value = 1 Then

        result = 1

      Else

        result = 1

        For i = 1 To value

          result = result * i

        Next

      End If

      Factorial = result

    End Function
    Notice the elements again:FOR variable = lower limit TO upper limit code NEXT. Also notice the added ElseIf element in the If statement, which allows you to add more options to the code that is to be executed. Finally, notice the declaration of the function and the variable "result" as Long. The Long datatype allows values much larger than Integer. Shown below is the code for a function that converts small numbers into words. 

Step 6  

Go back to your workbook and use the function by starting the content of a cell with an equal sign followed by the name of your function. Append to the name of the function an opening parenthesis, the parameters separated by commas and a final closing parenthesis. For example: =NumberToLetters(A4)
You can also use your user defined formula by looking for it in the User Defined category in the Insert Formula wizard. Just click in the Fx button located to the left of the formula bar.
The parameters can be of three types:
 

  1. Constant values typed directly in the cell formula. Strings have to be quoted in this case.
  2. Cell references like B6 or range references like A1:C3 (the parameter has to be of the Range datatype)
  3. Other functions nested inside your function (your function can also be nested inside other functions). I.e.: =Factorial(MAX(D6:D8))
 

Step 7  

Verify the result is Ok after using the function several times to ensure it handles different parameter values correctly:

 

Tips

  • Excel has many built in functions and most calculations can be done by using them either independently or in combination. Make sure you go through the list of available functions before you start coding your own. Execution may be faster if you use the built in functions.
  • If you don't know how to write the code for a function, read How to Write a Simple Macro in Microsoft Excel.
  • Whenever you write a block of code inside a control structure like If, For, Do, etc. make sure you indent the block of code using a few blank spaces or tab (the style of indentation is up to you). That will make your code easier to understand and you'll find a lot easier to spot errors and make improvements.
  • Use a name that's not already defined as a function name in Excel or you'll end up being able to use only one of the functions.
  • Sometimes, a function may not require all the parameters to calculate a result. In that case you can use the keyword Optional before the name of the parameter in the function header. You can use the function IsMissing(parameter_name) inside the code to determine if the parameter was assigned a value or not.

Warnings

  • Due to security measures, some people may disable macros. Make sure you let your colleagues know the book you're sending them has macros and that they can trust they're not going to damage their computers.
  • The functions used in this article are, by no means, the best way to solve the related problems. They were used here only to explain the usage of the control structures of the language.
  • VBA, as any other language, has several other control structures besides Do, If and For. Those have been explained here only to clarify what kind of things can be done inside the function source code. There are many online tutorials available where you can learn VBA.

Via wikihow

Obama! Are You Eating that Chicken Wing Correctly?

Yes, there is a right way and a wrong way to eat a chicken wing. And yes, Obama likes chicken wings just like everybody else does. Here's how you do it, courtesy of Food Wishes (also, here's several ...

SPLAT! Art Made from Everyday Household Items

Tom Friedman. One of my very favorite contemporary artists. Friedman injects the wonder into the humdrum. He creates magic from the unsuspected with his incredible sculptures assembled from simple ...

Cheat Your Way to 300 (via Remote Control)

This is full blown cheating - no ifs, ands or buts about it. Introducing the RC900, a remote-control bowling ball invented by San Antonio, Texas-based 900 Global. Says Popular Mechanics, "The ...

World's Fastest Bicycle Goes 75mph

Cycling enthusiasts, behold. Fastest bicycle in the world, designed by VARNA of British Columbia. Pretty impressive. Check it out, Barbara Buatois of France completes her new One Hour World Record at ...

Knit Your Food

Knitted delectable delights from Ed Bing Lee. Inspired? Gotta start somewhere. Previously, Crocheters Like to Party, Too. English Ladies Knit Entire Village.

loading...