Excel VBA – 如何在For循环中比较两个范围在1到1级别?

这个问题与此处列出的现有问题略有不同, 在这里 & 这里 。

我想在Excel VBA中编写一个UDF(而不是使用任何现有的VBA函数)在同一级别(1到1)同时循环两个范围,并检查这两个值是否匹配。

在这里input图像说明

Public Function compare(r1 As Range, r2 As Range) As Integer Dim i For Each cell In r1 if cell.Value = 'value from r2 at same range level, 1 to 1 compare i = i + 1 End If Next cell compare = i End Function 

在这个UDF中,它有两个范围作为input。 假设它们是简单的单列和相等的行。 现在For Each cell in Range循环中使用For Each cell in Range我希望在相同单元级别比较两个范围。 这可能吗?

我是否需要创build一个嵌套,并在每个内部For,跳过那些许多单元格以匹配Outer For的单元格?

更改为编号循环。

 Public Function compare(r1 As Range, r2 As Range) As long Dim i as long, r as long For r=1 to r1.cells.count if r1.cells(r).Value = r2.cells(r).Value Then i = i + 1 End If Next r compare = i End Function 

从变体数组中可能还有其他好处,将r2的大小调整为始终与r1相同的行x列,并将r1和r2限制为.UsedRange。

 Public Function compare(r1 As Range, r2 As Range) As long Dim i as long, r as long 'restrict to .usedrange so full columns can be input set r1 = intersect(r1, r1.parent.usedrange) 'make sure r2 is same dimensions as r1 set r2 = r2.cells(1).resize(r1.rows.count, r1.columns.count) For r=1 to r1.cells.count if r1.cells(r).Value = r2.cells(r).Value Then i = i + 1 End If Next r compare = i End Function