使用命名范围查找最后一行
如果工作表中有命名范围,并且你想动态获取该动态命名范围的最后一行。还包括命名范围不从第一行开始的情况。
Sub FindingLastRow()
Dim sht As Worksheet
Dim LastRow As Long
Dim FirstRow As Long
Set sht = ThisWorkbook.Worksheets("form")
'Using Named Range "MyNameRange"
FirstRow = sht.Range("MyNameRange").Row
' in case "MyNameRange" doesn't start at Row 1
LastRow = sht.Range("MyNameRange").Rows.count + FirstRow - 1
End Sub
更新:
@Jeeped 指出了一个潜在的漏洞,它是一个带有非连续行的命名范围,因为它会产生意想不到的结果。为了解决该问题,代码修改如下。
假设:targes sheet = form
,名为 range = MyNameRange
Sub FindingLastRow()
Dim rw As Range, rwMax As Long
For Each rw In Sheets("form").Range("MyNameRange").Rows
If rw.Row > rwMax Then rwMax = rw.Row
Next
MsgBox "Last row of 'MyNameRange' under Sheets 'form': " & rwMax
End Sub