作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
此问题与本网站列出的现有问题 here 略有不同。 , here & here .
我想在 Excel VBA 中编写 UDF(并且不使用任何现有的 VBA 函数)以在同一级别(1 到 1)同时循环遍历两个范围,并检查两个值是否匹配。
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/
我是一名优秀的程序员,十分优秀!