检查给定范围内的任何单元格是否具有等于该字符串的值

时间:2014-03-22 19:37:51

标签: vba function excel-vba boolean-expression excel

如何创建一个布尔函数来搜索范围中的单元格并检查是否有任何值等于指定的字符串?如果是,则返回true。如果不是,则返回false。

就我而言

Function NameExist(ByVal Name as String, NameRange as Range) As Boolean
Boolean as NameExist = False
If (Name = Michael) Then

1 个答案:

答案 0 :(得分:2)

这是一个实现:

Function NameExists(ByVal searchName As String, nameRange As Range) As Boolean
    NameExists = Not nameRange.Find(What:=searchName, LookAt:=xlWhole) Is Nothing
End Function

这是另一个更多的手动/暴力:

Function NameExists(ByVal searchName As String, nameRange As Range) As Boolean
    Dim i As Long
    Dim j As Long
    Dim v As Variant
    v = nameRange.Value
    NameExists = False
    For i = 1 To UBound(v, 1)
        For j = 1 To UBound(v, 2)
            If v(i, j) = searchName Then
                NameExists = True
                Exit Function
            End If
        Next j
    Next i
End Function

两者都应该给出相同的结果。

使用示例:

If NameExists("Michael",range("B3:C6")) Then MsgBox "Michael exists!"