查找范围(不在列中)的最后一个非空单元格

时间:2020-10-23 12:05:56

标签: excel vba

我想找到给定范围内的最后一个非空单元格。我的解决方案不起作用...

Public Sub Table_And_Layout()
    Dim wsRoadmap As Worksheet
    Dim rGoalL As Range

    Set wsRoadmap = Sheets("Roadmap")

    Set rGoalL = wsRoadmap.Range("A12:A20").End(xlUp)
    MsgBox rGoalL.Address
End Sub

2 个答案:

答案 0 :(得分:0)

如果要在范围所覆盖的行中最右边找到该单元格,请尝试以下操作:

Public Sub Table_And_Layout()
    Dim wsRoadmap As Worksheet
    Dim rTarget As Range
    Dim rGoalL As Range
    Dim dColumn As Double
    
    Set wsRoadmap = Sheets("Roadmap")
    
    For Each rTarget In wsRoadmap.Range("A12:A20")
        If dColumn < wsRoadmap.Cells(rTarget.Row, wsRoadmap.Columns.Count).End(xlToLeft).Column Then
            Set rGoalL = wsRoadmap.Cells(rTarget.Row, wsRoadmap.Columns.Count).End(xlToLeft)
            dColumn = rGoalL.Column
        End If
    Next
    
    
    MsgBox rGoalL.Address
End Sub

答案 1 :(得分:0)

遍历该范围的各个单元格(从最低的行向上并进行检查(For Each myCell In myRange(i).Cells)应该可以:

Function GetLastNonEmptyRow(myRange As Range) As Long
    
    Dim i As Long
    Dim firstCell As Long: firstCell = myRange.Cells(1, 1)        
    Dim myCell As Range
    
    For i = firstCell + myRange.Rows.Count To firstCell Step -1
        For Each myCell In myRange(i).Cells
            If myCell <> "" Then
                GetLastNonEmptyRow = myCell.Row
                Exit Function
            End If
        Next myCell
    Next i
            
    GetLastNonEmptyRow = -1 'means that the whole range is non-empty
            
End Function

这样称呼:

Sub TestMe()
    
    Dim myRange As Range: Set myRange = Worksheets(1).Range("F8:G11")
    Debug.Print GetLastNonEmptyRow(myRange)
        
End Sub