我有以下vba代码:
StartLastRow = .Cells(1, 1).SpecialCells(xlLastCell).Row
If StartLastRow > 24 Then
.Cells(StartLastRow, 1).CurrentRegion.EntireRow.Delete
StartLastRow = .Cells(1, 1).SpecialCells(xlLastCell).Row
End If
删除行后,StartLastRow
的值保持不变
我该如何解决?
答案 0 :(得分:1)
按照上面的@Siddharth Rout评论,使用Find
函数是获取最后一行最安全的方法。
StartLastRow = FindLastRow
If StartLastRow > 24 Then
.Cells(StartLastRow, 1).CurrentRegion.EntireRow.Delete
StartLastRow = FindLastRow
End If
'=======================================================================
Function FindLastRow() As Long
' This Function finds the last row in a worksheet, and returns the row number
Dim LastCell As Range
Set LastCell = Cells.Find(What:="*", After:=Cells(1), Lookat:=xlPart, LookIn:=xlFormulas, _
searchorder:=xlByRows, searchdirection:=xlPrevious, MatchCase:=False)
If Not LastCell Is Nothing Then
FindLastRow = LastCell.Row
Else
MsgBox "Error! worksheet is empty", vbCritical
FindLastRow = -10000
End If
End Function