gpt4 book ai didi

每个循环问题的 VBA Excel

转载 作者:行者123 更新时间:2023-12-04 21:55:51 26 4
gpt4 key购买 nike

我有下面的代码应该循环一列休息时间和一列员工时间。如果工作人员时间在 8:28 和 8:58 之间,那么如果休息时间超过 61 分钟,则单元格应切换颜色。同样,如果工作人员时间超过 8:58,如果休息时间超过 91 分钟,则单元格应切换颜色。现在,两者都没有发生,因为代码中显然缺少某些东西。

    Dim ttlBr As Range, stfTm As Range
Dim StfTm900 As Double, StfTm830 As Double, ttlBrTm900 As Double, ttlBrTm830 As Double
StfTm900 = TimeValue("08:58:00")
StfTm830 = TimeValue("08:28:00")
ttlBrTm900 = TimeValue("01:31:00")
ttlBrTm830 = TimeValue("01:01:00")
For Each ttlBr In Range("T2:T7")
For Each stfTm In Range("H2:H7")
If stfTm > StfTm830 And stfTm < StfTm900 Then
If ttlBr > ttlBrTm830 Then
Selection.FormatConditions(1).Interior.Color = 5263615
End If
ElseIf stfTm > StfTm900 Then
If ttlBr > ttlBrTm900 Then
Selection.FormatConditions(1).Interior.Color = 5263615
End If
End If
Next stfTm
Next ttlBr

我错过了什么?

enter image description here

编辑:为清楚起见添加了图片

最佳答案

我认为最重要的错误是你在做两个嵌套循环 , 这意味着您正在检查 T2:T7 的所有单元格与 H2:H7 的所有单元格相比.您实际需要的是比较同一行上的单元格,对吗?此外,您正在设置 FormatConditions(1).Interior.Color检查后,这是没有意义的。要么设置一些FormatConditions或使用 Range.Interior.Color ,但不要混合它们。

“下标超出范围”错误很可能是由于 FormatConditions(1)这不存在。

尝试使用类似这样的格式条件而不是循环:

  With Sheet1.Range("T2:T7").FormatConditions
.Delete
.Add(xlExpression, , _
"=AND(T2>" & ttlBrTm830 & ", H2 <" & StfTm900 & ",H2 >" & StfTm830 & ")").Interior.Color = 5263615
End With

关于每个循环问题的 VBA Excel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45080276/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com