【问题标题】:Advanced DateDiff using MSExcel使用 MSExcel 的高级 DateDiff
【发布时间】:2011-01-21 21:02:57
【问题描述】:

我有一个 Excel 电子表格,列出了工作轮班...四列对我们的目的很重要:

  • 开始日期
  • 开始时间
  • 结束日期
  • 结束时间

鉴于这些数据,我需要抽象出 7am7pm 之间每个班次的小时数。

需要记住的几件事...

  • 班次长度没有理论上的限制。它可以运行 1 小时到 3 天不等。
  • 我对 C#、VB、PHP 甚至是高级 Excel 函数的解决方案持开放态度......任何可以找到解决方案的方法。
  • 【问题讨论】:

    • 日期和时间是如何存储在电子表格中的?您是否使用实际的 Excel 日期或时间字段格式?如果是这样,那么您应该能够只说结束开始,这将使您知道轮班的时间。从那里您可以检查是否 早上 7 点并结束

    标签: excel datediff


    【解决方案1】:

    VBA ,不考虑分钟。我不知道你是否需要几分钟。

    Dim i As Integer
    Dim ShiftRange As Range
    Dim dteStart As Date
    Dim dteEnd As Date
    Dim HourCount As Long
    Dim MinCount As Long
    
    Set ShiftRange = Sheet1.UsedRange
    
    For i = 2 To ShiftRange.Rows.Count
        HourCount = 0
        dteStart = CDate(Cells(i, 1) + Cells(i, 2))
        dteEnd = CDate(Cells(i, 3) + Cells(i, 4))
    
        Do While dteStart <= dteEnd
            If Hour(dteStart) >= 7 And Format(dteStart, "hh:mm") <= #7:00:00 PM# Then
                HourCount = HourCount + 1
            End If
    
            dteStart = DateAdd("h", 1, dteStart)
        Loop
    
        MinCount = HourCount * 60
    
        ''Minutes
        If CDate(Cells(i, 2)) >= #7:00:00 AM# And CDate(Cells(i, 2)) <= #7:00:00 PM# Then
             MinCount = MinCount - Minute(CDate(Cells(i, 2)))
        End If
    
        If CDate(Cells(i, 4)) >= #7:00:00 AM# And CDate(Cells(i, 4)) <= #7:00:00 PM# Then
            MinCount = MinCount + Minute(CDate(Cells(i, 4)))
        End If
    
        Cells(i, 6) = MinCount 
    Next
    

    这假定 A、B、C 和 D 是包含日期和时间的列,并且列 F 为空。

    【讨论】:

      【解决方案2】:

      谢谢雷穆 非常好用。

      我进行了更改以允许部分时间

      Sub DayHours()
      Dim i As Integer
      Dim ShiftRange As Range
      Dim dteStart As Date
      Dim dteEnd As Date
      Dim MinCount As Double
      
      Set ShiftRange = Sheet1.UsedRange
      
      For i = 3 To ShiftRange.Rows.Count
      MinCount = 0
      dteStart = CDate(Cells(i, 3) + Cells(i, 4))
      dteEnd = CDate(Cells(i, 5) + Cells(i, 6))
      
      Do While dteStart <= dteEnd
          If Format(dteStart, "hh:mm") >= #7:00:00 AM# And Format(dteStart, "hh:mm") < #7:00:00 PM# Then
              MinCount = MinCount + 1
          End If
      
          dteStart = DateAdd("n", 1, dteStart)
      Loop
      Cells(i, 10) = MinCount / 60
      Next
      End Sub
      

      【讨论】:

      • 我对分钟数的处理方式略有不同。我会在上面添加。
      猜你喜欢
      • 2010-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-15
      • 1970-01-01
      • 1970-01-01
      • 2011-02-03
      相关资源
      最近更新 更多