我从这个宏中得到了一个奇怪的输出。宏应使用上面的颜色填充空白单元格,从而创建一个颜色块。即使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
P.S。这是我尝试回答this的问题,因为这是我学习/练习VBA的方式:)
答案 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