宏以检查列中的重复项

时间:2015-04-20 07:43:44

标签: vba excel-vba excel-2010 excel

我浏览了网站,发现了一些代码重复的代码示例,但它们仅匹配部分情况而非完全匹配。

我有一个宏,它接受一个单元格值,然后在列中查找任何重复项,并为其找到的任何内容增加计数。但是,它有点工作,因为它找到部分匹配重复,但我需要它只匹配完全匹配重复。

例如,目前如果我有一行包含1而另一行包含11,则会将这些行突出显示为重复。

这是我目前的代码。

Function CountMatches(searchvalue As String, sheet As Worksheet, r As String) As Integer

Dim firstFound As Range
Dim lastFound As Range
Dim matchCount As Integer
Set firstFound = sheet.Range(r).Find(searchvalue, After:=ActiveCell, SearchOrder:=xlByColumns, SearchDirection:=xlNext, _
MatchCase:=True, SearchFormat:=True)

sheet.Range(r).Select

Set firstFound = sheet.Range(r).Find(What:=searchvalue, After:=ActiveCell, LookIn:=xlValues, _
LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlNext, _
MatchCase:=True, SearchFormat:=False)

If firstFound Is Nothing Then

  CountMatches = 0


Else

Do

        Set lastFound = sheet.Range(r).Find(What:=searchvalue, After:=IIf(lastFound Is Nothing, firstFound, lastFound), LookIn:=xlValues, _
LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlNext, _
MatchCase:=True, SearchFormat:=False)

      matchCount = matchCount + 1

   Loop Until lastFound Is Nothing Or firstFound.Address = lastFound.Address

  CountMatches = matchCount


  End If

End Function

1 个答案:

答案 0 :(得分:1)

您需要查看整个单元格的内容而不是其中的一部分,即将LookAt:=xlPart更改为LookAt:=xlWhole

Range.Find documentation