2013-03-26 65 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