【问题标题】:Checking ColorIndex property of the range of Cells检查单元格范围的 ColorIndex 属性
【发布时间】:2014-05-29 19:23:11
【问题描述】:

我有一个奇怪的问题。假设我有一系列单元格 A5-J5,我修改了它们的颜色。我根据某些条件更改 ColorIndex 属性。如果整个范围具有相同的颜色,我想触发一些动作。很容易。当我手动更改范围内所有单元格的颜色(颜色索引为 1 的黑色)时,以下代码返回“TRUE”,一切正常。

Sub test()
    If Range(Cells(5, 1), Cells(5, 10)).Interior.ColorIndex = 1 Then
        MsgBox "TRUE"
    Else
        MsgBox "FALSE"
    End If
End Sub

但是,我当然不想手动更改单元格填充。我正在使用在满足某些条件时更改其 ColorIndex 的 VBA 代码。使用 VBA 代码将整个范围更改为 ColorIndex=1 后,以下代码返回 FALSE。

Sub testt()

    If Range(Cells(5, 1), Cells(5, 10)).Interior.ColorIndex = 1 Then
        MsgBox "TRUE"
    Else
        MsgBox "FALSE"
    End If

    Dim i As Integer
    For i = 1 To 10
        MsgBox Cells(5, i).Interior.ColorIndex & " Cell no " & i

    Next i
End Sub

要检查此范围内的每个单元格是否具有相同的 ColorIndex,我会遍历它们。每个单元格的 ColorIndex=1。然而,整个范围似乎并不 - 因为它返回 FALSE。仅当我使用 VBA 更改单元格的颜色时才会发生这种情况,当我这样做时,一切运行正常。

我知道我没有提供太多细节,但是也许这里有人有类似的问题。对不起,如果这个问题太琐碎了,但我真的找不到任何合乎逻辑的解释。

【问题讨论】:

  • 不确定您的意思,因为 Range("A5:A10").Interior.ColorIndex = 1Debug.Assert Range("A5:A10").Interior.ColorIndex = 1 不会停止执行。您如何更改 vba 中的 Color 属性
  • 如果满足适当的条件,我会更改单元格的颜色。我使用 cells().interior.colorindex=1。如果我使用 VBA 将每个单元格更改为 colorindex=1,则整个范围没有 ColorIndex=1。如果我手动将单元格更改为黑色,则整个范围的 ColorIndex=1。手动更改和使用 VBA 更改之间存在一些差异,但我不知道为什么。
  • 不应该。你能展示你的完整代码吗?

标签: vba excel excel-2010


【解决方案1】:

我写了以下代码,它工作得很好:

Option Explicit

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
CheckColor
End Sub

Sub CheckColor()

Dim sh As Worksheet
Set sh = ActiveSheet

If Range(Cells(5, 1), Cells(5, 10)).Interior.ColorIndex = 1 Then
    sh.Range("A1") = "True"
Else
    sh.Range("A1") = "False"
End If

End Sub

Sub SetColor()

Dim sh As Worksheet
Dim rn As Range
Dim cl As Range

Set sh = ActiveSheet
Set rn = sh.Range("A5:J5")

For Each cl In rn
    cl.Interior.ColorIndex = 1
Next

CheckColor

End Sub

【讨论】:

  • 感谢您的代码。我用它来测试我的小项目。问题是由 NULL 值产生的。如果您检查具有多种颜色的范围的 .ColorIndex ,则返回值为 NULL 并且它弄乱了我的代码。抱歉问了一个不好的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-01-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多