vba - 使用查找函数未找到值的错误消息

标签 vba excel

我使用此代码来检查条形码是否在数据库中,但每次条形码不在列表中时,都会提示一条错误消息:

Runtime Error 91 : Object variable or With block variable not set.

是否有一行我可以像消息框一样添加,表明输入的条形码无效。我知道这就是我所需要的,但显然,我不知道应该使用哪个函数来附带 IF 语句。有什么建议吗?

如果有人可以建议使用 FOR 语句(如果要搜索批处理)说不,我也将不胜感激。 1111-1114

Private Sub CheckBarcodeStatusCommandButton_Click()
    ActiveWorkbook.Sheets("Inventory Log").Select
    Columns("J:J").Select
    Selection.Find(What:=CheckBarcodeTextBox.Text, after:=ActiveCell, _
        LookIn:=xlFormulas, LookAt:=xlWhole, SearchOrder:=xlByRows, _
        SearchDirection:=xlNext, MatchCase:=False, MatchByte:=False, _
        SearchFormat:=False).Activate

    If ActiveCell.Offset(0, 1).Value = "In" Then
        MsgBox ("The barcode no. " & CheckBarcodeTextBox.Text _
            & " is currently available")
    ElseIf ActiveCell.Offset(0, 1).Value = "Out" Then
        MsgBox ("The barcode no. " & CheckBarcodeTextBox.Text _
            & " has already been used.")
    End If

    Application.DisplayAlerts = False
End Sub

最佳答案

来自documentation :

This method returns Nothing if no match is found. The .Find method does not affect the selection or the active cell.


这演示了如何使用 VBA .Find 方法:

这假设(根据您的示例)CheckBarcodeTextBox 包含要在列 J 中匹配的文本,仅匹配“整个单元格”。

Private Sub CheckBarcodeStatusCommandButton_Click()
    Dim lookFor As String, lookIn As Range, found As Range

    lookFor = CheckBarcodeTextBox.Text
    Set lookIn = ThisWorkbook.Sheets("Inventory Log").Columns("J:J")
    Set found = lookIn.Find(lookFor, , xlValues, xlWhole) 'match whole cell value

    If found Is Nothing Then
        'not found
        MsgBox "No match for: " & lookFor
    Else
        'found
        MsgBox "Found: " & lookFor & vbLf & _
               " in cell: " & found.Address & vbLf & _
               " which contains: " & found.Value
    End If
End Sub

如果您只需要检查匹配是否存在(并且不需要知道匹配的位置),那么上面的示例可以简化为一点。

Private Sub CheckBarcodeStatusCommandButton_Click()
    Dim lookIn As Range
    Set lookIn = ThisWorkbook.Sheets("Inventory Log").Columns("J")
    If lookIn.Find(CheckBarcodeTextBox, , xlValues, xlWhole) Is Nothing Then
        MsgBox "Not found:."    'do something if not found
    Else
        MsgBox "Found."         'do something if found
    End If
End Sub

在工作表公式中,我会使用 VLOOKUPMATCH,可以使用 Application.WorksheetFunction 调用,但两者都需要 在错误处理中处理不匹配的情况,因此.Find可能是最好的。


来自 Microsoft 文档的更多信息:

推荐书签:Microsoft 文档:Office VBA Reference
使用站点的左侧边栏导航至 VBA functions 等部分, methodsstatements .

关于vba - 使用查找函数未找到值的错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52267907/

相关文章:

vba - 用户窗体在 "End Sub"之后关闭,而无需调用 "Unload Me"

ms-access - ByRef 参数类型与 bool 值不匹配

c# - 使用 C# Interop.Excel 从 NamesManager 中删除重复名称

c# - 如何通过 .Net Interop 调用 VBA 函数

excel - VBA 根据位置选择形状

vba - 是如果 x/100 = Int(x/100) 然后 ActiveWorkbook.Save 还是如果 x/100 = Int(x) 然后 ActiveWorkbook.save?

events - VBA - 通过用户定义的函数更新其他单元格

vba - 如何选择除标题以外的整列?

excel - 如何在 For Each 循环之外创建一个 vbYesNo MsgBox?

vba - 将工作表合并为一张