[英]Excel VBA .Find Range Anomaly
“在將我的頭發拔了四個小時之后,發現了一個有趣的東西。
如果第一列的寬度對於所使用的字體大小而言太窄,則Excel 2010 VBA似乎在合並的單元格范圍內找不到日期值。 (這類似於Excel VBA無法在隱藏的行/列中找到日期值)。
3種可能的解決方案
重現步驟:
運行以下代碼:
Sub findDate()
Dim myRange As Range
Dim myDate As Date
Dim myFindDate As Date
Dim myRow As Integer
With ActiveSheet
Set myRange = .[A2]
myFindDate = .[A4:D35].Value
On Error Resume Next
myRow = myRange.Find( _
what:=myFindDate, _
LookIn:=xlValues, _
LookAt:=xlWhole, _
SearchOrder:=xlByRows, _
SearchDirection:=xlNext, _
MatchCase:=False, _
SearchFormat:=False).Row
On Error GoTo 0
If myRow <> 0 Then
MsgBox "The date is in row number = " & myRow
Else
MsgBox "Column A too narrow. Either use LookIn:=xlFormulas, widen Column A or reduce the font size."
End If
End With
End Sub
請注意,消息框顯示了相關的行號。
現在將A列的寬度減小到2.4,然后再次運行代碼。
注意出現的消息框:Excel VBA不再能夠找到日期!
這是上面解決方案1的代碼:
Sub findDate()
Dim myRange As Range
Dim myDate As Date
Dim myFindDate As Date
Dim myRow As Integer
With ActiveSheet
Set myRange = .[A2]
myFindDate = .[A4:D35].Value
On Error Resume Next
myRow = myRange.Find( _
what:=myFindDate, _
LookIn:=xlFormulas, _
LookAt:=xlWhole, _
SearchOrder:=xlByRows, _
SearchDirection:=xlNext, _
MatchCase:=False, _
SearchFormat:=False).Row
On Error GoTo 0
If myRow <> 0 Then
MsgBox "The date is in row number = " & myRow
Else
MsgBox "Column A too narrow. Either use LookIn:=xlFormulas, widen Column A or reduce the font size."
End If
End With
End Sub
(唯一的更改是在LookIn參數中:xlFormulas而不是xlValues)
如果您運行第二行代碼,則消息框將再次顯示行號。
希望這可以減輕別人給我帶來的痛苦!
加里
我按照您的“復制步驟”指示進行操作,您的示例對我不起作用。
我注意到了一些事情。
Dim myDate As Date
Dim myFindDate As Date
Dim myRow As Integer
值可能是日期,但您正在使用范圍。 因此,正確啟動代碼,
Dim myRange As Range, myFindDate As Range, myRow As Range
然后正確設置范圍。
Set myRange = [A2]
Set myFindDate = [A4:D35]
Set myRow = myFindDate.Find(what:=myRange, lookat:=xlWhole)
通過這種方式使用代碼,列的寬度無關緊要。
完整的代碼。
Sub findDateB()
Dim myRange As Range, myFindDate As Range, myRow As Range
Set myRange = [A2]
Set myFindDate = [A4:D35]
Set myRow = myFindDate.Find(what:=myRange, lookat:=xlWhole)
If Not myRow Is Nothing Then
MsgBox "The date is in row number = " & myRow.Row
Else: MsgBox "Not Found"
Exit Sub
End If
End Sub
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.