Excel 发现。()工作不正常
查找。()找不到正确的行。有时它会找到一个随机的行,有时它会找到第一行。这是我的代码:Excel 发现。()工作不正常,excel,excel-2010,vba,Excel,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
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
是一个文本框,其中包含我要编辑的行的行号值
我有另一种方法可以做到这一点,但它使用了一个循环。我宁愿知道我做得不正确,并使用Find()如果您的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
限制为您认为该值应该位于的列,会停止与其他列中的值的错误匹配。将搜索限制为xlWhole
将停止类似152
与3152
或1527
匹配的操作,因此SelectedRow
包含您试图查找的数字或字符串。你是想在一个特定的专栏里找到它吗?此外,如果未找到该值,则会导致错误。SelectRow是一个包含数字的文本框。是,此数字位于特定列中。这不是抛出错误。问题是它没有找到文本框中的数字所在的正确行。哪列是特定列?E列,但这会影响它吗?它正在逐行搜索单元格值或应为。这可能会影响它,因为它可能会在另一列的另一个单元格中找到相同的数字,尤其是在没有LookAt:=xlWhole
参数的情况下。(但如果ID在E列中,为什么要更改E列中的值?)这解释了我之前经历的“随机性”瞧:=xlWhole'正是我所需要的。非常感谢你的帮助。