简体   繁体   English

从 Excel VBA 中的日期和时间数据中删除时间

[英]Delete time from Date&Time Data in Excel VBA

image_1

As shown in image_1, I have a column of raw date data that comes with time.如图 1 所示,我有一列随时间而来的原始日期数据。 I want to get rid of it so that it only shows date (as shown in image_2)我想摆脱它,让它只显示日期(如图 2 所示)

image_2 . .

I can simply achieve this with the code columns("A").numberformat="mm/dd/yyyy" .我可以通过代码columns("A").numberformat="mm/dd/yyyy"简单地实现这一点。 However, I found this doesn't really get rid of the time but instead simply hide it.但是,我发现这并没有真正摆脱时间,而是简单地隐藏它。 I'm looking for some VBA code that not only visually but in fact removes the time.我正在寻找一些 VBA 代码,它们不仅在视觉上而且实际上消除了时间。 The expected result should just be like image_2, but when I click into any of the cells and in the formula bar, there's no time shown either.预期的结果应该就像 image_2,但是当我单击任何单元格并在公式栏中时,也没有显示时间。

Appreciate any thoughts on this.感谢您对此的任何想法。

One option using INT :使用INT的一种选择:

Sheet1.Range("A2:A19").Value = Sheet1.Evaluate("=INT(A2:A19)")

Or a loop:或循环:

Sub Test()
    Dim i As Long
    For i = 2 To 19
        With Sheet1.Range("A" & i)
            If IsDate(.Value) Then
                .Value = Int(.Value)
                .NumberFormat = "mm/dd/yyyy"
            End If
        End With
    Next
End Sub

EDIT : Probably worth finding the last row:编辑:可能值得找到最后一行:

With Sheet1
    Dim lastRow As Long
    lastRow = .Cells(.Rows.Count, 1).End(xlUp).Row

    .Range("A2:A" & lastRow).Value = .Evaluate("=INT(A2:A" & lastRow & ")")
    .Range("A2:A" & lastRow).NumberFormat = "mm/dd/yyyy"
End With

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM