查找功能效果很好,但是有一些我不理解的例外。我有一个用户窗体,我使用find方法通过其代码获取有关产品/商品的所有信息,并在用户窗体中按下按钮后将其显示出来。我表中的产品代码包含以下代码:1230、1231、1232 ...1239。主要问题是我不明白为什么数字(如1-9、123)不会触发msgbox“找不到产品”?
Private Sub btnSearch_Click()
Dim i As Long
Dim totalRows As Long
Dim itemCode As Range
Set itemCode = ThisWorkbook.Sheets("Data").Range("A:A").Find(Me.txtCode.Value)
totalRows = Worksheets("Data").Range("A:A").CurrentRegion.Rows.Count
'searching by code
If Trim(Me.txtCode.Value) = "" Then
Me.txtCode.SetFocus
MsgBox "Need item code"
Exit Sub
End If
If itemCode Is Nothing Then
MsgBox "Can't find product with such code"
End If
For i = 2 To totalRows
If Trim(Cells(i, 1)) = Trim(Me.txtCode) Then
txtName.Text = Cells(i, 2)
'unit of measurement name
txtUnitName.Text = Cells(i, 3)
txtPrice.Text = Cells(i, 4)
Exit For
End If
Next i
End Sub
答案 0 :(得分:0)
如果要完全匹配,应在查找参数中添加LookAt:=xlWhole
。
否则,这应该在不使用find的情况下做同样的事情:
Private Sub btnSearch_Click()
Dim i As Long
Dim totalRows As Long
Dim arrData As Variant
With Worksheets("Data")
totalRows = .Cells(Rows.Count, 1).End(xlUp).Row
arrData = .Range("A1:D" & totalRows)
End With
'searching by code
If Trim(Me.txtCode.Value) = "" Then
Me.txtCode.SetFocus
MsgBox "Need item code"
Exit Sub
End If
For i = 2 To totalRows
If Trim(arrData(i, 1)) = Trim(Me.txtCode) Then
txtName.Text = arrData(i, 2)
'unit of measurement name
txtUnitName.Text = arrData(i, 3)
txtPrice.Text = arrData(i, 4)
Exit For
End If
If i = totalRows Then MsgBox "Can't find product with such code"
Next i
End Sub
答案 1 :(得分:0)
替换:
Set itemCode = ThisWorkbook.Sheets("Data").Range("A:A").Find(Me.txtCode.Value)
使用:
Set itemCode = ThisWorkbook.Sheets("Data").Range("A:A").Find(Trim(Me.txtCode.Value), LookIn:=xlValues, LookAt:=xlWhole)