2013-03-26 427 views
1

我试图构建一个函数,它将接受输入单元格(比如“B5”)并返回一个引用表的范围对象(其中所提供的电池是右上角的条目)将范围对象传递给excel-vba中的函数 - 接收“Object Required”错误

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 

我已经运行到了很多的问题,在这里,我觉得我失去了一些东西简单。我得到的错误是lastRow行中的“Object Required”。

在调试模式下查看它我看到testCell被分配了范围对象的值(我认为这是默认值)。我在这里错过了什么?

我的方法甚至听起来吗?我应该以不同的方式解决这个问题吗?

+2

您需要使用分配testCell的值(或任何其他对象变量)的时候'Set',否则你指定的范围内的默认属性(在这种情况下'.Value') – 2013-03-26 16:13:05

回答

3

End返回一个Range对象,所以,lastrow必须是一个范围变量。

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 

如果你想5个单元下方lastcell,使用LastCell.Offset(5,0)

而在宏1,你可能会想是

Set SomeVar = ReturnTable(testcell) 
+0

优秀,感谢您的信息。这工作很好 – user1860694 2013-03-26 16:25:34

3

当分配对象(如范围),你必须使用“组”。

如果您在没有“设置”的情况下分配范围,VBA将分配范围的值而不是范围本身。

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

感谢您的意见,我现在明白了。 – user1860694 2013-03-26 16:25:50