将单元格(n)的颜色索引设置为等于单元格(n-1)的颜色索引

时间:2018-08-16 03:17:10

标签: excel vba

我从这个宏中得到了一个奇怪的输出。宏应使用上面的颜色填充空白单元格,从而创建一个颜色块。即使Debug.Print显示相同的ColorIndex数字,结果也不是我所期望的。

知道这里发生了什么吗?

Option Explicit

Sub Crayon()

Dim ws As Worksheet: Set ws = ThisWorkbook.Sheets("Sheet1")
Dim MyCell As Range

For Each MyCell In ws.Range("A2:A" & ws.Range("A" & ws.Rows.Count).End(xlUp).Row)
    If MyCell.Interior.ColorIndex = -4142 Then
        If MyCell.Offset(-1).Interior.ColorIndex <> -4142 Then
            MyCell.Interior.ColorIndex = MyCell.Offset(-1).Interior.ColorIndex
        End If
    End If
Next MyCell

End Sub

我曾经跟随宏在照片上产生Column G,该照片显示了由上面的宏Crayon产生的每个单元的颜色指数。我不确定如何用相同的颜色索引解释不匹配的颜色的输出。

Sub Index_Output()

Dim ws As Worksheet: Set ws = ThisWorkbook.Sheets("Sheet1")
Dim i

For i = 2 To 17
    ws.Range("G" & i) = ws.Range("C" & i).Interior.ColorIndex
Next i

End Sub

enter image description here

P.S。这是我尝试回答this的问题,因为这是我学习/练习VBA的方式:)

1 个答案:

答案 0 :(得分:1)

颜色的变化归因于ColorIndex的性质,MSDN的注释表示调色板中颜色的索引。来自不同调色板的颜色将具有相同的索引号,因此请使用Color而不是ColorIndex

在最里面的ColorIndex内将Color更改为If...End IF

Sub Crayon()

Dim ws As Worksheet: Set ws = ThisWorkbook.Sheets("Sheet1")
Dim MyCell As Range

For Each MyCell In ws.Range("A2:A" & ws.Range("A" & ws.Rows.Count).End(xlUp).Row)
    If MyCell.Interior.ColorIndex = xlNone Then
        If MyCell.Offset(-1).Interior.ColorIndex <> xlNone Then
            MyCell.Interior.Color = MyCell.Offset(-1).Interior.Color
        End If
    End If
Next MyCell

End Sub