Determine last non-value (may have a formula) row in column

前端 未结 4 1370
一向
一向 2021-01-22 13:59

I have a column that has a formula in each row field. The formula propagates data from another Excel spreasheet. If there is nothing in the row field, though, the row remains bl

4条回答
  •  -上瘾入骨i
    2021-01-22 14:26

    I've never done anything quite like this, but it seems to work correctly and quicky for fairly large areas. Even though you said the column is all formulas, this accounts for a mix of values and formulas, thus the outer loop stepping backwards through the Areas:

    Function GetLastFormulaBlank(rngInput As Excel.Range) As Excel.Range
    
    Dim rngFormulas As Excel.Range
    Dim rngArea As Excel.Range
    Dim CellCounter As Long
    Dim AreaCounter As Long
    Dim varAreaCells As Variant
    Dim rngLastFormulaBlank As Excel.Range
    
    Set rngFormulas = rngInput.SpecialCells(xlCellTypeFormulas)
    For AreaCounter = rngFormulas.Areas.Count To 1 Step -1
        Set rngArea = rngFormulas.Areas(AreaCounter)
        varAreaCells = rngArea.Value2
        If IsArray(varAreaCells) Then
            For CellCounter = UBound(varAreaCells) To LBound(varAreaCells) Step -1
                If varAreaCells(CellCounter, 1) = "" Then
                    Set rngLastFormulaBlank = rngArea.Cells(CellCounter)
                    Exit For
                End If
            Next CellCounter
        Else
            If varAreaCells = "" Then
                Set rngLastFormulaBlank = rngArea.Cells(1)
            End If
        End If
        If Not rngLastFormulaBlank Is Nothing Then
            Exit For
        End If
    Next AreaCounter
    
    Set GetLastFormulaBlank = rngLastFormulaBlank
    End Function
    

    You'd call it like this:

    Sub test()
    Dim rngLastFormulaBlank As Excel.Range
    
    Set rngLastFormulaBlank = GetLastFormulaBlank(ActiveSheet.Range("A:A"))
    If Not rngLastFormulaBlank Is Nothing Then
        MsgBox rngLastFormulaBlank.Address
    Else
        MsgBox "no formulas with blanks in range"
    End If
    End Sub
    

提交回复
热议问题