gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 02:26:01 28 4
gpt4 key购买 nike

此问题与本网站列出的现有问题 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com