• 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
    • 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
    • Excel for Operations Management Course
    • Excel for Decision Making Under Uncertainty Course
    • Excel for Finance Course
    • Excel Analysis ToolPak Course
    • 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
  • Blog
  • Excel Webinars
  • Excel Forum
    • Register as Forum Member

Return a Range from a UDF

You are here: Home / Excel VBA / Return a Range from a UDF
Return a range from a UDF
January 24, 2017 by Philip Treacy

I've previously written a UDF to count colored cells and then perform various maths functions on the values in those cells, like SUM, AVERAGE or COUNT.

In this post I'm going to rewrite that code so that we can return a range from a UDF. This range contains all the cells that match the reference color, and you can then use this range in other functions and calculations.

I had already planned to do this, but following a comment on the last post, Catalin (our support guru) posted his code which does the same job, so some of the credit must go to him too.

The UDF

The UDF is called FindColors and is really a pretty straightforward few lines of VBA:

'
' Written by Philip Treacy
' myonlinetraininghub.com/return-a-range-from-a-udf
'

Function FindColors(InputRange As Range, ReferenceCell As Range) As Range
    
    Dim ReferenceColor As Long
    Dim Cell As Range, Result As Range
     
    ReferenceColor = ReferenceCell.Interior.Color
        
    For Each Cell In InputRange

        If Cell.Interior.Color = ReferenceColor Then
            
            If Result Is Nothing Then
                
                Set Result = Cell
                
            Else

                Set Result = Union(Result, Cell)

            End If

        End If

    Next Cell
    
    Set FindColors = Result

End Function

All we need to do is check each cell in the InputRange sent to the function, to see if that cell has the same background color as our ReferenceCell.

A regular old For ... Next loop does this job for us.

UNION

If we find cells that match the color of our ReferenceCell, we use the UNION operator to join these separate cells together into a single range.

Set Result = Union(Result, Cell)

Returning the Resulting Range

The last thing to do is return the result of the function, which is the range of colored cells matching our ReferenceCell.

But, because we are returning a range object we must Set the function result like so:

Set FindColors = Result


Using the UDF Result

If you want to find the SUM of all cells colored the same as B9, and where ColoredCells is a named range, you'd enter this in a cell:

=SUM(FindColors(ColoredCells,B9))

Download a Sample Workbook

There are several examples in the workbook you can download :

Enter your email address below to get the workbook.

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

download iconDownload the Excel Workbook.

examples using range returned by udf

A Word on Recalculation

If you change the background color of the cell using the Ribbon (or a couple of other ways), the function output is not recalculated. That's just the way Excel works and I wrote about this in a previous post - check the section headed Recalculation.

Bonus Function - GetColor

This was in the previous workbook too, but I didn't mention it.

Use this function to get the hex value of a cell's background color. Or to check that certain cells all have the same color.

To use it just call the function from a cell:

=GetColor(B9)

Check Out Other Posts on User Defined Functions

Creating a UDF

Creating Multi-Function UDF's

Creating a Reference to PERSONAL.XLSB

Creating an Excel Add-In For UDF's

Count, Sum and Average Colored Cells

Return a range 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 an array from a udf

Return An Array From A UDF

If you can return an array from a udf you are able to return multiple pieces of data and place them into multiple cells
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:locating values in large excel tablesLocating Values in Large Excel Tables
Next Post:Return An Array From A UDFReturn an array from a udf

Reader Interactions

Comments

  1. Sunny Kow

    January 24, 2017 at 4:20 pm

    Hi Philip

    Do we need to make both function volatile?

    Sunny

    Reply
    • Philip Treacy

      January 25, 2017 at 9:27 am

      Hi Sunny,

      You could, but if you change a cell color using the Ribbon (for example) this still wouldn’t trigger recalculation without pressing SHIFT+F9. If you use the Format Painter to change the cell colors, or just type new numbers into the colored cells, the functions recalculate anyway.

      Cheers

      Phil

      Reply

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...

Featured Content

  • 10 Common Excel Mistakes to Avoid
  • Top Excel Functions for Data Analysts
  • Secrets to Building Excel Dashboards in Less Than 15 Minutes
  • Pro Excel Formula Writing Tips
  • Hidden Excel Double-Click Shortcuts
  • Top 10 Intermediate Excel Functions
  • 5 Pro Excel Dashboard Design Tips
  • 5 Excel SUM Function Tricks
  • 239 Excel Keyboard Shortcuts

100 Excel Tips and Tricks eBook

Download Free Tips & Tricks

Subscribe to Our Newsletter

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

We respect your email privacy

239 Excel Keyboard Shortcuts

Download Free PDF

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.

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
microsoft mvp logo
trustpilot excellent rating
Secured by Sucuri Badge
MyOnlineTrainingHub on YouTube Mynda Treacy on Linked In Mynda Treacy on Instagram Mynda Treacy on Twitter Mynda Treacy on Pinterest MyOnlineTrainingHub on Facebook
 

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.