将范围对象传递给excel-vba中的函数 – 接收“Object Required”错误
我试图build立一个函数,将采取一个input单元格(说“B5”),并返回一个范围对象引用一个表(其中提供的单元格是右上angular的条目)
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
我在这里遇到了很多问题,我觉得我错过了一些简单的东西。 我得到的错误是在最后一行“对象需要”。
在debugging模式下看它,我看到testCell被赋予了范围对象的值(我认为这是默认值)。 我在这里错过了什么?
我的方法听起来甚么? 我应该以不同的方式解决这个问题吗?
End返回一个Range对象,所以,lastrow必须是一个范围variables。
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
如果你想要lastcell下面的5个单元格,使用LastCell.Offset(5,0)
在Macro1中,你可能会想要类似的东西
Set SomeVar = ReturnTable(testcell)
当你分配对象(如范围),你必须使用“设置”。
如果您在没有“设置”的情况下分配范围,VBA将分配范围的值而不是范围本身。
Set testCell = Worksheets("HMA").Range("B5")