【问题标题】:vba FOR to validate color of cells in a rangevba FOR验证范围内单元格的颜色
【发布时间】:2017-11-03 07:13:11
【问题描述】:

我正在做一个宏来通过颜色索引检查和验证所有单元格。如果我的代码有错误,请帮助我。非常感谢。

    Sub Validate()
Dim rng As Range: Set rng = Application.Range("CATALOG!B2:F98")
Dim cel As Range
Dim i As Boolean

i = False

For Each cel In rng
With cel
    If .Interior.ColorIndex = 6 Then
        If .EntireRow.Hidden = False Then
            i = True
        End If
    End If
   End With
   Next cel

 If i = True Then
  MsgBox "yellow"
Else
  MsgBox "none"
End If

End Sub

【问题讨论】:

  • 你的代码在哪里?
  • 你得到错误还是什么?我可以告诉你,无论如何你只会运行 1 个单元格,因为你 Exit Sub 在你的 IF..ELSE 的两个部分中。我会假设如果您输入 Else 语句就可以了,因此您不会退出子。
  • 你不需要在你的'With语句中重复'cel'。我也认为您想删除两个“退出子”,但也许这就是您想要的?此外,您可以使用“For Each cel in rng”,因此无需 .Cells...
  • 嗨。谢谢你。请立即查看我的代码。但我现在的问题是提示说黄色但我不再有黄色单元格,我担心它也会检测到隐藏的单元格。我怎样才能只合并活动单元格而忽略隐藏单元格的值。谢谢
  • 在您的 If 语句中添加一个检查,以便 If .Interior.ColorIndex = 6 Then 变为 If .Interior.ColorIndex = 6 and not (.entirerow.Hidden or .entirecolumn.Hidden) Then

标签: excel validation loops colors vba


【解决方案1】:

不清楚你在问什么,但有两种方法:

1) 首先,当您要检查范围内的每个单元格是否具有.Interior.ColorIndex = 6 时。那么你的代码应该是这样的:

Sub Validate()
Dim rng As Range: Set rng = Application.Range("CATALOG!B2:F98")
Dim cel As Range
Dim i As Boolean

i = True
For Each cel In rng.Cells
    If Not cel.Interior.ColorIndex = 6 Then
        i = False
        Exit For 'we found cell with different color, so we can exit loop
    End If
Next cel

If i = True Then
    MsgBox "yellow"
Else
    MsgBox "none"
End If

End Sub

2) 你想检查是否有任何单元格有.Interior.ColorIndex = 6。那么它应该是这样的:

Sub Validate()
Dim rng As Range: Set rng = Application.Range("CATALOG!B2:F98")
Dim cel As Range
Dim i As Boolean

i = False
For Each cel In rng.Cells
    If cel.Interior.ColorIndex = 6 Then
        i = True
        Exit For 'we found cell with the color, so we can exit loop
    End If
Next cel

If i = True Then
    MsgBox "yellow"
Else
    MsgBox "none"
End If

End Sub

【讨论】:

  • 嗨。请看我上面的代码..它仍然不准确。即使我在可见单元格上不再有黄色,它也会提示“黄色”。
【解决方案2】:

在我控制的内容中,您正试图遍历所有非隐藏单元格,看看它们是否具有黄色背景色,如果它们是黄色,则需要根据输入进行更改。

Sub Validate()

Dim rng As Range: Set rng = Application.Range("CATALOG!B1:F98")
Dim cel As Range

For Each cel In rng
    With cel
        If .Interior.ColorIndex = 6 Then
            If .EntireRow.Hidden = False Then
                .Interior.ColorIndex = InputBox("please input new colorIndex", "SetColorIndex")
            End If
        End If
   End With
Next cel

End Sub

【讨论】:

  • 嗨。请看我上面的代码..它仍然不准确。即使我在可见单元格上不再有黄色,它也会提示“黄色”。
  • 你想要提示吗?否则,您的黄色与 ColorIndex 6 不对应。如果它在隐藏行内,我的代码不会提示黄色(ColorIndex 6)背景。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-07-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多