Create a User Defined Function (macro)


Create a User Defined Function
 Excel allows you to create custom functions, called "User Defined Functions" (UDFs) that can be used the same way you would use SUM() or some other built-in Excel function. This can be especially useful for advanced mathematics or special text manipulation. In fact, many Excel add-ins provide large collections of specialized functions.
This article will help you get started creating user defined functions with a couple of useful examples
  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 for Excel 2003 or .xlam for Excel 2007+). Then load the add-in (Tools > Add-Ins... for Excel 2003 or Developer > Add-Ins for Excel 2010+).
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 
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
  • 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(cell,[default_value])
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(text,n,delimiter)
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,"-")).
Function GetElement(text As Variant, n As Integer, _ 
                    delimiter As String) As String 
    GetElement = Split(text, delimiter)(n - 1)
End Function 


Example #3: Return the name of a month
The following function is based upon the built-in visual basic MonthName() function and returns the full name of the month given the month number. If the second argument is TRUE it will return the abbreviation.
=VBA_MonthName(month,boolean_abbreviate)
Example: =VBA_MonthName(3) will return "March" and =VBA_MonthName(3,TRUE) will return "Mar".
Function VBA_MonthName(themonth As Long, Optional abbreviate As Boolean) As Variant 
    VBA_MonthName = MonthName(themonth, abbreviate)
End Function 


Example #4: 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,supply,[default_value])

Function KEI(demand As Variant, supply As Variant, _ 
             Optional default_value As Variant) As Variant 
'Keyword Effectiveness Index (KEI) 
    If IsMissing(default_value) Then 
        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 


Here is Example of Macro:

Function deduct(money As Long)
 Dim Salary As Long
 Salary = money * 1
 Select Case Salary
    Case 0 To 200000
        deduct = 2600
    Case 200001 To 250000
        deduct = 2925
    Case 250001 To 300000
        deduct = 3575
    Case 300001 To 350000
        deduct = 4225
    Case 350001 To 400000
        deduct = 4875
    Case 400001 To 450000
        deduct = 5525
    Case 450001 To 500000
        deduct = 6175
    Case 500001 To 550000
        deduct = 6825
    Case 550001 To 600000
        deduct = 7475
    Case 600001 To 650000
        deduct = 8125
    Case 650001 To 700000
        deduct = 8775
    Case 700001 To 750000
        deduct = 8425
    Case 750001 To 800000
        deduct = 10075
    Case 800001 To 850000
        deduct = 10725
    Case 850001 To 900000
        deduct = 11375
    Case 900001 To 950000
        deduct = 12025
    Case 950001 To 1000000
        deduct = 12675
    Case 1000001 To 100000000
        deduct = 13000
 End Select
End Function

Comments

Popular posts from this blog

រូបគំនូរប្រវត្តិសាស្ត្រ ជាច្រើននៅលើជញ្ជាំងព្រះវិហារ វត្តកំពង់ធំត្រូវបានគេបង្ហាញ ក្រោយពេលវាយកំទេចចោលរាបស្មើដី

ធ្លាក់សពណ៌ត្នោត មានន័យដូចម្តេច? ស្ត្រីគ្រប់រូបគួរដឹងពីឥឡូវនេះ

ចៀសវាង ៧ចំណុចនេះពេលកក់សក់ បើមិនចង់អោយសក់ខូច