在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
查找方法"失败">
- 如果将
xlValues
与LookIn
参数一起使用,则如果隐藏了要查找值的行或列,则Find
将"无法"找到它。 - 默认情况下,
Find
方法使用xlNext
表示SearchDirection
因此您可以省略它。 - 你的问题肯定是省略了
After
论点。 问题是,如果您输入第一个单元格 (A1
) 作为After
参数的参数(默认情况下为 (A1
)),搜索将从A2
开始,如果xlByColumns
或B1
如果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