检查VBA中的列中是否存在值

Tru*_*ran 28 excel vba matching

我有一列超过500行的数字.我需要使用VBA来检查变量X是否与列中的任何值匹配.

有人可以帮帮我吗?

sco*_*ott 47

范围的查找方法比使用for循环手动遍历所有单元格更快.

这是在vba中使用find方法的示例

Sub Find_First()
Dim FindString As String
Dim Rng As Range
FindString = InputBox("Enter a Search value")
If Trim(FindString) <> "" Then
    With Sheets("Sheet1").Range("A:A") 'searches all of column A
        Set Rng = .Find(What:=FindString, _
                        After:=.Cells(.Cells.Count), _
                        LookIn:=xlValues, _
                        LookAt:=xlWhole, _
                        SearchOrder:=xlByRows, _
                        SearchDirection:=xlNext, _
                        MatchCase:=False)
        If Not Rng Is Nothing Then
            Application.Goto Rng, True 'value found
        Else
            MsgBox "Nothing found" 'value not found
        End If
    End With
End If
End Sub
Run Code Online (Sandbox Code Playgroud)

  • 谢谢你这样做,斯科特.对于非数字值,它比`FOR`循环更健壮.@ user1547174你可以使用变量`Rng`获取有关匹配位置的信息,特别是调用`Rng.Address`,它将单元格位置作为字符串返回. (2认同)

chr*_*sen 32

最简单的就是使用 Match

If Not IsError(Application.Match(ValueToSearchFor, RangeToSearchIn, 0)) Then
    ' String is in range
Run Code Online (Sandbox Code Playgroud)

  • 在VB编辑器中不显示自动完成,但似乎工作 (2认同)

Jak*_*man 22

如果你想这样做没有 VBA,你可以使用的组合IF,ISERRORMATCH.

因此,如果所有值都在A列中,请在B列中输入以下公式:

=IF(ISERROR(MATCH(12345,A:A,0)),"Not Found","Value found on row " & MATCH(12345,A:A,0))
Run Code Online (Sandbox Code Playgroud)

这将查找值"12345"(也可以是单元格引用).如果找不到该值,则MATCH返回"#N/A"并ISERROR尝试捕获该值.

如果要使用VBA,最快的方法是使用FOR循环:

Sub FindMatchingValue()
    Dim i as Integer, intValueToFind as integer
    intValueToFind = 12345
    For i = 1 to 500    ' Revise the 500 to include all of your values
        If Cells(i,1).Value = intValueToFind then 
            MsgBox("Found value on row " & i)
            Exit Sub
        End If
    Next i

    ' This MsgBox will only show if the loop completes with no success
    MsgBox("Value not found in the range!")  
End Sub
Run Code Online (Sandbox Code Playgroud)

您可以在VBA中使用工作表函数,但它们很挑剔,有时会抛出无意义的错误.该FOR循环是相当万无一失.

  • 使用范围的find方法而不是遍历每个单元格要快得多 (4认同)
  • 仅供参考,你可以比匹配函数更容易:`= countif(A:A,12345)> 0`如果找到数字将返回True,否则返回false. (4认同)

小智 9

尝试这个:

If Application.WorksheetFunction.CountIf(RangeToSearchIn, ValueToSearchFor) = 0 Then
Debug.Print "none"
End If
Run Code Online (Sandbox Code Playgroud)