User defined array functions in Excel

Many languages have functions to process lists (array). These functions usually return a list, so you can pass that to another list function. This chaining of functions is really powerful.

UNIX provides this sort of chaining capability. If I had a cities (with some repetitions) and I wanted to find out how many started with the letter 'A', I'd just type:

cat cities | sort | uniq | grep "^A" | wc

cat: types the cities.
sort: sorts the cities alphabetically.
uniq: finds unique cities (works only if sorted - that's why we had to sort the list).
grep: filters the cities. Only allows cities beginning with A.
wc: word count

To do this on Excel, the only way is to

  1. get the unique values. Data - Filter - Advanced Filter, and select "Unique records only", "Copy the list to another location", and select a location
  2. get the first letter. =LEFT(cell,1) returns the first letter of the cell.
  3. count the number of "A"s. =COUNT(range, "A") counts the number of "A"s.

But ideally, I'd like a 1-line formula like

=LENGTH(UNIQUE(GREP("^A", range)))

Excel doesn't provide these functions by default, but you can add them as user defined functions. Doing this lets you condense several cells into one. Instead of having to copy all your data into a set of unique values, and then adding a column for the first cell, the entire operation can be condensed into one formula.

I consider the following functions the a basic set for list processing.

I created these UDFs. You can download the functions and play with them. Below are some tasks that you can do with them, that are difficult otherwise.

This is a small sample. The power of list processing is phenomenal, especially when combined with array formulas. Download these macros and play with them!


Excel 2003 Power Programming with VBA (Excel Power Programming With Vba) Professional Excel Development: The Definitive Guide to Developing Applications Using Microsoft(R) Excel and VBA(R) (The Addison-Wesley Microsoft Technology Series) VBA and Macros for Microsoft Excel (Business Solutions) Advanced modelling in finance using Excel and VBA

Written on 23 Feb 2007

Comments


(not shared, not spammed)


S Anand, Infosys Consulting, London UK. +44 7957 440 260