每个循环问题的VBA Excel

时间:2017-07-13 12:13:24

标签: excel vba excel-vba

我有以下代码,它应该遍历一列休息时间和一列工作人员时间。如果工作人员时间在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

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

2 个答案:

答案 0 :(得分:3)

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

&#34;下标超出范围&#34; 错误很可能是因为FormatConditions(1)不存在。

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

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

答案 1 :(得分:0)

该行

ttlBr.FormatConditions(1).Interior.Color = 5263615

仅在单元格已具有格式条件时才起作用,否则会抛出描述的错误

相关问题