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

tad*_*das 2 excel vba excel-vba

一个菜鸟问题.

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

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

for i=1 to 10 
    for j = 1 to 10
        cells(i,j) = cells(i+1,j)
    next j
next i
Run Code Online (Sandbox Code Playgroud)

我怎么能用下面的代码完成上述操作?

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

for each loopCell in rng
    loopCell = UPCOMING OR PREVIOUS loopCell
next loopCell
Run Code Online (Sandbox Code Playgroud)

小智 5

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

for each loopCell in rng
    loopCell = loopcell.Offset(-1, 0)
next loopCell
Run Code Online (Sandbox Code Playgroud)

对于上一个

要么

for each loopCell in rng
    loopCell = loopcell.Offset(1, 0)
next loopCell
Run Code Online (Sandbox Code Playgroud)

对于下一个

希望能有所帮助


Gar*_*ent 5

如果rng是一个很好的紧凑矩形范围,FairlyLegit提出的解决方案很好.如果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
Run Code Online (Sandbox Code Playgroud)