我需要用静态列但可变行中的单元格划分可变范围。我的范围将始终在单元格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”行,但是我一生都无法提出将其实现的语法。我是否需要另一个级别的循环?
答案 0 :(得分:2)
使用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