CREATING CUSTOM FUNCTIONS

Suppose your company offers a quantity discount of 10 percent on the sale of a product, provided the order is for more than 100 units. In the following paragraphs, you’ll build a function to calculate this discount. The file Treeorders.xls contains a worksheet which shows an order form that lists each item, the quantity, the price, the discount (if any), and the resulting extended price.

To create a custom Discount function in this workbook, follow these steps:

  1. Press Alt+F11 to open the Visual Basic Editor (VBE), and then choose Insert, Module. A new module appears.
  2. In the new module, enter the following code. To make the code more readable, use the Tab key to indent lines. (The indentation is for your benefit only and is entirely optional. The code will run with or without indentation.) After you type an indented line, the VBE assumes that your next line will be similarly indented. To move back out (that is, to the left) one tab character, press Shift+Tab.
        Function Discount(quantity, price)
            If quantity >= 100 Then
            Discount = quantity * price * 0.1
            Else
            Discount = 0
            End If
            Discount = Application.Round(Discount, 2)
        End Function