簡體   English   中英

檢查 VBA 列中是否存在值

[英]Check if value exists in column in VBA

我有一列超過 500 行的數字。 我需要使用 VBA 來檢查變量 X 是否與列中的任何值匹配。

有人可以幫幫我嗎?

范圍的 find 方法比使用 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

如果您想在沒有VBA 的情況下執行此操作,您可以使用IFISERRORMATCH的組合。

因此,如果所有值都在 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循環非常萬無一失。

試試這個:

If Application.WorksheetFunction.CountIf(RangeToSearchIn, ValueToSearchFor) = 0 Then
Debug.Print "none"
End If

只是為了修改 scott 的答案以使其成為一個函數:

Function FindFirstInRange(FindString As String, RngIn As Range, Optional UseCase As Boolean = True, Optional UseWhole As Boolean = True) As Variant

    Dim LookAtWhat As Integer

    If UseWhole Then LookAtWhat = xlWhole Else LookAtWhat = xlPart

    With RngIn
        Set FindFirstInRange = .Find(What:=FindString, _
                                     After:=.Cells(.Cells.Count), _
                                     LookIn:=xlValues, _
                                     LookAt:=LookAtWhat, _
                                     SearchOrder:=xlByRows, _
                                     SearchDirection:=xlNext, _
                                     MatchCase:=UseCase)

        If FindFirstInRange Is Nothing Then FindFirstInRange = False

    End With

End Function

如果未找到該值,則返回 FALSE,如果找到,則返回范圍。

您可以選擇告訴它區分大小寫,和/或允許部分單詞匹配。

我取出了 TRIM,因為如果您願意,可以事先添加它。

一個例子:

MsgBox FindFirstInRange(StringToFind, Range("2:2"), TRUE, FALSE).Address

這會在第二行進行區分大小寫的部分單詞搜索,並顯示一個包含地址的框。 以下是相同的搜索,但不區分大小寫的全字搜索:

MsgBox FindFirstInRange(StringToFind, Range("2:2")).Address

您可以根據自己的喜好輕松調整此函數,或將其從 Variant 更改為布爾值或其他任何內容,以稍微加快速度。

請注意,VBA 的 Find 有時比其他方法(如強力循環或匹配)慢,所以不要僅僅因為它是 VBA 原生的就認為它是最快的。 它更加復雜和靈活,這也可能使它並不總是那么高效。 它有一些有趣的怪癖需要注意,比如“對象變量或塊變量未設置” 錯誤

修復了@JeffC 在@sdanse 函數中提到的問題:

Function FindFirstInRange(FindString As String, RngIn As Range, Optional UseCase As Boolean = True, Optional UseWhole As Boolean = True) As Variant

    Dim LookAtWhat As Integer

    If UseWhole Then LookAtWhat = xlWhole Else LookAtWhat = xlPart

    With RngIn
        Set FindFirstInRange = .Find(What:=FindString, _
                                     After:=.Cells(.Cells.Count), _
                                     LookIn:=xlValues, _
                                     LookAt:=LookAtWhat, _
                                     SearchOrder:=xlByRows, _
                                     SearchDirection:=xlNext, _
                                     MatchCase:=UseCase)
        
        If FindFirstInRange Is Nothing Then
            FindFirstInRange = False
            Exit Function
        End If
        
        If IsEmpty(FindFirstInRange) Then
            FindFirstInRange = False
        Else
            FindFirstInRange = True
        End If
            
    End With

End Function

嘗試添加 WorksheetFunction:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM