【问题标题】:How can I compare two dates in Excel VBA?如何在 Excel VBA 中比较两个日期?
【发布时间】:2014-07-18 11:43:20
【问题描述】:

我正在做一个学校项目来比较 date1 是否等于 date2 - 1(date1 比 date2 早一天)。

date2 位于 date1 下一个单元格。这将放置在 if/else 语句中,比较将返回布尔值。

这是我正在处理的代码,

Sub someLoop()

Dim night As Long
night = 1

Dim c As Long

Dim max_rows As Long

max_rows = UsedRange.Rows.Count

For c = 2 To max_rows
    Range("A" & c).Select
    If ActiveCell.Value = ActiveCell.Offset(1, 0).Value2 - 1 Then
        night = night + 1
    Else
        ActiveCell.Offset(0, 2).SetValue = night
        night = 1
    End If

Next c

End Sub

【问题讨论】:

    标签: excel vba date


    【解决方案1】:

    Excel 中的日期可以像数字一样处理。

    所以,如果 [A1] 有 28-May-14 而 [A2] 有 29-May-14,那么你可以写出公式:=(A1=A2-1)

    【讨论】:

    • 我在问如何在 VBA if 语句中做到这一点。现在我坚持这一点,“如果 ActiveCell.Value = ActiveCell.Offset(1, 0).Value - 1 Then”,其中 ActiveCell.Value = date1 和 ActiveCell.Offset(1, 0).Value = date2
    • 你写的不是VBA语句吗?如果 ActiveCell.Value = ActiveCell.Offset(1, 0).Value - 1 那么也许你可以使用 ActiveCell.Value2 来获取底层数字?
    • 是的,它是一个 VBA 语句,但它没有执行我想要的操作
    • 我认为您需要提供更多详细信息。 “它没有表现出我想要的”并不足以引起人们的注意。您是否尝试过使用 .Value2?
    【解决方案2】:

    我会使用DATEDIFF

    例如:

    dateDiff("d", date2 , date1) = 1
    

    使用date2 = 28.05.2014date1 = 29.05.2014d 定义您想要按天计算的差异。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多