匹配函数查找输入今天日期的单元格
Match function to find the cell entered today's date
我正在尝试使用匹配功能来定位输入今天日期的单元格。
今天的日期是 2022 年 4 月 22 日,我需要宏 return 下面 excel sheet 中的值为 4。
下面是我的代码,它显示错误消息“运行-time error '1004': Unable to get the Match 属性 of the WorksheetFunction class。”
你能帮我修复代码吗?非常感谢
Sub FindDate()
Dim FindDate As Long
FindDate = WorksheetFunction.Match(Date, Sheet1.Rows(1), 0)
Debug.Print FindDate
End Sub
Match
是WorksheetFunction
class的成员,但需要用对象来调用。使用
FindDate = Application.Match(Date, Sheet1.Rows(1), 0)
如果找不到匹配项,WorksheetFunction.Match
将抛出错误。这就是这里发生的事情:
如果您搜索 Date
它找不到该值,因为 Excel 中的日期存储在单元格中作为自 1900-01-01
以来的天数并且该值是类型Long
(或 Double
,如果它包含时间)。因此,如果您要查找日期,则需要搜索 CDbl(Date)
。
Sub FindDate()
Dim FindDate As Long
On Error Resume Next 'hide error message if match doesn't find anything
FindDate = WorksheetFunction.Match(CDbl(Date), Sheet1.Rows(1), 0)
On Error Goto 0 're-activate error reporting !!!
If FindDate > 0 Then
Debug.Print FindDate
Else
MsgBox "Date was not found!"
End If
End Sub
我正在尝试使用匹配功能来定位输入今天日期的单元格。 今天的日期是 2022 年 4 月 22 日,我需要宏 return 下面 excel sheet 中的值为 4。 下面是我的代码,它显示错误消息“运行-time error '1004': Unable to get the Match 属性 of the WorksheetFunction class。” 你能帮我修复代码吗?非常感谢
Sub FindDate()
Dim FindDate As Long
FindDate = WorksheetFunction.Match(Date, Sheet1.Rows(1), 0)
Debug.Print FindDate
End Sub
Match
是WorksheetFunction
class的成员,但需要用对象来调用。使用
FindDate = Application.Match(Date, Sheet1.Rows(1), 0)
WorksheetFunction.Match
将抛出错误。这就是这里发生的事情:
如果您搜索 Date
它找不到该值,因为 Excel 中的日期存储在单元格中作为自 1900-01-01
以来的天数并且该值是类型Long
(或 Double
,如果它包含时间)。因此,如果您要查找日期,则需要搜索 CDbl(Date)
。
Sub FindDate()
Dim FindDate As Long
On Error Resume Next 'hide error message if match doesn't find anything
FindDate = WorksheetFunction.Match(CDbl(Date), Sheet1.Rows(1), 0)
On Error Goto 0 're-activate error reporting !!!
If FindDate > 0 Then
Debug.Print FindDate
Else
MsgBox "Date was not found!"
End If
End Sub