Question posted 2009 · +15 upvotes
I seem to be getting a type mismatch error when trying to do something like this:
In new workbook:
A1 B1
5 4
Function Test1() As Integer
Dim rg As Range
Set rg = Test2()
Test1 = rg.Cells(1, 1).Value
End Function
Function Test2() As Range
Dim rg As Range
Set rg = Range("A1:B1")
Test2 = rg
End Function
Adding =Test1() should return 5 but the code seems to terminate when returning a range from test2(). Is it possible to return a range?
Accepted answer +36 upvotes
A range is an object. Assigning objects requires the use of the SET keyword, and looks like you forgot one in your Test2 function:
Function Test1() As Integer
Dim rg As Range
Set rg = Test2()
Test1 = rg.Cells(1, 1).Value
End Function
Function Test2() As Range
Dim rg As Range
Set rg = Range("A1:B1")
Set Test2 = rg '<-- Don't forget the SET here'
End Function
Top excel-vba Q&A (6)
- How to clear the entire array? +58 (2010)
- How to change Format of a Cell to Text using VBA +55 (2011)
- Download attachment from Outlook and Open in Excel +43 (2012)
- 2 Dimensional array from range +34 (2013)
- Hiding an Excel worksheet with VBA +33 (2009)
- How do I slice an array in Excel VBA? +31 (2008)
excel-vba solutions on this site
— top 3%.