2
'找到一個有趣的 - 4小時後,我的頭髮撕了出來。Excel VBA。找到範圍異常
如果第一列的寬度對於使用的字體大小太窄,似乎Excel 2010 VBA將無法在合併範圍內的單元格中找到日期值。 (這與Excel VBA無法在隱藏行/列中查找日期值類似)。
3個可能的解決方法:最好先
- 更改看着參數xlFormulas。
- 擴展列直到宏使用LookIn:= xlValues。
- 縮小字體大小,直到宏使用LookIn:= xlValues。
重現步驟:
- 插入一個日期到A2(例如7/3)。
- 合併橫跨4列(A2:D2) - 這是要找到日期的字段
- 在單元格A4:A35(例如1/3到31/3)中創建一組連續日期。
- 合併不同4列(A4:D35)
運行下面的代碼:
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
(唯一的變化是在看着參數:xlFormulas代替xlValues)
如果運行的代碼此第二比特,所述消息框會再次顯示行號。
'希望這可以節省別人給我帶來的痛苦!
Gary