首页 > 解决方案 > 在给定 Range 对象的 VBA 中循环两个相同长度的单元格范围

问题描述

假设我有这样的代码:

For Each cell1 In range_vals
    For Each cell2 In range_pred

      If (cell1 = cell2) Then
            //Do something
      End If

    Next cell1
Next cell2

但是我想要做的是同时遍历两个单元格范围,并且这个范围是长度,如下所示:

For Each cell1, cell2 In range_vals, range_pred   

      If (cell1 = cell2) Then
            //Do something
      End If

Next cell1, cell2

我知道这可以在 python 中完成,但是我正在努力在 VBA 中完成它。

标签: excelvbaloops

解决方案


而不是使用For Each,尝试For像这样使用:

Dim range_vals As Range
Dim range_pred As Range
Dim i As Integer

With Worksheets("Sheet1")
   Set range_vals = .Range("A1:A10")
   Set range_pred = .Range("B1:B10")

   For i = 1 To range_vals.Cells.Count
      If range_vals.Cells(i) = range_pred.Cells(i) Then
         MsgBox "do something"
      End If
   Next
End With

这将“并行”循环,将 A1 与 B1、A2 与 B2 进行比较,依此类推。


推荐阅读