首页 > 解决方案 > excel VBA查找不适用于特定值

问题描述

Find 功能效果很好,但我不明白的例外情况很少。我有用户表单,我使用 find 方法通过其代码获取有关产品/项目的所有信息,并在用户表单中按下按钮后显示它。我表中的产品代码由这样的代码组成:1230、1231、1232...1239。主要问题是我不明白为什么像:1-9、123 这样的数字不会触发消息框“找不到产品”?

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

标签: excelvbafind

解决方案


代替:

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)


推荐阅读