在多个列范围中查找LastRow?

我试图findLastRow在多个列范围忽略某些列…我有两个尝试,但不能得到正常工作:

两个例子都忽略了N和O列

我的第一个尝试是以下,但它没有得到正确的最后一个范围,如果我在A15例如T10,它认为最后一行是10,当它应该是15。

Sub LastRowMacro() LastRowString = "A1:M" & Rows.Count & ", P1:Z" & Rows.Count LastRowTest = Range(LastRowString).Find(What:="*", After:=[A1], SearchOrder:=xlByRows, searchDirection:=xlPrevious).Row End Sub 

我的第二次尝试如下,但似乎相当长的啰嗦。

 Sub LastRowMacro() Dim i As Long LastRow = 1 IgnoreColumnList = "N;O" For i = 1 To Cells(1, Columns.Count).End(xlToLeft).Column ColumnLetter = Split(Cells(1, i).Address(True, False), "$")(0) For Each varFind In Split(IgnoreColumnList, ";") If varFind = ColumnLetter Then varNotFound = False Exit For End If varNotFound = True Next If varNotFound Then CurrentLastRow = Cells(Rows.Count, i).End(xlUp).Row If CurrentLastRow >= LastRow Then LastRow = CurrentLastRow End If varNotFound = False End If Next End Sub 

理想情况下,我想我的第一次尝试工作,但如果它不工作,那么肯定会有人可以改善我的第二个版本…

尝试这个

*有一个ignoreListvariables,其中包含您要忽略的所有列。 确保你填写正确 – 目前忽略NOP

*您可能需要将shvariables设置为正确的表格 – 当前是Sheet1

* BTW。 此代码段将始终查找电子表格的最后一行。 你可以添加另一个elseif来检查是否有2列与最后一行相同,如果有2列的lastRows最高。

 Sub FindingLastRow() ' ignoring some columns Dim ignoreList ignoreList = Array("N", "O", "P") ' MODIFY IGNORE LIST Dim sh As Worksheet Set sh = Sheet1 ' SET CORRECT SHEET Dim currentlast As Range Set currentlast = sh.Cells(1, 1) Dim iteratingCell As Range With sh For j = 1 To .UsedRange.Columns.Count Set iteratingCell = .Cells(1, j) If Not isIgnored(iteratingCell, ignoreList) Then If iteratingCell.Cells(Rows.Count).End(xlUp).Row >= currentlast.Cells(Rows.Count).End(xlUp).Row Then Set currentlast = iteratingCell End If End If Next Set currentlast = .Range("$" & Split(currentlast.Address, "$")(1) & "$" & currentlast.Cells(Rows.Count).End(xlUp).Row) End With MsgBox currentlast.Address End Sub Function isIgnored(currentlast As Range, ignoreList As Variant) As Boolean Dim ignore As Boolean Dim letter As Variant For Each letter In ignoreList If StrComp(Split(currentlast.Address, "$")(1), letter, vbTextCompare) = 0 Then ignore = True Exit For End If Next isIgnored = ignore End Function