来自文档 https://learn.microsoft.com/office/vba/api/excel.range.find:
该方法返回Nothing
如果没有找到匹配项。这.Find
方法不会影响选择或活动单元格。
这演示了如何使用VBA.Find
method:
这假设(根据您的示例)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
如果您只需要检查是否匹配exists(并且不需要知道location),那么上面的例子可以稍微简化一下。
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
or MATCH
,可以使用调用Application.WorksheetFunction
但两者都需要On Error
处理不匹配的情况,所以.Find
可能是最好的。
来自 Microsoft 文档的更多信息:
- Range.Find Method (Excel) https://learn.microsoft.com/office/vba/api/excel.range.find
- Application.DisplayAlerts财产 (Excel) https://learn.microsoft.com/office/vba/api/excel.application.displayalerts
Recommended Bookmark: Microsoft Documentation: Office VBA Reference https://learn.microsoft.com/office/vba
Use the sites' left sidebar to navigate to sections like VBA functions https://learn.microsoft.com/office/vba/language/reference/functions-visual-basic-for-applications, methods https://learn.microsoft.com/office/vba/language/reference/methods-visual-basic-for-applications and statements https://learn.microsoft.com/office/vba/language/reference/statements.