在Ms Excel
我有一个VBA代码看起来在一个范围内找到一个月的日子。范围像1,2,3,...,30,1(在列中),因为有些月份有30天,而有些月份则有31天。当试图在范围代码中找到“ 1”时,请始终输入第二个“ 1” “ 结果是。当我从范围中删除第二个“ 1”时,它将给出正确的结果。在这种情况下,“ SearchDirection”似乎无能为力。这是什么原因呢?
我使用的代码:
day = 1
Set findday = findmonth.Find(day, LookIn:=xlValues, LookAt:=xlWhole, SearchDirection:=xlNext, SearchOrder:=xlByColumns)
Debug.Print findday.Address
xlValues
与该LookIn
参数一起使用,则如果您希望在其中查找值的行或列被隐藏,Find
则将“失败”查找它。Find
方法使用xlNext
for,SearchDirection
因此您可以忽略它。After
论点。问题是,如果您输入第一个单元格(A1
)作为参数的After
参数(默认为(A1
)),则搜索将从A2
ifxlByColumns
或B1
if开始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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句