检查单元格是否有两个相同的数字

时间:2013-04-15 14:54:04

标签: excel-vba vba excel

有人可以告诉我如何检查一个单元格,A1有两个相同的数字吗? 示例单元格A1 = 1124.这意味着我的意思包含2个相同的数字,如果是这样,B1将是“是”非常感谢。

1 个答案:

答案 0 :(得分:1)

如果您使用的是Excel 2010(未在Excel 2007中测试过),那么您不需要VBA。您可以在B1中使用此公式并将其复制下来。

=IF(LOWER(A1)<>SUBSTITUTE(LOWER(A1),LOWER(1),"",2),"Yes",
 IF(LOWER(A1)<>SUBSTITUTE(LOWER(A1),LOWER(2),"",2),"Yes",
 IF(LOWER(A1)<>SUBSTITUTE(LOWER(A1),LOWER(3),"",2),"Yes",
 IF(LOWER(A1)<>SUBSTITUTE(LOWER(A1),LOWER(4),"",2),"Yes",
 IF(LOWER(A1)<>SUBSTITUTE(LOWER(A1),LOWER(5),"",2),"Yes",
 IF(LOWER(A1)<>SUBSTITUTE(LOWER(A1),LOWER(6),"",2),"Yes",
 IF(LOWER(A1)<>SUBSTITUTE(LOWER(A1),LOWER(7),"",2),"Yes",
 IF(LOWER(A1)<>SUBSTITUTE(LOWER(A1),LOWER(8),"",2),"Yes",
 IF(LOWER(A1)<>SUBSTITUTE(LOWER(A1),LOWER(9),"",2),"Yes",
 IF(LOWER(A1)<>SUBSTITUTE(LOWER(A1),LOWER(0),"",2),"Yes",
 "No"))))))))))

<强>解释

如果该特定号码正在重新调整,公式将从excel单元格中的0 - 9进行检查。

<强>截图

enter image description here

VBA版

Sub Sample()
    Debug.Print Does2NumbersMatch(Range("A1"))
End Sub

Function Does2NumbersMatch(rng As Range)
    Dim i As Long

    Does2NumbersMatch = "No"

    For i = 0 To 9
        isMatch = Application.Evaluate("=IF(LOWER(" & rng.Address & ")<>SUBSTITUTE(LOWER(" & _
                  rng.Address & "),LOWER(" & i & "),"""",2),""Yes"",""No"")")
        If isMatch = "Yes" Then
            Does2NumbersMatch = "Yes"
            Exit Function
        End If
    Next i
End Function