|
- Sub DetectAndHighlightAnomalies()
- Dim lastRow As Long
- Dim i As Long
- Dim isIncreasing As Boolean
- Dim isDecreasing As Boolean
- Dim rangeToCheck As Range
- Dim firstAnomalyCell As Range
-
- ' 获取K列和M列最后一行有数据的行号
- lastRow = Cells(Rows.Count, "K").End(xlUp).Row
-
- ' 设置要检查的区域为K列和M列的数据区域
- Set rangeToCheck = Union(Range("K1:K" & lastRow), Range("M1:M" & lastRow))
-
- ' 遍历区域中的每个单元格,检查数据趋势
- For i = 2 To lastRow
- If Cells(i, "K") > Cells(i - 1, "K") Then
- isIncreasing = True
- isDecreasing = False
- ElseIf Cells(i, "K") < Cells(i - 1, "K") Then
- isIncreasing = False
- isDecreasing = True
- End If
-
- If Cells(i, "M") > Cells(i - 1, "M") Then
- If Not isIncreasing Then
- If firstAnomalyCell Is Nothing Then
- Set firstAnomalyCell = Cells(i, "K")
- If Cells(i, "K") = Cells(i, "M") Then
- Set firstAnomalyCell = Cells(i, "M")
- End If
- End If
- Cells(i, "K").Interior.Color = RGB(0, 255, 0)
- Cells(i, "M").Interior.Color = RGB(0, 255, 0)
- End If
- isIncreasing = True
- isDecreasing = False
- ElseIf Cells(i, "M") < Cells(i - 1, "M") Then
- If not isDecreasing Then
- If firstAnomalyCell Is Nothing Then
- Set firstAnomalyCell = Cells(i, "K")
- If Cells(i, "K") = Cells(i, "M") Then
- Set firstAnomalyCell = Cells(i, "M")
- End If
- End If
- Cells(i, "K").Interior.Color = RGB(0, 255, 0)
- Cells(i, "M").Interior.Color = RGB(0, 255, 0)
- End If
- isIncreasing = False
- isDecreasing = True
- End If
- End For
-
- ' 如果找到异常单元格,定位到第一个异常单元格
- If Not firstAnomalyCell Is Nothing Then
- firstAnomalyCell.Select
- End If
- End Sub
- Sub ClearColors()
- Dim lastRow As Long
- Dim rangeToClear As Range
-
- ' 获取K列和M列最后一行有数据的行号
- lastRow = Cells(Rows.Count, "K").End(xlUp).Row
-
- ' 设置要清除颜色的区域为K列和M列的数据区域
- Set rangeToClear = Union(Range("K1:K" & lastRow), Range("M1:M" & lastRow))
-
- ' 清除区域内单元格的颜色
- rangeToClear.Interior.ColorIndex = xlColorIndexNone
- End Sub
复制代码 |
|