210 likes | 299 Views
Excel User Functions. Writing your own Excel user function. Excel provides over 400 functions to users But sometimes it would be very convenient to have a function which is not provided
E N D
Writing your own Excel user function • Excel provides over 400 functions to users • But sometimes it would be very convenient to have a function which is not provided • In our example (in workbook UserFunctionDemo) , we have a function that finds the middle value of three numbers • The first step is to create a module for the function
Mac vs Windows • The process on the Mac is almost exactly the same • I’ve inserted some slides at the end to show how it looks on the Mac, and made a separate video • The one difference I’ve found is that the user functions you write don’t show up in the function list the way they do on Windows
A User Function goes in a Module Instead of a UserForm, insert a Module
Change the Module Name and Type the Code Use the Name property in the property box
The name of my function shows up in the list of completions provided by Excel
To Add A Description… • Users find it helpful to see a description of what the function does • To provide one, click the macros icon (continued…)
Type your macro name at the top (it’s not there because it’s not a workbook macro)
Type a helpful description and click OK If you give your macro a shortcut key, make sure it is not the same key used for something else really useful like control X, V, C or similar
Another nice example • I got this one from the website exceltip.com • It was contributed by Martin Green, an Excel consultant • The idea: If you give Excel’s Weekday function a date, it will give you a number from 1 to 7 representing the day. You want to have a macro return a day name instead of a number • This is also implemented in workbook UserFunctionDemo
Here’s the code (most of it) FunctionDayName(inputDateAs Date) As String DimdayNumberAs Integer 'we know this number is always small dayNumber = Weekday(inputDate, vbSunday) '*** Use Select Case to choose the dayname based on the number Select Case dayNumber Case 1 DayName = "Sunday" Case 2 DayName = "Monday" … Case 7 DayName = "Saturday" End Select End Function
A few comments… • Giving the type of the value returned, as we did here, seems to be optional, even with Option Explicit in force FunctionDayName(inputDateAs Date) As String • The definition ends with End Function instead of End Sub, as it would with a sub procedure • This is a nice example of where the Select Case conditional gives clear, readable code • Weekday is an Excel function; the second argument is a constant that tells Excel we want 1 to represent Sunday
Rename the Module using the Properties window I named it MyFunction
In the Developer Tab, choose Macros… Type the macro name and choose Options, then type the description
Go to Excel and Use Your Function! I used my function Middle in a formula for cell A4.