【问题标题】:Setting cell (n) Color Index equal to cell (n - 1) Color Index设置单元格 (n) 颜色索引等于单元格 (n - 1) 颜色索引
【发布时间】:2018-08-16 12:19:19
【问题描述】:

我从这个宏中得到一个奇怪的输出。宏应该用上面的颜色填充空白单元格,创建一个颜色块。即使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

附:这是我试图回答 this 问题的尝试,因为这就是我学习/练习 VBA 的方式:)

【问题讨论】:

标签: excel vba


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-24
    • 1970-01-01
    • 2019-09-06
    • 1970-01-01
    相关资源
    最近更新 更多