在多个列范围中查找最后一行?

时间:2014-08-21 06:34:51

标签: excel vba excel-vba excel-2010

我正在尝试在多列范围内找到忽略某些列的LastRow ...我有两次尝试但无法正常工作:

两个例子都忽略了列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

理想情况下,我希望我的第一次尝试工作,但如果它不起作用,那么肯定可以改进我的第二个版本......

1 个答案:

答案 0 :(得分:1)

试试这个

*有一个ignoreList变量,其中包含您要忽略的所有列。确保正确填充此内容 - 目前忽略NOP

*您可能需要将sh变量设置为正确的工作表 - 目前为Sheet1

*顺便说一句。此代码段始终会在电子表格中找到最后最后一行。您可以添加另一个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