【问题标题】:Divide each cell in a range by a cell on the same row将范围中的每个单元格除以同一行上的单元格
【发布时间】:2019-01-01 13:45:07
【问题描述】:

我需要将变量范围除以静态列中的单元格,但变量行。我的范围将始终从单元格 J2 开始,但可以在任何地方结束。静态列始终为 H。所以我的要求是将 J2 除以 H2,然后将 K2 除以 H2,L2 除以 H2(行尾);将 J3 除以 H3 等。

我的代码很接近,但我无法让行和下一个单元格同时进行。要么计算总是放在 J2 中,要么总是使用 H2 中的值,而不是在行的其余部分进行时进行到 H3、H4 等。

在下面我的代码示例中,它是两个问题中的后者:

Dim rng As Range, e As Long, lastrow As Long, lastcol As Long

lastcol = Sheets("Group_PositionList").Cells(1, Columns.Count).End(xlToLeft).Column
lastrow = Sheets("Group_PositionList").Cells(Rows.Count, 1).End(xlUp).Row

Set rng = ActiveSheet.Range(Cells(2, 10), Cells(lastrow, lastcol))

For e = 2 To lastrow
    For Each Cell In rng
        If Cell.Value > 0 Then
            Cell.Value = Cell.Value / Cells(e, 8).Value
        End If
    Next
Next e
End Sub

我看到该过程没有到达“Next e”行,但我终其一生都无法想出到达那里的语法。我需要另一个级别的循环吗?

【问题讨论】:

    标签: vba excel loops for-loop


    【解决方案1】:

    使用 for 循环迭代列:

    Dim rng As Range, e As Long, i As Long, lastrow As Long, lastcol As Long
    With Sheets("Group_PositionList")
        lastcol = .Cells(1, Columns.Count).End(xlToLeft).Column
        lastrow = .Cells(Rows.Count, 1).End(xlUp).Row
    
    
    
        For e = 2 To lastrow
            For i = 10 To lastcol
                If .Cells(e, i).Value > 0 Then
                    .Cells(e, i).Value = .Cells(e, i).Value / .Cells(e, 8).Value
                End If
            Next
        Next e
    End With
    

    但是使用变体数组会更快:

    Dim rng, mRng, e As Long, i As Long, lastrow As Long, lastcol As Long
    With Sheets("Group_PositionList")
        lastcol = .Cells(1, Columns.Count).End(xlToLeft).Column
        lastrow = .Cells(Rows.Count, 1).End(xlUp).Row
    
    
        rng = .Range(Cells(2, 10), Cells(lastrow, lastcol)).Value
        mRng = .Range(Cells(2, 8), Cells(lastrow, 8)).Value
    
        For e = LBound(rng, 1) To UBound(rng, 1)
            For i = LBound(rng, 2) + 2 To UBound(rng, 2)
                If rng(e, i).Value > 0 Then
                    rng(e, i).Value = rng(e, i).Value / mRng(e, 1).Value
                End If
            Next
        Next e
    
        .Range(Cells(2, 10), Cells(lastrow, lastcol)).Value = rng
    
    End With
    

    【讨论】:

    • 绝对完美。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-05
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多