首页 文章

比较两个单元格的颜色并删除行

提问于
浏览
0

我正在尝试突出显示我的工作表单元格中包含红色相同字符串的两列中的单元格,然后删除包含具有两个红色单元格的行的所有行 .

这就是我到目前为止所提出的 . 第一阶段工作,但后来我试图比较两个单元格的颜色,但它不起作用 .

Option Explicit

Sub Macro1()

Dim WhatFor As String

WhatFor = InputBox("Enter your search word to highlight", "Search Criteria")
If WhatFor = Empty Then Exit Sub

Range("A1").Select
Selection.CurrentRegion.Select
Selection.FormatConditions.Add Type:=xlTextString, String:=WhatFor, _
  TextOperator:=xlContains
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority

With Selection.FormatConditions(1).Font
    .Color = -16383844
    .TintAndShade = 0
End With
With Selection.FormatConditions(1).Interior
    .PatternColorIndex = xlAutomatic
    .Color = 13551615
    .TintAndShade = 0
End With
Selection.FormatConditions(1).StopIfTrue = False

End Sub


Sub Macro2()

Dim i As Integer
Dim cell As Range

cell = ActiveWorkbook.ActiveSheet.Range

i = 1

Do While Cells("A, i").Value <> ""

    If cell("A, i").Interior And cell("F, i").Interior = 13551615 Then:      
        Rows(i).EntireRow.Delete
    End If

    i = i + 1

Loop

End Sub

example of my sheet

1 回答

  • 0

    代码中的错误符合您的IF语句:

    If (Cells(i, "A").Interior.Color = 13551615) And (Cells(i, "F").Interior.Color = 13551615) Then
    

    应该:

    If (cell("A, i").Interior = 13551615) And (cell("F, i").Interior = 13551615) Then:
    

    不幸的是,条件格式不会影响.InteriorColor . 它确实改变了单元格的颜色,但我们不能这样检查它 .

    目前无法检查实际显示的颜色 .

    可以构建一个函数来模拟单元格的所有条件格式中的条件,但只要Microsoft为条件格式添加其他类型的条件,就必须更新该函数 . 可以找到一个很好的示例:here :(请注意,此函数返回colorindez而不是颜色)


    另一个逻辑问题是删除行:

    'This method does not check each row!
    i = 1
    Do While Cells(i, "A").Value <> ""
        If '<your condition>
            Rows(i).EntireRow.Delete
        End If
    i = i + 1
    Loop
    

    我们假设 i = 5 ,你想要删除那一行 . 原始行5被删除,第6行变为第5行,第7行变为第6行,等等 .

    然后我变成6,你检查那行(原来是第7行......)

    这样,原来的第6行永远不会被检查......

    在这种情况下,通常最好从最后一行开始,然后向上工作 . 或者您可以使用 .rows 属性和 FOR EACH 构造:

    Dim row As Range
    
    For Each row In [A1].CurrentRegion.Rows
      If Intersect(row, [B:B]).Value Like "*" & WhatFor  & "*" Then
        row.Delete
      End If
    Next row
    

    (此版本仅检查1列,以B列为例)


    但是,问题的答案就是jsotola所说的:" it makes absolutely no sense to color the cells? just delete the rows" - jsotola 17分钟前


    如果我想删除行而不着色单元格 - 基本代码应该如何?我需要比较“搜索”中的单元格而不是“相等” . 仅比较每个单元格中的部分字符串 .

    谢谢:-) - yaeer,1分钟前

相关问题