VBA - 循环行并根据条件插入值

VBA - to Loop rows and insert value based on condition

我的问题是关于 excel VBA 循环。我希望循环在更改某些单元格值时从头开始填充结果。

我写了一个宏来循环行并根据条件插入值,但是我遇到了困难,因为我在包含一个额外的条件以在单元格值更改时再次开始循环。

条件 1 = 当订单日期时间超过 21:00 小时时应该开始计算时间 window,但是我想循环直到新日期到来并开始填充 window 从下一个日期 21:00

开始的时间

考虑 1 名受让人可以在 1 小时内处理 10 个订单,而 2 名受让人可以在 1 小时内处理 20 个订单,依此类推....

Sub EstimatedTimeWindow()
Dim i as long, n as long,
Dim x as double
Dim p as long

    No_of_Orders = 20
    No_of_Assignee  = 2
    OrdersinHour = No_of_Orders  * No_of_Assignee

   Worksheets("final_data").select
   n = cells(rows.count,"A").end(xlup).row
   p = 0

   For i = 2 to n
   x = (1* cells(i,"A")/1)) - Int(Cells(i,"A")) 'to check the time
  If x >= 0.875 'time as 21:00
     p = p + 1
       If p <= OrdersinHour Then
          Cells(i,"B") = "Estimated window time 21:00 - 22:00"
       End If
       If p > OrdersinHour AND p <= OrdersinHour * 2 Then
          Cells(i,"B") = "Estimated window time 22:00 - 23:00"
       End if
       If p > OrdersinHour AND p <= OrdersinHour * 3 Then
          Cells(i,"B") = "Estimated window time 23:00 - 00:00"
       End if
       If p > OrdersinHour AND p <= OrdersinHour * 4 Then
          Cells(i,"B") = "Estimated window time 00:00 - 01:00"
       End if
  End if
Next
End Sub

误读问题:我把那个答案留在下面了,但是可以忽略。更新的答案添加到开头:

不要删除 x 中的日期 - 然后,当单元格中的日期与 行的日期不同时,重置 p 到 0

For i = 2 to n
    If Int(I) <> Int(cells(I,1).Value Then 'Order Date has changed day
        p = 0 'Reset counter p to 0
    End If
    x = cells(i,1).Value 'to check the time
    If (x mod 1) >= 0.875 'time as 21:00
'Continue as normal

您可以在特定时间使用 Application.OnTime 调用宏 - 但是,如果您关闭工作簿但 Excel 打开它 重新打开工作簿以 运行 宏,除非您禁用 OnTime。它变得...凌乱。

更好的解决方案是在工作表上的值更改时使用 Worksheet_Change 事件来 运行 代码:

Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Intersect(Target, Me.Columns(1)) Is Nothing Then 'A Cell in Column A changed
        Call EstimatedTimeWindow
    End If
End Sub

此外,对现有代码进行快速调整:x = Cells(i, 1).Value Mod 1 会让您有时间使用更清晰的代码,Hour 语句比 0.875 和 Switch 语句更易于阅读p 也会使您的代码更清晰:

For i = 2 to n
    If Int(x) <> Int(Cells(i,1).Value) Then
        p = 0
    End If
    x = Cells(i, 1).Value 'Since we take the Hour, no need to trim the date off first
    If Hour(x) >= 9 Then
        p = p + 1
        Select Case (p\OrdersinHour) 'Same as Int(p/OrdersinHour)
            Case 0:
                Cells(i,2).value = "Estimated window time 21:00 - 22:00"
            Case 1:
                Cells(i,2).value = "Estimated window time 22:00 - 23:00"
            Case 2:
                Cells(i,2).value = "Estimated window time 23:00 - 20:00"
            Case 3:
                Cells(i,2).value = "Estimated window time 00:00 - 01:00"
        End Select
    End IF
Next