BLOGS BY TOPIC
BLOGS BY AUTHOR
BLOGS BY YEAR
On-line training in writing functions using VBA, for use either within other VBA programs or within Excel itself.
- Writing and Using Functions in Excel Visual Basic
- Examples of a Function to Make Coding Easier
- Writing Functions for Use within Excel VBA (this blog)
Posted by Andy Brown on 24 February 2012
You need a minimum screen resolution of about 700 pixels width to see our blogs. This is because they contain diagrams and tables which would not be viewable easily on a mobile phone or small laptop. Please use a larger tablet, notebook or desktop computer, or change your screen resolution settings.
Writing Functions for Use within Excel VBA
Suppose you want to work out how tall you are in metres, given your height in feet and inches (these are weird, archaic units of measurement still commonly used in the UK - you don't need to understand what they are to use this example).
The VBA for our Function
Our Excel spreadsheet should look like this:
Type in the formula:
The Metres function should take in two arguments:
- The person's height in whole feet; and
- The residual number of inches
and return the number of metres. Here's some code which would do this:
Function Metres(Feet As Single, Inches As Single) As Single
Const MetresPerInch As Single = 0.0254
Const InchesPerFoot As Integer = 12
'first work out how may inches tall the person is
Dim TotalInches As Single
TotalInches = Feet * InchesPerFoot + Inches
'now return number of metres
Metres = MetresPerInch * TotalInches
Using the Function within Excel
You can type in this function within Excel, but it's more fun to use the function wizard:
Click on the cell where the answer should go, then click on the function wizard tool.
You can now choose your function:
- Choose to display user-defined functions (ie ones you've written).
- Choose the Metres function.
Here's the Insert Function dialog box with the steps shown numbered:
The Insert Function dialog box
You now - at last - have help on the arguments, and can complete the dialog box in the usual way:
Complete the dialog box by specifying which cells will provide the feet and inches.
Advanced hint: user-defined functions are "volatile". What this means is if you calculate a spreadsheet containing user-defined functions their value will always be recalculated, even if it can't possibly have changed. This means that if you use VBA functions extensively your spreadsheet calculation speed may drop.
Personally I think Excel has got all of the functions I need, and I only ever use VBA functions within code to make programming easier.