I have a spreadsheet that has a number of sections with a random number of rows for each one.
How can you find the last row for one of the section?
Example:
-------------------------------------------------------
ROW 1
-------------------------------------------------------
ROW 2
-------------------------------------------------------
ROW 3
-------------------------------------------------------
ROW 4
-------------------------------------------------------
LAST ROW <-- Select last row
However this can different for each section where the number of rows is different:
-------------------------------------------------------
ROW 1
-------------------------------------------------------
ROW 2
-------------------------------------------------------
LAST ROW <-- Select last row
This is the code I have already:
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
If they are tables you could do this:
Dim r as Long
With ActiveSheet.ListObjects("Table1")
r = .ListRows(.ListRows.Count).Range.Row
End With
But if you simply want to add another row at the end:
ActiveSheet.ListObjects("Table1").ListRows.Add
Or add before a particular row:
ActiveSheet.ListObjects("Table1").ListRows(3).Add
'You can change the '3' to a variable, of course
Try this
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
You could use in your main Sub as follows:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.