Tuesday, January 4, 2011

Creating Easy to Use Functions Customized through Excel VBA

Have you ever encountered a ridiculously long function where it is way too difficult to figure out?  Take the following:

=IF(B3>1,IF(D3<0,IF(E3="",G3+1,0),G3-1),H3)

You can walk through the steps of the above formula but then the next time you wish to adapt it you will have to decipher this once more.  .

User-defined functions can simplify things for you by creating the labels that make sense for the formula while leaving the complexities of all the if/then logic behind the scenes.  An example would be as follows:

Function Order(Confirmed, Qty, Price, TaxRate)
If Confirmed = Yes then
                        Order = Qty * Price * TaxRate
            Else
                        Order = 0
End If
End Function

When the user clicks on the fx from the formula bar and selects from the category User Defined and choose Order from the list of functions below they will see the following:
After hitting ok, the formula will appear as follows: 
Imagine how you can incorporate user-defined functions within a VBA script that defines which fields it references or what values to use.

No comments: