2011-11-24 19 views
0

我一直在嘗試各種方法來查找範圍中的最後一行並將此數字返回給子例程,但無濟於事。Excel 2011 VBA - 自定義函數來獲取最後一行的範圍

下面的代碼我有

Sub StartHere() 
    Dim oSheet As Worksheet 
    Set oSheet = WorkSheets(1) 
    ProcessData(oSheet) 
End Sub 

Sub ProcessData(ByVal wkst As Worksheet) 
    Dim rng As Range 
    Dim lastRow As Long 

    'set range 
    Set rng = wkst.Range("L:S") 'Range that i want to process data on 

    'get the last row (in Long datatype) 
    lastRow = CLng(getLastRowInRange(rng)) 

End Sub 

Function getLastRowInRange(ByRef rng As Range) 
    getLastRowInRange = rng.Cells.Find(What:="*", After:=[A1], SearchOrder:=xlByRows,_ SearchDirection:=xlPrevious).Row 
End Function 

我一直在

getLastRowInRange = rng.Cells.Find(What:="*", After:=[A1], SearchOrder:=xlByRows,_ SearchDirection:=xlPrevious).Row 

任何線索,讓球員類型不匹配?

+0

可能的重複[如何查找包含Excel中的數據的宏的最後一行?](http://stackoverflow.com/questions/71180/how-can-i-find-last-row-包含數據在Excel中的表格與宏) – GSerg

+0

嗨GSerg,不,它不是重複的。當我單獨嘗試getLastRowInRange函數時沒有問題,但是當我將它與StartHere()和ProcessData()子例程集成時遇到了問題。所以我想弄清楚我的代碼有什麼問題。 – Poliquin

+0

好的。然後看到我的答案。 – GSerg

回答

4
ProcessData(oSheet) 

Remove the parentheses

否則,您正在傳遞oSheet對象的默認屬性的值,但它沒有。雖然你應該得到「對象不支持這個屬性或方法」。

這樣做後,改函數調用:

getLastRowInRange = rng.Cells.Find(What:="*", After:=rng.Cells(1), SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row 

After必須屬於搜索範圍。 A1不屬於L:S

最後,請確保您處理Find返回Nothing(您目前不在此處,愉快地在返回的對象上調用.Row)時的情況。

+0

嗨GSerg,謝謝它的作品!順便說一句,rng.Cells(1)是指什麼?此外,我試圖刪除括號,但Excel 2011停止了它 - 錯誤。我把它放回去,它工作。 – Poliquin

+0

@ Yakult121您是否使用Mac for Excel?它可能在語法方面有所不同。 'rng.cells(1)'是'rng'的第一個單元格。 – GSerg