Yes, you can return objects like Ranges, Shapes, or even other UserForms from a VBA function by declaring the return type as Object or Variant and using the Set keyword to assign the reference. This allows you to write compact, reusable code that acts like a built-in Excel function, such as retrieving a specific cell range or a chart object dynamically based on inputs.

What You'll Need

  • Microsoft Excel installed (2010 or later versions are recommended for modern VBA features).
  • The Developer tab enabled in the Ribbon (if not, go to File > Options > Customize Ribbon and check the box).
  • A basic understanding of how to open the VBA Editor (press Alt + F11).

Step-by-Step

  1. Open the VBA Editor: Launch Excel and press Alt + F11 on your keyboard to open the Visual Basic for Applications editor. Alternatively, go to the Developer tab on the Ribbon and click Visual Basic.
  2. Create a New Module: In the VBA Editor, right-click on any existing project in the Project Explorer on the left side. Select Insert > Module. This creates a new code window where you can write your function.
  3. Define the Function: In the new module, start typing the function declaration. To return an object, use the Object data type or the Variant data type. For example: Public Function GetRange(cellAddress As String) As Object. The Public keyword ensures the function is visible to other modules, while cellAddress is the argument passed to it.
  4. Assign the Object Reference: Inside the function body, use the Set keyword to assign a valid object reference to the function name. This is a critical step; without Set, the function returns a Nothing value. For example: Set GetRange = Range(cellAddress). This line takes the string address (like "A1") and converts it into a Range object, which is then assigned to the function.
  5. Handle Errors: Add an error handler to manage cases where the address is invalid. Wrap the assignment in an On Error GoTo block. For example: On Error GoTo InvalidAddress. Then, add a label like InvalidAddress: where you can set the function to return Nothing or a default object if the address is not found.
  6. Return from the Function: Ensure the function ends with the assignment to the return variable and the error handling label. The function should look like this: Public Function GetRange(cellAddress As String) As Object On Error GoTo InvalidAddress Set GetRange = Range(cellAddress) Exit Function InvalidAddress: Set GetRange = Nothing End Function.
  7. Use the Function in a Worksheet: Go back to your Excel worksheet. In a cell, type =GetRange("B2") and press Enter. The function will return the Range object associated with cell B2. You can then use this range in formulas like =GetRange("B2").Value to get the value, or =GetRange("B2").Interior.Color to get the background color.
  8. Test Different Objects: Modify the function to return other types of objects. For example, to return a Shape, use Set GetShape = ActiveSheet.Shapes("Rectangle1"). To return a Chart, use Set GetChart = ActiveSheet.ChartObjects("Chart1"). The key is to ensure the object exists before assigning it to the function.

Common Mistakes

  • Forgetting the Set Keyword: The most common error is trying to assign an object reference without the Set keyword. This causes the function to return Nothing. Always use Set when assigning references to objects.
  • Returning Nothing Instead of an Object: If the object you are trying to return does not exist (e.g., a shape with a name that doesn't exist), the function will return Nothing. This can cause runtime errors in the calling code if it tries to access properties of Nothing. Always check for the existence of the object before returning it.
  • Using the Wrong Data Type: Declaring the return type as Integer or String will not work for objects. You must use Object or Variant to allow the function to hold an object reference.
  • Modifying the Returned Object in Place: If you modify the returned object in the calling code, it will also modify the original object in the worksheet. For example, if you set GetRange("A1").Value = 10, the value in cell A1 will change. This is usually the desired behavior, but be aware of it.

Tips

  • Use Variant for Maximum Flexibility: While Object is specific, Variant can also hold objects and other data types. This can be useful if you want a function that can return either a Range or a String depending on the input.
  • Check for Nothing in the Calling Code: Before using the returned object, check if it is Nothing. This prevents runtime errors. For example: Dim myRange As Object Set myRange = GetRange("InvalidAddress") If Not myRange Is Nothing Then MsgBox myRange.Address Else MsgBox "Address not found" End If.
  • Optimize Performance for Large Ranges: If you are returning a Range object, consider using the Value property to return a copy of the data instead of the object itself. This can improve performance when working with large datasets. For example: Public Function GetRangeValue(cellAddress As String) As Variant Set GetRangeValue = Range(cellAddress).Value End Function.
  • Document Your Function: Use comments to explain what the function does, what arguments it takes, and what it returns. This makes your code easier to understand and maintain. For example: ' Returns the Range object for the specified address. Returns Nothing if invalid..

Troubleshooting

If the function returns #VALUE! or #REF! in the worksheet, it usually means the function did not return a valid range or object. Ensure that the cell address is spelled correctly and that the sheet is active. If the function returns Nothing, check the error handling code to ensure that the object assignment is wrapped in the On Error GoTo block. If you are getting a runtime error 91 (Object variable or With block variable not set), it is likely because you are trying to access a property of a Nothing object. Always check if the object is Nothing before using it.

Frequently Asked Questions

Can I return a UserForm from a VBA function?

Yes, you can return a UserForm object, but it is generally not recommended for direct use in worksheet formulas. You would typically show the form using the Show method on the returned object.

Why does my function return Nothing?

Your function returns Nothing if the Set keyword is missing, if the object you are trying to return does not exist, or if an error occurs before the assignment. Check your code for these issues.

Is it better to return a Range or a Variant?

Returning a Range is more specific and can be faster if you need to manipulate the object directly. Returning a Variant is more flexible if you need to return different types of data. Choose based on your specific needs.

Can I use this function to return a PivotTable?

Yes, you can return a PivotTable object, but similar to UserForms, it is not typically used in worksheet formulas. You would usually manipulate the PivotTable through VBA code after returning the object.

What happens if I modify the returned object?

If you modify the returned object, the changes will be reflected in the original object in the worksheet. This is because the function returns a reference to the existing object, not a copy.

Can I return a collection or array from a function?

Yes, you can return a Collection or an Array from a function, but these are not objects in the strict sense of the VBA Object Model. They are data structures that can be returned using the Set keyword or by value.