【问题标题】:Color last cells of a series of increasing cells为一系列增加的单元格中的最后一个单元格着色
【发布时间】:2017-10-28 01:13:35
【问题描述】:

我正在尝试创建一个宏来为高于前一个的单元格着色。我只想为一系列 30 个单元格之后的单元格着色,每个单元格都比前一个单元格高。在这个截图中,如果我有这样一个系列,应该只对 E35 着色,因为从 E5 到 E35,这 30 个单元格中的每一个都严格高于它们的前任(E35>E34>E33>...>E6>E5)。

这是我尝试做的代码:

Sub Consecutive_HigherCells()

Dim i, j As Integer

For i = 32 to 10000
For j = 1 To 30

    If Cells (i,5).Value > Cells(i-j,5).Value Then

    Cells(i, 5).Select

    With Selection.Font
        .Color = -16776961
        .TintAndShade = 0
    End With

    End If

Next j
Next i

End Sub

实际上,代码不起作用,因为从 E32 到 E1000 的所有单元格至少高于 30 个高级单元格之一,当我运行它时,它会被着色。

我真的需要你的帮助

【问题讨论】:

标签: excel vba


【解决方案1】:
Option explicit

Sub Consecutive_HigherCells()

Const LIMIT as long = 30

Dim i as long, j as long, Counter as long

For i = 32 to 10000

Counter = 0

For j = LIMIT to 1 step -1

If cells(i-j-1,"E").Value2 > cells(i-j,"E").value2 Then
Counter = counter + 1
Else
Exit for
End if

Next j

If counter = LIMIT then cells(i,"E").interior.color = rgb(255,255,0)

Next i

End Sub

未经测试并在移动设备上编写,格式错误,敬请见谅。

【讨论】:

    【解决方案2】:

    下面的代码将遍历您的完整列表和颜色单元格,其中下一个顺序的值较低

    Sub HighlightCells30()
        Dim lr As Long, i As Long, count As Long
        count = 0
        lr = ActiveSheet.Range("E" & Rows.count).End(xlUp).Row
        For i = 5 To lr
            count = count + 1
            If Range("E" & i + 1).Value < Range("E" & i).Value Then
                If i <> lr And count > 30 Then
                    Range("E" & i).Interior.Color = vbYellow
                    count = 0
                End If
            End If
        Next i
    End Sub
    

    我不太明白这 30 个批次的目的是什么? 编辑:根据下面的 Scotts 解释更新代码

    【讨论】:

    • OP 希望连续 30 个数字大于上面的数字,而不仅仅是上面的数字。
    【解决方案3】:

    @Chillin > 感谢您的帮助,您已经很接近了。我修改了你的代码,它现在可以工作了。

    Option Explicit
    
    Sub Consecutive_HigherCells30()
    
    Const LIMIT As Long = 30
    
    Dim i As Long, j As Long, Counter As Long
    
    For i = 32 To 10000
    
    Counter = 0
    
    For j = LIMIT To 1 Step -1
    
    'If Cells(i - j - 1, "E").Value > Cells(i - j, "E").Value Then
    If Cells(i - j - 1, "E").Value < Cells(i - j, "E").Value Then
    
    Counter = Counter + 1
    Else
    Exit For
    End If
    
    Next j
    
    If Counter = LIMIT Then Cells(i - 1, "E").Interior.Color = RGB(255, 255, 0)
    
    Next i
    
    End Sub
    

    【讨论】:

      猜你喜欢
      • 2013-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-11
      • 1970-01-01
      • 1970-01-01
      • 2019-08-18
      • 1970-01-01
      相关资源
      最近更新 更多