VBA Range.Find过程 – 找不到types不匹配

我正在为我的工作场所build立一个数据库,这是一个大型科学中心的外联部门。 我们有很多学校违反了我们(非常具体)的合同,所以我们希望跟踪和减less这些违规行为。

为了减less拼写错误,使search数据库变得更加困难,我希望用户(当进入一所新学校时)拉起用户表单,input他们的学校名称,然后点击一个searchbutton来填充一个列表框符合他们的学校名称。 如果他们点击该列表中的一所学校,则该表格将其用作学校名称。 如果不是,则提示他们input新的学校名称。

我的代码现在是非常基本的。 我正在尝试使用Find&FindNext过程来提取所有学校名称的实例,但是我得到了一个types不匹配错误(#13)与我目前的代码,我无法find可能发生的情况从。 我已经检查没有variables或用户窗体对象拼写错误。

我希望Find函数只返回第一个单元格的Range,这样我就可以根据需要将它变成.Address或.Value。

Option Explicit Private Sub cbtnSearchSchool_Click() Dim lrow As Long Dim schoolmatch As Range 'defines "lrow" as the last completely empty row in the table lrow = Cells.find(What:="", _ After:=Range("A1"), _ LookIn:=xlValues, _ LookAt:=xlPart, _ SearchOrder:=xlByColumns, _ SearchDirection:=xlNext, _ MatchCase:=False, _ SearchFormat:=False).Row Range("A1").Activate 'defines "schoolmatch" variable as the first school in the list that 'matches what was entered in the text box. Set schoolmatch = Range("SchoolName").find(What:=txtbSchoolName.Value, _ After:=ActiveCell, _ LookIn:=xlValues, _ LookAt:=xlPart, _ SearchOrder:=xlByColumns, _ SearchDirection:=xlNext, _ MatchCase:=False, _ SearchFormat:=False) 'returns value of first found cell to check for accuracy MsgBox schoolmatch.Value 

如果有人想看,这是Userform的一张照片。

编辑:对不起,我实际上调整了作为一个Range最初的学校匹配,只是改变它为对象,而我正在debugging – 我得到了同样的错误之前和之后,改变它。

它向我显示了我得到的错误 – 这是Set schoolmatch = Range.Find操作,但我无法弄清楚我将混合数据types的任何地方。 我有一个SchoolName范围,我已经仔细检查,并检查了拼写错误的所有其他variables名称。

随着时间的推移,这个名单上会有成千上万的学校,所以这个searchfunction对于用户在表单上select一个学校之前过滤一些结果是必要的。

它看起来像使用Object可能会导致错误。 另外,稍微调整一下lRow的分配方式,应该会更好:

 Option Explicit Private Sub cbtnSearchSchool_Click() Dim lrow As Long Dim schoolmatch As Range 'defines "lrow" as the last completely empty row in the table lrow = Range("A1").End(xlDown).Row 'defines "schoolmatch" variable as the first school in the list that 'matches what was entered in the text box. Set schoolmatch = Range("SchoolName").find(What:=txtbSchoolName.Value, _ After:=ActiveCell, _ LookIn:=xlValues, _ LookAt:=xlPart, _ SearchOrder:=xlByColumns, _ SearchDirection:=xlNext, _ MatchCase:=False, _ SearchFormat:=False) 'returns value of first found cell to check for accuracy MsgBox schoolmatch.Value 

如果单元格A100为空,但是B100不是,那么将会错误地将该行(第100行)分配为最后一行。

如果你真的需要确保这不会发生(与你的OP一样),你可以遍历所有行直到空白。 也许这样:

 lRow = 1 Do While WorksheetFunction.CountA(Rows(lRow)) <> 0 lRow = lRow + 1 Loop Debug.print "Last row is: " & lRow 

非常感谢大家的帮助! 显然这是我想我的查找function在A1上开始,但我的命名范围从A2开始。

再次感谢大家愿意帮助像我这样的自学成才的新手清理我的代码!