使用宏在Excel中循环不同范围的单元格

时间:2018-02-14 20:18:54

标签: excel excel-vba loops vba

我试图在Excel工作表上循环一组不同的范围。这是我的工作表 - Example sheet

enter image description here

当我运行宏时,我希望它在E和F列中显示4,6,12和14.这是我的代码。

as

这里的错误是什么?

2 个答案:

答案 0 :(得分:1)

目前,您正在将Rng12中的每个单元格添加到rng11中的每个单元格。我们想在其中一个范围内循环一次,并在另一个范围内引用相应的单元格。

Sub auto_updateTest()
Dim rng11 As Range, rng12 As Range
Dim i As Long, j As Long

With Worksheets("Sheet1") 'change to your sheet
    Set rng11 = .Range("E3:F4")
    Set rng12 = .Range("A3:B4")
    For i = 1 To rng11.Rows.Count
        For j = 1 To rng11.Columns.Count
            rng11.Cells(i, j).Value = rng11.Cells(i, j).Value + rng12.Cells(i, j).Value

        Next j
    Next i
End with

End Sub

现在使用这个小范围它会很快但随着范围变大,请考虑将所有内容移动到内存阵列。这将限制对工作表的调用次数并加快更大的数字集:

Sub auto_updateTest()
Dim rng11 As Variant, rng12 As Variant
Dim i As Long, j As Long

With Worksheets("Sheet1") 'change to your sheet
    rng11 = .Range("E3:F4").Value
    rng12 = .Range("A3:B4").Value
    If UBound(rng11, 1) <> UBound(rng12, 1) Or UBound(rng11, 2) <> UBound(rng12, 2) Then
        MsgBox "Ranges not the same size"
        Exit Sub
    End If
    For i = LBound(rng11, 1) To UBound(rng11, 1)
        For j = LBound(rng11, 2) To UBound(rng11, 2)
            rng11(i, j) = rng11(i, j) + rng12(i, j)

        Next j
    Next i
    .Range("E3:F4").Value = rng11

End With

End Sub

答案 1 :(得分:0)

你的内循环(cell11)为rng11中的每个值加1,然后外循环递增并且内循环重复。我计算出E3最终为17.尝试使用单个循环,并使用偏移量。