每个循环的VBA参考前一个和即将到来的项目

时间:2015-05-08 16:12:25

标签: vba excel-vba excel

一个菜鸟问题。

以下代码作为示例给出,因此我不是指具体案例。

如下所示进行循环时,我可以轻松引用上一个和即将发布的项目:

for i=1 to 10 
    for j = 1 to 10
        cells(i,j) = cells(i+1,j)
    next j
next i

如何使用以下代码执行上述操作?

dim rng, loopCell as Range
set rng = range(...)

for each loopCell in rng
    loopCell = UPCOMING OR PREVIOUS loopCell
next loopCell

2 个答案:

答案 0 :(得分:5)

FairlyLegit 提出的解决方案很好,如果 rng 是一个很好的紧凑矩形范围。如果 rng 是一个不相交的单元格组,那么获取前一个单元格有点棘手:

Sub dural()
    Dim rng As Range, r As Range, rPrevious As Range
    Set rng = Range("A1,C5,F7")
    For Each r In rng
        If rPrevious Is Nothing Then
        Else
            If r.Value = rPrevious.Value Then
                MsgBox r.Address & " has the same value as " & rPrevious.Address
            End If
        End If
        Set rPrevious = r
    Next r
End Sub

答案 1 :(得分:4)

使用offset属性。语法为.Offset(rowindex, column index)

for each loopCell in rng
    loopCell = loopcell.Offset(-1, 0)
next loopCell

For Previous

或者

for each loopCell in rng
    loopCell = loopcell.Offset(1, 0)
next loopCell

For Next

希望有所帮助