如何使用查找function来search文本框的值?

我正在尝试制作一个用户窗体,可以使用一个ID号码来显示数据。

我正在尝试引用一个文本框并将其选中,然后将其用作参考,以填写表单中的时间和注释。 我认为是我不能把“txtID.Value”到查找function。

这是我的代码的一个例子:

Sheet1.Select Columns("A:A").Select Selection.Find(What:="txtID.Value", After:=ActiveCell, LookIn:= _ xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:= _ xlNext, MatchCase:=False, SearchFormat:=False).Activate ActiveCell.Select ActiveCell.Offset(0, 8).Value = txtTime2 ActiveCell.Offset(0, 9).Value = txtComment2 

使用Find函数时,build议使用Range对象,并将其设置为结果。 此方法允许您捕获一个可能的场景,其中Find在search范围Sheet1.Columns("A:A")找不到匹配项。

此外,尽量避免使用SelectSelectionActiveCell ,并使用完全限定的Range对象(如下面的代码)。

 Dim FndRng As Range Set FndRng = Sheet1.Columns("A:A").Find(What:=txtID.Value, LookIn:=xlFormulas, LookAt:=xlPart, _ SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False) If Not FndRng Is Nothing Then ' successful find FndRng.Offset(, 8).Value = txtTime2 FndRng.Offset(, 9).Value = txtComment2 Else ' unable to fins the value in txtID MsgBox "Unable to find " & txtID.Value & " in Sheet1" End If 

注意 :如果你有这个代码outisde User_Form模块,那么你需要添加User_Form引用时,试图获取txtID.Value

对于eaxmple,假设表单的名称是UserForm1 ,然后将此行更改为:

 Set FndRng = Sheet1.Columns("A:A").Find(What:=UserForm1.txtID.Value, LookIn:=xlFormulas, LookAt:=xlPart, _ SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False) 

要使其工作,你将不得不把代码如下,这是相当自我解释。

 Selection.Find(What:=Userform1.textbox1.value, After:=ActiveCell, LookIn:= _ xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:= _ xlNext, MatchCase:=False, SearchFormat:=False).Activate ActiveCell.Select 

希望这可以帮助