excel 如何从列中获取最近的日期和时间

56lgkhnf  于 2022-12-14  发布在  其他
关注(0)|答案(2)|浏览(212)

I'm trying to obtain the most recent date and time from a column using VBA excel.
The issue here is that once I run the macro, I obtain the correct most recent date, but the time obtained remains in a 00:00:00 value as shown in the image.
Table with dates and macro result
How can I obtain the most recent time and date from the B column correctly?
I tried

Sub ObtainNewestDateTimeofaColumn()

   Max_DateTime = Application.WorksheetFunction.Max(Columns("$B:$B"))         
   Max_Date = Format((CDate((Split(Max_DateTime, ".")(0)))), "dd/mm/yyyy hh:mm:ss")    
   MsgBox (Max_Date)

   End Sub

and obtained the result : "26/02/2022 00:00:00"
The result I was expecting was: "26/02/2022 11:45:00"

q8l4jmvw

q8l4jmvw1#

我不知道你的Max_Date = ...行是怎么回事,但是格式应该可以。

Option Explicit

Sub MaxValueOutput()
    
    Dim RefRG As Range
    Dim DT_TM As String
    
    Set RefRG = Sheet1.Range("A2:A7")   ' Or your range
    
    DT_TM = Format(Application.WorksheetFunction.Max(RefRG), "yyyy-mm-dd hh:mm:ss")
    MsgBox DT_TM, vbOKOnly, "Demontration Only"
    
End Sub

您可能更喜欢稍有不同的数字格式...但这应该没关系。

suzh9iv8

suzh9iv82#

问题出在您的Split函数中。日期是以十进制数字储存的,其中整数部分是自1899年12月31日以来的天数,而小数部分则是一天(或时间)的分数。
而且VBA在许多领域都是以美国为中心的(十进制为点
当您对小数执行Split运算并返回结果数组中的第一个元素时,实际上是从datetime值中删除了时间部分,因此结果中缺少时间。
Max_Date=行更改为:

Max_Date = Format(max_datetime, "dd/mm/yyyy hh:mm:ss")

相关问题