在我的用户表单中,用户可以输入文本进行搜索。如果记录存在,记录将出现在用户表单中,用户可以通过单击按钮删除或更新记录。否则,会弹出一个msgbox“No record match from your list”(列表中没有匹配的记录)。
我的代码如下所示。
然而,在我输入文本并单击“搜索”按钮后,msgbox总是弹出(有时会弹出几次),没有找到任何记录,甚至我搜索的记录实际上存在于excel中。
我能知道有什么问题吗?我应该如何改进我的代码?
Private Sub Img_Search_click()
Dim X As Long
Dim Y As Long
X = Cells.Find(What:="*", After:=Range("A1"), LookIn:=xlValues, LookAt:= _
xlPart, SearchOrder:=xlByRows, SearchDirection:=xlPrevious, MatchCase:=False _
, MatchByte:=False, SearchFormat:=False).Row
For Y = 16 To X
If Sheets("myForm").Cells(Y, 12).Value = txt_Search.Text Then
txt_name = Sheets("myForm").Cells(Y, 7).Value
cmb_Type = Sheets("myForm").Cells(Y, 11).Value
txt_Inventory = Sheets("myForm").Cells(Y, 12).Value
txt_CardReader = Sheets("myForm").Cells(Y, 13).Value
txt_Function = Sheets("myForm").Cells(Y, 14).Value
txt_OLocation = Sheets("myForm").Cells(Y, 15).Value
txt_OPort = Sheets("myForm").Cells(Y, 16).Value
txt_NLocation = Sheets("myForm").Cells(Y, 17).Value
txt_NPort = Sheets("myForm").Cells(Y, 18).Value
txt_Printer = Sheets("myForm").Cells(Y, 19).Value
cmb_Printer_Network = Sheets("myForm").Cells(Y, 20).Value
txt_Remarks = Sheets("myForm").Cells(Y, 21).Value
Else
MsgBox "No record match from your request list.", vbInformation, "Information"
End If
Next
End Sub
字符串
我也试着像下面这样改进代码来替换Else
部分,但是“搜索”甚至不起作用!
if Sheets("myForm").Cells(Y, 12).Value <> txt_Search.Text Then
MsgBox "No record match from your request list.", vbInformation, "Information"
Me.txt_Search.Value = ""
txt_name.SetFocus
Exit Sub
end if
型
2条答案
按热度按时间bkkx9g8r1#
正如评论中所说:在只有一个匹配的情况下,for循环是不必要的。一个Application.Match就足以获得正确的行并以这种方式获得值:
字符串
注解掉的行是因为我不想充实整个表单。使用阵列来最小化与片材的相互作用。没有更多的for循环和只有一个MsgBox时,它没有找到:)
3qpi33ja2#
您将循环遍历从16到
Y
的每一行,并检查值是否匹配-如果不匹配,则显示MsgBox。所以我们假设匹配在第20行-
Y
将是20,并且您将以X = 16
开始循环第16行不匹配,因此触发MsgBox。第17行不匹配,所以触发了MsgBox第18行不匹配,所以触发了MsgBox我想你明白了。如果你尝试使用循环执行搜索功能,你不应该在循环中触发失败消息(而是在循环/搜索功能结束后)