'发现了一个有趣的 - 经过4个小时的撕裂我的头发。
如果第一列的宽度对于使用的字体大小来说太窄,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)
如果运行第二位代码,消息框将再次显示行号。
'希望这可以节省别人给我带来的痛苦!!
加里
答案 0 :(得分:0)
我按照您的“重现步骤”说明操作,您的示例对我不起作用。
我注意到了一些事情。
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