我正在尝试制作一个可以使用ID号显示数据的用户表单。
我正在尝试引用一个文本框并选择它,然后将其用作参考以填写工作表中的时间和注释。我认为我不能将"txtID.Value"放入查找功能中。
这是我的代码示例:
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
函数时,建议使用 Range
对象,并将其设置为结果。此方法允许您捕获Find
无法在搜索范围内找到匹配项的可能情况Sheet1.Columns("A:A")
。
此外,尽量避免使用 Select
、 Selection
和 ActiveCell
,并使用完全限定的 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
注意:如果你有这段代码超越User_Form
模块,那么你需要在尝试获取txtID.Value
时添加User_Form
引用。
对于 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
希望这有帮助