动态范围的第一行和最后一行

时间:2019-05-21 19:41:25

标签: excel vba

我很惊讶对此没有答案。我已阅读Setting Dynamic Ranges in VBASelecting Dynamic Range以及Autofill Dynamic Range Last Row and Last ColumnMSDN

我在一张大小不同的纸上有多个不同的范围。我正在尝试汇总column L。我可以使用硬编码的和(通过subtotal变量)来完成此操作,但是我想将公式插入单元格中。这需要知道每个范围的开始行和结束行。我的代码几乎可以正常工作。当范围仅包含一行时,它将失败。即使这样,我仍然认为必须有一种更聪明的方法。

如何确定填充多个范围的图纸上范围的开始和结束行?

For i = 2 To j

    If .Cells(i + 1, "L") = "" And .Cells(i + 2, "L") = "" Then
        b = .Cells(i - 1, "J").End(xlUp).Row
    End If

    subtotal = subtotal + .Cells(i, "L").Value2
    If .Cells(i, 1) = "" And .Cells(i - 1, "B") <> "" Then
        If .Cells(i - 1, "K") = 0 Then
            .Cells(i, "K").Value2 = "Check Payment"
            'Set sumRng = .Range(.Cells(b, "L"), .Cells(i - 1, "L"))
            .Cells(i, "L").Formula = "=sum(L" & b & ":L" & i - 1 & ")"
            .Cells(i - 1, "L").Borders(xlEdgeBottom).LineStyle = xlContinuous
            total = total + subtotal
            subtotal = 0
        ElseIf .Cells(i - 1, "K") = "Checking" Then
            .Cells(i, "K").Value2 = "EFT Payment"
            'Set sumRng = .Range(.Cells(b, "L"), .Cells(i - 1, "L"))
            .Cells(i, "L").Formula = "=sum(L" & b & ":L" & i - 1 & ")"
            .Cells(i - 1, "L").Borders(xlEdgeBottom).LineStyle = xlContinuous
            total = total + subtotal
            subtotal = 0
        End If
    End If
Next

enter image description here

2 个答案:

答案 0 :(得分:1)

您可以像这样遍历该列:

For i = 2 To mySheet.Range("B" & Rows.Count).End(xlUp).Row + 1
    If Range("B" & i).Value <> vbNullString Then
        If Range("B" & i - 1).Value = vbNullString Then
            j = i
        End If
    Else
        If Range("B" & i - 1).Value <> vbNullString And Range("B" & i - 1).Formula <> "=SUM(B" & j & ":B" & i - 2 & ")" Then
            Range("B" & i).Formula = "=SUM(B" & j & ":B" & i - 1 & ")"
        End If
    End If
Next i

答案 1 :(得分:1)

这使用Match跳过块,因此数量或循环次数更少

With ActiveSheet
    Dim b As Long
    b = 2

    Do Until b = .Rows.Count

        Dim x As Variant
        x = .Evaluate("Match(True, Index(" & .Range(.Cells(b, "l"), .Cells(.Rows.Count, "l")).Address & " <> """",),0)")
        If Not IsError(x) Then
            b = b + x - 1
        Else
            Exit Sub
        End If

        x = .Evaluate("Match(True, Index(" & .Range(.Cells(b, "l"), .Cells(.Rows.Count, "l")).Address & " = """",),0)")
        Dim i As Long
        i = b + x - 1

        .Cells(i, "l").Formula = "=sum(L" & b & ":L" & i - 1 & ")"

        b = i + 2
     Loop
End With