我有一列超过500行的数字。我需要使用VBA来检查变量X是否与列中的任何值匹配。
有人可以帮帮我吗?
如果你想在没有VBA的情况下这样做,你可以使用IF
,ISERROR
和MATCH
的组合。
因此,如果所有值都在A列中,请在B列中输入以下公式:
=IF(ISERROR(MATCH(12345,A:A,0)),"Not Found","Value found on row " & MATCH(12345,A:A,0))
这将查找值“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
您可以在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
试试这个:
If Application.WorksheetFunction.CountIf(RangeToSearchIn, ValueToSearchFor) = 0 Then
Debug.Print "none"
End If
尝试添加WorksheetFunction:
If Not IsError(Application.WorksheetFunction.Match(ValueToSearchFor, RangeToSearchIn, 0)) Then
' String is in range