如何在VBA中查找动态大小的行部分中的最后一行?

时间:2016-06-29 13:50:26

标签: excel vba

我有一个电子表格,其中包含多个部分,每个部分都有一个随机行数。

如何找到其中一个部分的最后一行?

示例:

<?xml version="1.0" ?>
<root>
  <parent1>
    <child1>blah</child1>
    <child2>blah blah</child2>
  </parent1>
  <parent2>blah</parent2>
</root>

但是,对于行数不同的每个部分,这可能会有所不同:

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

这是我已经拥有的代码:

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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