Você está na página 1de 4

How to Create Custom Excel Functions. User Defined Function (UDF) Examples for Excel.

" THE Guide to Excel in Everything "


Home | Excel Links | Excel Templates
SEARCH:

How to Create Custom User Defined Excel
Functions
Advanced Excel Techniques - (1/7/04)
- Jon Wittwer
Vertex42, LLC
Excel allows you to create custom functions, called "User Defined Functions" (UDF's) that can be
used the same way you would use SUM() or some other built-in Excel function.
The Excel enthusiast who wishes to use advanced mathematics or perform text manipulation is
often seriously disappointed by Excel's limited library of formulas and functions. However, all is not lost!
For an excellent explanation of pretty much everything you need to know to create your own custom
Excel function, I would recommend John Walkenbach's book, Excel 200X Formulas. The book
provides many good user defined function examples, so if you like to learn by example, it is a
great resource.
This article will help you get started with user defined functions and show a couple of cool
examples. If you are a software developer, specifically for engineering applications, I would
recommend the following course:
Microsoft Excel VBA User Defined Function Design for Engineers by EMAGENIT.com
"... The ability to make UDF's allows complex engineering calculations to take place in a single Microsoft Excel worksheet cell.
VBA UDF's can also be packaged into procedure libraries and distributed. This allows standardized rapid analysis environments to
be developed cheaply in Microsoft Excel. They can even communicate with FORTRAN and C utilizing their source code." Learn
More ...
How to Create Excel User Defined Functions
1. Open up a new workbook.
2. Get into VBA (Press Alt+F11)
3. Insert a new module (Insert > Module)
4. - Copy and Paste the Excel user defined function examples -
5. Get out of VBA (Press Alt+Q)
6. Use the functions (They will appear in the Paste Function dialog box, Shift+F3, under the "User
Defined" category)
If you want to use a UDF in more than one workbook, you can save your functions in your own custom
add-in. Simply save your excel file that contains your VBA functions as an add-in file (.xla). Then load
the add-in (Tools > Add-Ins...). Warning! Be careful about using custom functions in spreadsheets
that you need to share with others. If they don't have your add-in, the functions will not work when
they use the spreadsheet.
Benefits of User Defined Excel Functions
Create a complex or custom math function.
Simplify formulas that would otherwise be extremely long "mega formulas".
Diagnostics such as checking cell formats.
Custom text manipulation.
Advanced array formulas and matrix functions.
Limitations of UDF's
Quick Links ...
Create Excel Functions
Benefits of Excel UDFs
Limitations
UDF Examples
Optional UDF Argument


Vertex42 Articles
Amortization Formulas
Dashboard Reports
Using Excel Solver
Financial Modeling
Debt Consolidation
Monte Carlo Simulation
> Histograms in Excel
> Random Numbers
> Normal Distribution
Graph
Excel Web Queries
Custom Excel Functions
Excel Training
Toolbar Buttons
Significant Figures
Fun and Games

Excel Templates
> Amortization Schedule
> Asset Tracking
> Attendance Tracking
> Balloon Loan
> Excel Calendar
> Checkbook
> Class Schedule
> Expense Reports
> Gantt Chart
> Inventory
> Invoice
> Mortgage
> Personal Budget
> Project Management
> Purchase Order
> Retirement Savings
> Stock Quotes
> Timesheet
> Timeline Examples
> Work Schedule
http://www.vertex42.com/ExcelArticles/user-defined-functions.html (1 of 4) [1/5/2007 8:50:02 PM]
Go
How to Create Custom Excel Functions. User Defined Function (UDF) Examples for Excel.
Cannot "record" an Excel UDF like you can an Excel macro.
More limited than regular VBA macros. UDF's cannot alter the structure or format of a
worksheet or cell.
If you call another function or macro from a UDF, the other macro is under the same limitations as
the UDF.
Cannot place a value in a cell other than the cell (or range) containing the formula. In other words,
UDF's are meant to be used as "formulas", not necessarily "macros".
Excel user defined functions in VBA are usually much slower than functions compiled in C++ or
FORTRAN.
Often difficult to track errors.
If you create an add-in containing your UDF's, you may forget that you have used a custom
function, making the file less sharable.
Adding user defined functions to your workbook will trigger the "macro" flag (a security issue:
Tools > Macros > Security...).
User Defined Function Examples
Example #1: Get the Address of a Hyperlink
The following example can be useful when extracting hyperlinks from tables of links that have
been copied into Excel, when doing post-processing on Excel web queries, or getting the email
address from a list of "mailto:" hyperlinks.
This function is also an example of how to use an optional Excel UDF argument. The syntax
for this custom Excel function is:
=LinkAddress(cel l ,[def aul t _val ue])
To see an example of how to work with optional arguments, look up the IsMissing command
in Excel's VBA help files (F1).
Function LinkAddress(cell As range, _
Optional default_value As Variant)
'Lists the Hyperlink Address for a Given Cell
'If cell does not contain a hyperlink, return default_value
If (cell.range("A1").Hyperlinks.Count <> 1) Then
LinkAddress = default_value
Else
LinkAddress = cell.range("A1").Hyperlinks(1).Address
End If
End Function
Example #2: Extract the Nth Element From a String
This example shows how to take advantage of some functions available in VBA in order to do
some slick text manipulation. What if you had a bunch of telephone numbers in the following
format: 1-800-999-9999 and you wanted to pull out just the 3-digit prefix?
This UDF takes as arguments the text string, the number of the element you want to grab (n),
and the delimiter as a string (eg. "-"). The syntax for this example user defined function in Excel
is:
=GetElement(t ext ,n,del i mi t er )
Example: If B3 contains "1-800-333-4444", and cell C3 contains the formula, =GetElement
(B3,3,"-"), C3 will then equal "333". To turn the "333" into a number, you would use =VALUE
(GetElement(B3,3,"-")).
> Yearly Calendar
> ... Links ...





http://www.vertex42.com/ExcelArticles/user-defined-functions.html (2 of 4) [1/5/2007 8:50:02 PM]
How to Create Custom Excel Functions. User Defined Function (UDF) Examples for Excel.
Function GetElement(text As Variant, n As Integer, _
delimiter As String) As String
'Returns the nth element from a delimited text string
Dim txt, str As String
Dim count, i As Integer

'Manipulate a copy of the text string
txt = text

'If a space is used as the delimiter, remove extra spaces
If delimiter = Chr(32) Then txt = Application.Trim(txt)

'Add a delimiter to the end of the string
If Right(txt, Len(txt)) <> delimiter Then
txt = txt & delimiter
End If

'Initialize count and element
count = 0
str = ""

'Get each element
For i = 1 To Len(txt)
If Mid(txt, i, 1) = delimiter Then
count = count + 1
If count = n Then
GetElement = str
Exit Function
Else
str = ""
End If
Else
str = str & Mid(txt, i, 1)
End If
Next i
GetElement = ""
End Function
Example #3: UDF for a Custom Mathematical Formula
One of the nice things about custom Excel functions is that you can simplify Excel formulas that
would otherwise use nested If...Then... statements. As an example, let's say we have a simple
function that includes division, but the formula changes when the divisor is zero. Also, we
want to do some error checking, so we don't end up with #VALUE all over our spreadsheet.
For this example, we'll look at the KEI formula (Keyword Effectiveness Index), which when
simplified looks something like this when using built-in Excel functions:
=IF(supply=0,demand^2,demand^2/supply)
The syntax for the custom user defined function is:
=KEI(demand,suppl y,[def aul t _val ue])
Function KEI(demand As Variant, supply As Variant, _
Optional default_value As Variant) As Variant
'Keyword Effectiveness Index (KEI)
If IsMissing(default_value) Then
http://www.vertex42.com/ExcelArticles/user-defined-functions.html (3 of 4) [1/5/2007 8:50:02 PM]
How to Create Custom Excel Functions. User Defined Function (UDF) Examples for Excel.
default_value = "n/a"
End If
If IsNumeric(demand) And IsNumeric(supply) Then
If supply = 0 Then
KEI = demand ^ 2
Exit Function
Else
KEI = demand ^ 2 / supply
Exit Function
End If
End If
KEI = default_value
End Function
More Custom Excel Function Examples
Rounding Significant Figures in Excel :: Shows how to return #NUM and #N/A error values
There are certainly many more examples of UDF's for Excel. Again, I would strongly recommend
John Walkenbach's book, Excel 200X Formulas. But, if you are looking for examples on the
internet, you may want to check out the following websites:
User Defined Function Examples - www.ozgrid.com
Examples of user defined functions or UDF's for Excel written in VBA. Random numbers, Hyperlinks, count sum or sort by
colors.

UDF Examples and Tips - www.exceltip.com
Writing Your First VBA Function in Excel. Area of a rectangle (perhaps a little too simple), fuel consumption, and other info about
UDF's.

Build an Excel Add-In - http://www.fontstuff.com/vba/vbatut03.htm
An excellent tutorial that takes you through building an add-in for a custom excel function.

CITE THIS ARTICLE AS:
Wittwer, J.W., "How to Create Custom User Defined Excel Functions" From Vertex42.com, January, 2004, http://www.
vertex42.com/ExcelArticles/user-defined-functions.html
[ Home | Sitemap | Support | About/Contact Us | Privacy | Legal Stuff ]
2003 Vertex42, LLC All rights reserved. Custom Excel Functions
http://www.vertex42.com/ExcelArticles/user-defined-functions.html (4 of 4) [1/5/2007 8:50:02 PM]

Você também pode gostar