查找。()无法正常工作

时间:2017-05-18 20:51:14

标签: excel excel-vba excel-2010 vba

查找。()找不到正确的行。有时它会在找到第一行的其他时间找到一个随机行。这是我的代码:

Private Sub CommandButton_Tool_Turn_In_Click()
Dim iTurnIn As Long
Dim ws As Worksheet
Dim Answer As String
'Ask Yes or no
Answer = MsgBox("This will EDIT the invitory. Would you like to continue?", vbYesNo + vbQuestion)
If Answer = vbYes Then
    'Find Row to Edit
    Set ws = Worksheets("ToolData")
        iTurnIn = ws.Cells.Find(What:=Me.SelectedRow.Value, SearchOrder:=xlRows, LookIn:=xlValues).Row
    'Writing textbox/combobox values to worksheet
    With ws
        .Cells(iTurnIn, 5).Clear 'this is here to Debug
        .Cells(iTurnIn, 5).Value = "Yes"
    End With
    Call CommandButton_SSN_Search_Click
    Call UF1ListBoxRefresh
    MsgBox "Succesfuly EDITED Selected line!"
    Else
    'Do nothing
    End If
    End Sub

我已将问题缩小到这个

ws.Cells.Find(iTurnIn = ws.Cells.Find(What:=Me.SelectedRow.Value, SearchOrder:=xlRows, LookIn:=xlValues).Row

Me.SelectedRow是一个TextBox,其中包含我要编辑的行的行号值。

我有另一种方法可以正常工作,但它使用循环。我宁愿知道我做错了什么并使用Find()

1 个答案:

答案 0 :(得分:0)

如果您的ID位于E列,则应使用以下内容:

Dim findResult As Range
Set findResult = ws.Columns("E").Find(What:=Me.SelectedRow.Value, _
                                      SearchOrder:=xlRows, _
                                      LookIn:=xlValues, _
                                      LookAt:=xlWhole)
If findResult Is Nothing Then
    MsgBox "ID not found"
    Exit Sub
End If
iTurnIn = findResult.Row

Find限制为您认为值应该位于的Column会停止与其他列中的值进行错误匹配。将搜索范围限制为xlWhole会阻止15231521527匹配。