检查VBA中的列是否存在值

我有一列500行以上的数字。 我需要使用VBA来检查variablesX是否与列中的任何值匹配。

有人可以帮帮我吗?

如果你想在没有 VBA的情况下这样做,你可以使用IFISERRORMATCH的组合。

所以如果所有的值都在列A中,在列B中input这个公式:

 =IF(ISERROR(MATCH(12345,A:A,0)),"Not Found","Value found on row " & MATCH(12345,A:A,0)) 

这将查找值“12345”(也可以是单元格引用)。 如果没有find该值, MATCH返回“ ISERROR / 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 

您可以使用VBA中的工作表函数,但是它们是挑剔的,有时会引起无意义的错误。 FOR循环非常安全。

范围的查找方法比使用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 

最简单的就是使用Match

 If Not IsError(Application.Match(ValueToSearchFor, RangeToSearchIn, 0)) Then ' String is in range