2

I'm trying to build a function that will take an input cell (say "B5") and return a range object that refers to a table (of which the supplied cell is the top-right entry)

Sub Macro1()
Dim testCell As Range

testCell = Worksheets("HMA").Range("B5")
ReturnTable testCell

End Sub

Function ReturnTable(cell As Range)
    firstcell = cell
    lastrow = firstcell.End(x1Down)
    Table = Range(firstcell, lastrow + 5).Value
End Function

I've been running into a lot of problems here, and I feel like I'm missing something simple. The error that I'm getting is "Object Required" at the lastRow line.

Looking through it in debug mode I see that testCell is assigned the value of the range object (I assume this is the default). What am I missing here?

Is my approach even sound? Should I be looking at solving this problem in a different way?

1
  • 2
    You need to use Set when assigning the value of testCell (or any other object variable), otherwise you're assigning the default property of the range (in this case .Value) Commented Mar 26, 2013 at 16:13

2 Answers 2

4

The End returns a Range object, so, lastrow must be a range variable.

Function ReturnTable(firstcell as Range) as Range 'add this as range to tell the result of the function is a range
    dim LastCell as Range
    Set LastCell = firstcell.END(xldown)
    Set ReturnTable = Range(firstcell, lastcell) 'must use the same name of the function
End Function

If you want 5 cells below lastcell, use LastCell.Offset(5,0)

And in Macro1, you probably will want something like

Set SomeVar = ReturnTable(testcell)
Sign up to request clarification or add additional context in comments.

Comments

3

When you assign Objects (like Range) you have to use "Set".

If you assign Range without "Set" VBA will assign the value of the Range and not the Range itself.

Set testCell = Worksheets("HMA").Range("B5")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.