2016-06-29 31 views
0

我有一個電子表格,每個電子表格都有一些隨機數的部分。如何在VBA中的動態大小的行中找到最後一行?

如何找到該部分的最後一行?

實施例:

------------------------------------------------------- 
ROW 1 
------------------------------------------------------- 
ROW 2 
------------------------------------------------------- 
ROW 3 
------------------------------------------------------- 
ROW 4 
------------------------------------------------------- 
LAST ROW <-- Select last row 

然而,這可以爲每個部分,在那裏的行數是不同的不同:

------------------------------------------------------- 
ROW 1 
------------------------------------------------------- 
ROW 2 
------------------------------------------------------- 
LAST ROW <-- Select last row 

這是代碼我已經:

Sub AddNewAllocToSpendLine(sectionHeading As String, Optional sSheetName As String = c_Alloc2SpendSheetName) 

    Worksheets(sSheetName).Activate 

    'get the section heading position 
    Set c = Worksheets(sSheetName).Range("A:A").Find(sectionHeading, LookIn:=xlValues, LookAt:=xlWhole) 

    Debug.Print c 

    Dim addrow As String 
    Dim lRow As Long 

    addrow = c.Row + 1 

    If addrow <> "" And IsNumeric(addrow) = True Then 

     Rows(addrow).Insert shift:=xlDown 

    Else 
     MsgBox ("enter only row number") 
    End If 

End Sub 
+1

你是什麼意思的'部分'? – newguy

+1

'lastRow =工作表(「Sheet1」)。單元格(工作表(「Sheet1」)。rows.count,1).end(xlup).row' –

+0

@newguy不同標題的行彼此不同。教育,旅遊等 – user3565164

回答

0

如果他們是桌子,你可以這樣做:

Dim r as Long 
With ActiveSheet.ListObjects("Table1") 
    r = .ListRows(.ListRows.Count).Range.Row 
End With 

但是,如果你只是想在結束時添加其他行:

ActiveSheet.ListObjects("Table1").ListRows.Add 

特定行之前或加:

ActiveSheet.ListObjects("Table1").ListRows(3).Add 
'You can change the '3' to a variable, of course 
+0

輝煌我嘗試了 - 表格很有意義。謝謝! – user3565164

+0

@ user3565164沒問題!如果它爲你工作,你會檢查這是一個可以接受的答案? – Brian

0

試試這個

Function FindSectionLastRow(rng As Range, header As String) 
    Dim f As Found 

    Set f = rng.Find(what:=header, LookIn:=xlValues, LookAt:=xlWhole, MatchCase:=False) 
    If Not f Is Nothing Then FindSectionLastRow = f.End(xlDown).Row 
End Function 

你可以在你的主要Sub中使用如下:

Sub AddNewAllocToSpendLine(sectionHeading As String, Optional sSheetName As String = c_Alloc2SpendSheetName) 

    Dim sectionLastRow As Long 

    ' your code 

    SectionLastRow = FindSectionLastRow(Worksheets(sSheetName).Columns(1), sectionHeading) 


    ' more code to use 'SectionLastRow' 

End Sub 
相關問題