首页 > 解决方案 > 总结 VlOOKUP 和 COUNTIF 的 VBA 代码

问题描述

我正在尝试将列(column1)的每个单元格与另一列(column2)中的所有单元格进行比较,并获得匹配次数的结果。

在使用 VLOOKUP 的 excel 中,我创建了 column3,它给出的结果为“匹配”和“不匹配”,然后使用 COUNTIF“匹配”单元格。有什么办法可以避免这个column3,直接得到匹配总数的结果吗?

帮助将不胜感激。

标签: excelvbavlookupcountif

解决方案


您可以使用该 vba 代码。随意更改它。

Sub GetMatces()
Dim rng1 As Range, rng2 As Range, result As Integer, cell1 As Range, 
cell2 As Range

result = 0
Set rng1 = ActiveSheet.Range("A1:A8")  'Here you can put the exact range to run the code or you can set it as a selection with "set rng=application.selection"
Set rng2 = ActiveSheet.Range("b1:b8")

For Each cell1 In rng1
For Each cell2 In rng2
    If cell1 = cell2 Then result = result + 1
Next cell2
Next cell1

MsgBox result 'that variable is the sum of the matces. you can do it everything you want
End Sub

推荐阅读