如何应用搜索方向查找首次出现?



在MS Excel中,我有VBA代码,可以在一个范围内查找一个月中的几天。

范围类似于 1,2,3,...,30,1(列),因为有些月份有 30 天,而有些月份有 31 天。

当尝试在范围内查找"1"时,代码总是给出第二个"1"。

当我从范围中删除第二个"1"时,它会给出正确的结果。

在这种情况下,"搜索方向"似乎没有任何作用。

day = 1
Set findday = findmonth.Find(day, LookIn:=xlValues, LookAt:=xlWhole, SearchDirection:=xlNext, SearchOrder:=xlByColumns)
Debug.Print findday.Address

查找方法"失败">

  • 如果将xlValuesLookIn参数一起使用,则如果隐藏了要查找值的行或列,则Find将"无法"找到它。
  • 默认情况下,Find方法使用xlNext表示SearchDirection因此您可以省略它。
  • 你的问题肯定是省略了After论点。 问题是,如果您输入第一个单元格 (A1) 作为After参数的参数(默认情况下为 (A1)),搜索将从A2开始,如果xlByColumnsB1如果xlByRows。因此,您必须为Find方法指定区域中的最后一个单元格,以便使用区域中的第一个单元格 (A1) 开始搜索。

例如:

Day = 1
Set findday = findmonth.Find( _
What:=Day, _
After:=findmonth.Cells(findmonth.Rows.Count, findmonth.Columns.Count), _
LookIn:=xlFormulas, _
LookAt:=xlWhole, _
SearchOrder:=xlByColumns, _
SearchDirection:=xlNext)
Debug.Print findday.Address

或者,如果您更喜欢一行:

Dim findday As Range
Day = 1
Set findday = findmonth.Find(What:=Day, After:=findmonth.Cells(findmonth.Rows.Count, findmonth.Columns.Count), LookIn:=xlFormulas, LookAt:=xlWhole, SearchOrder:=xlByColumns, SearchDirection:=xlNext)
Debug.Print findday.Address

使用With语句,您可以使其更具可读性:

Day = 1
With findmonth
Set findday = .Find(What:=Day, After:=.Cells(.Rows.Count, .Columns.Count), LookIn:=xlFormulas, LookAt:=xlWhole, SearchOrder:=xlByColumns)
End With
Debug.Print findday.Address

最新更新