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

标签 excel vba

此问题与本网站列出的现有问题 here 略有不同。 , here & here .

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

enter image description here

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 中,它采用两个范围作为输入。为了简单起见,假设它们是单列且相等的行。现在使用 For Each cell in Range 循环,我希望比较同一单元格级别的两个范围。这可能吗?

我是否需要创建一个嵌套 For,并在每个内部 For 中跳过许多单元格以匹配外部 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 

关于Excel VBA - 如何在 For 循环中以 1 到 1 的级别比较两个范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47301493/

相关文章:

python - 在python中列出超出范围的索引

excel - 在由实时加载项更改的单元格上自动执行 excel 宏

excel - 不要将空单元格绘制为 '0'

excel - 为 VBA 组合框创建动态范围

vba - 根据值查找连续单元格

将单元格中包含公式的Excel文件读取到R中

vba - 在工作表值中查找数组数据

html - 如何使用vba填写html自动完成字段?

vba - 启动时从 VBA 打开宏安全性

vba - 在 Word VBA 中右键单击选择列表框项