• Skip to main content
  • Skip to header right navigation
  • Skip to site footer

My Online Training Hub

Learn Dashboards, Excel, Power BI, Power Query, Power Pivot

  • Courses
  • Pricing
    • SALE 20% Off All Courses
    • Free Courses
    • Power BI Course
    • Excel Power Query Course
    • Power Pivot and DAX Course
    • Excel Dashboard Course
    • Excel PivotTable Course – Quick Start
    • Advanced Excel Formulas Course
    • Excel Expert Advanced Excel Training
    • Excel Tables Course
    • Excel, Word, Outlook
    • Financial Modelling Course
    • Excel PivotTable Course
    • Excel for Customer Service Professionals
    • Multi-User Pricing
  • Resources
    • Free Downloads
    • Excel Functions Explained
    • Excel Formulas
    • Excel Add-ins
    • IF Function
      • Excel IF Statement Explained
      • Excel IF AND OR Functions
      • IF Formula Builder
    • Time & Dates in Excel
      • Excel Date & Time
      • Calculating Time in Excel
      • Excel Time Calculation Tricks
      • Excel Date and Time Formatting
    • Excel Keyboard Shortcuts
    • Excel Custom Number Format Guide
    • Pivot Tables Guide
    • VLOOKUP Guide
    • ALT Codes
    • Excel VBA & Macros
    • Excel User Forms
    • VBA String Functions
  • Members
    • Login
    • Logout
    • Password Reset
  • Blog
  • Excel Webinars
  • Excel Forum
    • Register as Forum Member

Return An Array From A UDF

You are here: Home / Excel VBA / Return An Array From A UDF
Return an array from a udf
January 31, 2017 by Philip Treacy

This post is going to look at how to return an array from a udf. My last post looked at how to return a range from a UDF and in that, I included a small, bonus function which gave you the interior color of a cell.

I'm going to modify that function so it becomes an array function, or an array formula as they are also known. Specifically it will become a multi-cell array function as it will return multiple values into multiple cells.

What is an Array?

An array is just a list of values, e.g. 1, 2, 3, 4, 5 is an array with 5 values, or elements

That was an example of a one dimensional array. Think of one dimension representing values along a straight line, like the x-axis on a chart.

A two dimensional array holds values that can be used to represent something that requires two things to identify it, e.g. the x and y co-ordinates on a chart, the squares on a chess board, or even the cells on your worksheet (A1, etc).

Three dimensional arrays contain three lists of values used to identify something (the xyz co-ordinates) perhaps the latitude, longitude and height above sea level of a point on the Earth's surface.

You can have more dimensions of course if you need them, but for my example we're sticking with just one.

XYZ Axes

Returning Arrays of Different Sizes

In order to process an unknown number of values, we need to work out how many values are passed into our function and then allocate the appropriate amount of storage in an array.

Initially we allocate an unknown amount of storage space for the array named Result():

    Dim Result() As Variant

Once the function is called we can work out how many cells are in the range we're passing into the function. We can do this by using Application.Caller which gives us a Range object, as long as our function is called from a cell. This range is the range of cells passed into the function.

We can work out how many cells in the range and whether we're passing a row or a column into the function

    With Application.Caller
        CallerRows = .Rows.Count
        CallerCols = .Columns.Count
    End With

If CallerRows > 1 then a column is being passed into the function.

Caller Rows

If CallerCols > 1 then a row is being passed into the function.

Caller Columns

The number of cells in the range is CallerRows * CallerCols, so we redimension the array to hold a value for each of those cells.

    'ReDimension the array to fit all the elements (cells)
    ReDim Result(1 To CallerRows * CallerCols)

If we pass in a range containing 6 cells, then our result will contain 6 values. Remember that this function is only dealing with one dimensional arrays, that is, values either in a row or a column.

If we pass in a range containing 10 cells, but allocate less than 10 cells for the result, we'll get #VALUE! errors.

Not enough Cells for Array Result


If we pass in 6 cells, and allocate more than 6 cells for the result, cells 7 onwards will be filled with 0.

Too Many Cells for Array Result

How you choose to deal with this is up to. You can write your own error handling, or just let Excel deal with it.

Don't Forget

This is an array formula, so when you enter it you must use CTRL+SHIFT+ENTER. That is, hold down CTRL and SHIFT, then press ENTER.

Fixed Sized Arrays

If you know the number of elements in your array will be fixed you can specify this and not worry about working it out when the function is called, For example, here's a 10 element array:

Dim myResult(1 To 10) As Variant

But passing in a range with more or less than 10 elements could easily break your function.

Array Orientation

By default a function will return an array as a row. If you want the results to go into a column, you need to transpose the array

    'Transpose the result if returning to a column
    If CallerRows > 1 Then
    
        GetColor = Application.Transpose(Result)
        
    Else
    
        GetColor = Result
    
    End If

Download the Workbook

Enter your email address below to download the sample workbook.

By submitting your email address you agree that we can email you our Excel newsletter.
Please enter a valid email address.

Here's a link to download a workbook with sample code and examples.

Return an array from a udf

More User Defined Function Posts

writing udfs in excel with python

Writing UDFs in Excel With Python

Write Excel UDFs in Python. Use the power of the vast Python libraries for data science, statistics, web scraping or database connectivity.
Return a range from a UDF

Return a Range from a UDF

If you return a range from a UDF this allows you to use that range in other functions and calculations.
create an excel add-in for user defined functions udfs

Create an Excel Add-In for User Defined Functions (UDF’s)

How to create an Excel add-in for user defined functions (UDF's) to make them easier to use.
creating a reference to personal.xlsb for user defined function udf

Creating a Reference to PERSONAL.XLSB for User Defined Functions (UDF’s)

How to create a reference to PERSONAL.XLSB so that using User Define Functions (UDF's) is easier
Creating Multi-Function UDF's

Creating Multi-Function UDF’s

Combine separate functions into one, multi function UDF (user defined function)

Creating a UDF (User Defined Function) in Excel

Create your own functions in Excel

More Excel VBA Posts

Display All Matches from Search in Userform ListBox

Display All Matches from Search in Userform ListBox

Search a range for all partial and full matches of a string, and display matching records (entire rows) in a userform listbox. Sample code and userform.
animating excel charts

Animating Excel Charts

Use animation correctly to enhance the story your data is telling. Don't animate your chart just for some eye candy. Sample code and workbook to download.
dynamic data validation lists in userforms

Dynamic Data Validation Lists in Userforms

Data validation lists using the same source that are dynamically modified to prevent the same choice being made in each list.
show report filter pages for power pivot pivottables

Show Report Filter Pages for Power Pivot PivotTables

PivotTables created from Power Pivot can't use the 'Show Report Filter Pages' option. But this piece of VBA allows you to do just that.
charting real time data in excel

Charting Real Time Data in Excel

Receive data in real time and chart the data as it arrives. Can be used to chart things like stock prices or sensor readings. Sample code and workbook
select multiple items from drop down data validation list

Select Multiple Items from Drop Down (Data Validation) List

Choose multiple items from a data validation (drop down) list and store them all in the same cell. Sample workbook with working VBA.
Excel Calendar (Date Picker) to Use in Worksheets and Userforms

Multi-Language Excel Calendar (Date Picker) for Worksheets and Userforms

Easy to use, highly customizable and multi-language. This date picker is implemented as a userform that is simple to integrate into your workbook.
automating and emailing pivot table reports

Automating and Emailing Pivot Table Reports

Automate the creation and distribution of pivot table reports with some VBA. Send reports to multiple email recipients using Outlook.
search for data with userform

Searching for Data With a User Form

Search a list of records (like a table) using a user form, and then populate the fields of the search form when the record is found.
Checking values in range objects with vba

Checking Values in Range Objects With VBA

Use built in tools or your own code to examine the values contained within Range objects in VBA. Sample code to download.




Category: Excel VBATag: user defined function
Previous Post:Return a range from a UDFReturn a Range from a UDF
Next Post:Excel Conditional Formatting to Highlight MatchesExcel Conditional Formatting Thumb

Reader Interactions

Comments

  1. Stephen

    February 1, 2017 at 8:23 pm

    Interesting, thanks. Your solution is well on the way towards something that has always bothered me …

    When charting data from a list or table, there is no way to accumulate the values as part of the charting process. OK, I obviously just insert a helper column that accumulates the values and chart that. Simple enough, but you’d think there would be an option built into Excel’s charting system.

    Helper columns always seem like clutter to me, especially for something so simple. So I attempted to create a UDF several years back, intending to insert it manually into the ‘formula’ created for the chart and make the accumulation happen, but it was beyond my knowledge/abilities.

    It would be nice to see a solution to this unfinished business, though I can’t remember why it was so important at the time!

    Thanks for the interesting articles – I get them by RSS feed and email.

    Reply
    • Mynda Treacy

      February 2, 2017 at 5:41 pm

      Hi Stephen,

      I’m not sure I follow what you want to do. Are you wanting the chart to have an automatic option to plot a cumulative value based on a series already in the chart? Perhaps you could share an example file so we can better understand what you’re after.

      Cheers,

      Mynda

      Reply
      • Stephen

        February 17, 2017 at 10:28 pm

        Mynda

        Yes to the automatic option, but only the cumulative values need to be in the chart (versus date). A simple example where this is useful would be a record of miles travelled by car. Each row would have the miles for a single trip, with the date. The chart should plot the total mileage versus the date. I know it’s easy to create an extra helper column, but …

        This could also be useful for time or money spent on a project.

        I’ve a horrible feeling you’re going to tell me there’s a check box I’ve never noticed 😉

        Regards

        Stephen

        Reply
        • Mynda Treacy

          February 19, 2017 at 2:44 pm

          Hi Stephen,

          Thanks for clarifying. I’d use a PivotTable to first summarise the data in your table into total by date, then insert a Pivot Chart to display the total miles per date.

          Hope that helps.

          Mynda

          Reply
          • Stephen

            February 21, 2017 at 1:13 am

            Thanks Mynda. PivotTable, Power Pivot and PowerQuery are such powerful additions to Excel.

            Thanks for all your help
            Stephen

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Current ye@r *

Leave this field empty

Sidebar

More results...

Course Sale

mynda treacy microsoft mvpHi, I'm Mynda Treacy and I run MOTH with my husband, Phil. Through our blog, webinars, YouTube channel and courses we hope we can help you learn Excel, Power Pivot and DAX, Power Query, Power BI, and Excel Dashboards.

Subscribe to Our Newsletter

Receive weekly tutorials on Excel, Power Query, Power Pivot, Power BI and More.

We respect your email privacy

Guides and Resources

  • Excel Keyboard Shortcuts
  • Excel Functions
  • Excel Formulas
  • Excel Custom Number Formatting
  • ALT Codes
  • Pivot Tables
  • VLOOKUP
  • VBA
  • Excel Userforms
  • Free Downloads

239 Excel Keyboard Shortcuts

Download Free PDF

Free Webinars

Excel Dashboards Webinar

Watch our free webinars and learn to create Interactive Dashboard Reports in Excel or Power BI

Click Here to Watch Now

Blog Categories

  • Excel
  • Excel Charts
  • Excel Dashboard
  • Excel Formulas
  • Excel PivotTables
  • Excel Shortcuts
  • Excel VBA
  • General Tips
  • Online Training
  • Outlook
  • Power Apps
  • Power Automate
  • Power BI
  • Power Pivot
  • Power Query
trustpilot excellent rating
 

Company

  • About My Online Training Hub
  • Disclosure Statement
  • Frequently Asked Questions
  • Guarantee
  • Privacy Policy
  • Terms & Conditions
  • Testimonials
  • Become an Affiliate

Support

  • Contact
  • Forum
  • Helpdesk – For Technical Issues

Copyright © 2023 · My Online Training Hub · All Rights Reserved

Microsoft and the Microsoft Office logo are trademarks or registered trademarks of Microsoft Corporation in the United States and/or other countries. Product names, logos, brands, and other trademarks featured or referred to within this website are the property of their respective trademark holders.