VBA For Microsoft Excel - Functions: 1.3 Testing The Function
VBA For Microsoft Excel - Functions: 1.3 Testing The Function
Page 1 of 4
City Short Courses
NetPay is how much you take home after IncomeTax, National Insurance and
Or from the Formulas tab,
Pension Fund contributions have been deducted.
choose the InsertFunction
button, The arithmetic would look like this in code:
Deductions = (GrossPay * IncomeTax) _
choose UserDefined + (GrossPay * NI) _
+ (GrossPay * Pension)
from the dropdown, NetPay = GrossPay - Deductions
select the function
from the list and The full function would look like this:
click OK
Function NetPay _
(GrossPay As Single, IncomeTax As Single, _
NI As Single, Pension As Single) As Single
Dim Deductions As Single
Deductions = (GrossPay * IncomeTax) + _
In the next step click in the textbox and click the cell that contains the radius, (GrossPay * NI) + _
then click OK (GrossPay * Pension)
NetPay = GrossPay - Deductions
End Function
Note that NetPay is the return value for the function and the function name.
1. To insert the function, select a cell and choose the Insert Function icon
from the Formulas tab
2. Choose the User Defined category and select NetPay and click OK
3. Put the cell references into the textboxes and click OK
Page 2 of 4
City Short Courses
As another example, you could write a function which named PriceChange You can make use of the Union operator (,) with the arguments to the function
to calculate the percentage change in a share price. The function might look as ActiveCell = WorksheetFunction.Average(Range(“B2:B9”), Range(“D2:D9”))
follows: The limitation with WorksheetFunction is that the functions don’t recalculate
Function PriceChange (opening As Single, closing As Single) unless you re-run the macro - for dynamic data, it is better to use Excel’s
As Single formulas. On the other hand these statements are quicker to run than a
PriceChange = (closing - opening) / opening solution that uses loops
End Function
You might put the return value into a variable e.g.,
It really doesn’t matter what you call the arguments, as long you use them in a variable = WorksheetFunction.Sum(Selection)
way that is consistent with the logic of the function. However the variable
Sub SumNumbersInSelection()
containing the return value must have the same name as the Function itself. Dim Total As Single
You can type the function into the Excel interface like so: Total = WorksheetFunction.Sum(Selection)
Range(“C12”) = Total
MsgBox "The sum of numbers in the selection is " _
& Total
End Sub
3 VBA functions
VBA provides many inbuilt functions, some of which are the same as in Excel. Here is
a selection.
Page 3 of 4
City Short Courses
Page 4 of 4