I am using this code to check if a barcode is on the database but every time the barcode is not on the list it prompts an error message saying:
Runtime Error 91 : Object variable or With block variable not set.
Is there a line I can add like a msgbox that the barcode entered is invalid. I understand that this is what I need but apparently, I don't know which function I should use to come with an IF statement. Any suggestions?
I would also appreciate if anyone can suggest using the FOR statement if a batch would be searched say nos. 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
From the documentation:
This demonstrates how to use the VBA
.Find
method:This assumes (based on your example) that
CheckBarcodeTextBox
contains text to match in ColumnJ
, matching the "entire cell" only.If you only need to check if a match exists (and don't need to know the location of the match), then the above example can be simplified a bit.
In a worksheet formula I'd use
VLOOKUP
orMATCH
, which can be called usingApplication.WorksheetFunction
but both requiresOn Error
handling to deal with non-matches, so.Find
is probably best.More Information from Microsoft Docs:
Range.Find
Method (Excel)Application.DisplayAlerts
Property (Excel)Use the sites' left sidebar to navigate to sections like VBA functions, methods and statements.
Try
The worksheet's MATCH is as fast or faster than Range.Find within a single column. Using Application.Match returned to a variant allows you to test with IsError.