[英]How to find a date time value in an excel sheet
我需要找到包含datetime值的第一个单元格。
我感兴趣的单元格显示此
2015年6月6日00:00
这是公式字段(日期部分后两个空格)
06.03.2015 00:00:00
单元格格式是这个
DD-MMM-YYYY hh:mm
我尝试了这个,但是找不到电池
Public Function FindCurrentCell() As Range
Dim cell As Range
Dim current As String
Sheets("Futures").Select
current = Format(Date, "dd.mm.yyyy") + " 00:00:00"
Set cell = Cells.Find(What:=current, After:=Range("A1"), LookIn:=xlFormulas, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False)
Dim test As String
test = cell.Address
Set FindCurrentCell = cell
End Function
如果您在网上搜索,则会发现许多网站,它们会告诉您如何查找日期。 但是,他们以魔术的形式给出了答案:“执行这一系列复杂的步骤,它将起作用。”问题是:如果它不起作用,您会怎么做?
显然您需要:
.Cells.Find(What:=DateValue(Format(DateWanted, "dd/mm/yyyy")))
其中“ dd / mm / yyyy”代表您所在国家/地区的Excel标准日期格式。
我发现的“ dd / mm / yyyy”没有任何变化将使我能够成功地找到所需格式的日期。
问题的根源是Excel如何存储日期。 当我键入此,它是9:23 2015年3月7日如果键入? CDbl(Date)
? CDbl(Date)
和CDbl(Now())
进入立即窗口,我得到:
? CDbl(Date)
42070
? CDbl(Now())
42070.3911805556
42070是自1900年1月1日以来的日期数。.3911是(自午夜以来的秒数)除以(一天中的秒数)。
因此,如果在单元格中看到“ 2015年3月7日”或“ 7/3/15”,我知道在幕后,Excel持有42070并带有.NumberFormat
告诉它42070是日期以及如何显示该日期。
专家告诉您,在DateValue(Format(DateWanted, "dd/mm/yyyy")))
您需要像Excel希望格式化日期一样获取“ dd / mm / yyyy”。 此语句的麻烦之处在于DateValue
会舍弃所有仔细的格式设置并返回日期,这又意味着什么呢?
关于格式的所有这些建议不仅是垃圾,而且显然是有害的垃圾。 重要的是“ What value”是Date类型。 例如,以下两个都是有效的:
Cells.Find(What:=Date)
Dim SearchDate As Date: SearchDate = Date
Cells.Find(What:=SearchDate)
我想提醒您,“日期”必须完全匹配; 例如,搜索“ 2015年3月7日”将不会找到“ 2015年7月7日匹配”。 实际上,这是不正确的。 似乎经常重复出现的有关此效果的建议只有在您对格式大惊小怪的情况下才是正确的。
Sub Test()
Dim RngToday As Range
Set RngToday = FindCurrentCell
If RngToday Is Nothing Then
Debug.Print "Today's date not found"
Else
Debug.Print "Today’s date in " & RngToday.Address
End If
End Sub
Public Function FindCurrentCell() As Range
Dim cell As Range
With Worksheets("Futures")
Set cell = .Cells.Find(What:=Date, After:=.Range("A1"), LookIn:=xlFormulas, _
SearchOrder:=xlByRows, SearchDirection:=xlNext)
If cell Is Nothing Then
' Today's date not found
' Add any appropriate code
Else
' Today's date found
' Add any appropriate code
End If
End With
Set FindCurrentCell = cell
End Function
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.