我使用此代码来检查条形码是否在数据库中,但每次条形码不在列表中时,都会提示一条错误消息:
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
在工作表公式中,我会使用 VLOOKUP
或 MATCH
,可以使用 Application.WorksheetFunction
调用,但两者都需要 在错误
处理中处理不匹配的情况,因此.Find
可能是最好的。
来自 Microsoft 文档的更多信息:
推荐书签:Microsoft 文档:Office VBA Reference
使用站点的左侧边栏导航至 VBA functions 等部分, methods和 statements .
关于vba - 使用查找函数未找到值的错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52267907/