'发现一个有趣的 - 经过4个小时的撕裂我的头发 .
如果第一列的宽度对于使用的字体大小而言太窄,则Excel 2010 VBA似乎不会在合并的单元格范围内找到日期值 . (这类似于Excel VBA无法在隐藏的行/列中查找日期值) .
3 Possible Solutions: best first
-
将LookIn参数更改为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
(唯一的变化是在LookIn参数中:xlFormulas而不是xlValues)
如果运行第二位代码,消息框将再次显示行号 .
“希望这可以节省别人给我带来的痛苦!
加里
1 回答
我按照你的“重现步骤”说明,你的例子不适合我 .
我注意到的一些事情 .
值可能是日期,但您正在使用范围 . 所以正确启动代码,
然后正确设置范围 .
以这种方式使用代码,列的宽度无关紧要 .
完整的代码 .