【发布时间】:2015-06-04 03:25:36
【问题描述】:
'发现一个有趣的 - 在我拔掉头发 4 小时后。
如果第一列的宽度对于所使用的字体大小来说太窄,Excel 2010 VBA 似乎不会在合并的单元格范围内找到日期值。 (这类似于 Excel VBA 无法在隐藏的行/列中找到日期值)。
3 种可能的解决方案:最好的优先
- 将 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)
如果您运行第二段代码,消息框将再次显示行号。
'希望这可以减轻其他人给我带来的痛苦!
加里
【问题讨论】: