单元格内部颜色索引Excel VBA

基于语言表,列A =语言,B =数字,C =彩色单元格

我想知道什么是VBA,所以无论何时在列B(使用Workbook_SheetChange)上键入一个数字,C都会使用Colorindex与input的数字相同的颜色。

另一方面,我相信是上一个问题的解决scheme的一部分,关于VBA,我该如何编写cell.Interior.ColorIndex =(一个特定的单元格的值,如果B2 = 4 – >行,整个或直到最后一列有数据,cell.Interior.ColorIndex = 4)并为整行着色。

谢谢

sheetchange函数具有作为参数的target ,这是您更改的单元格。 您可以使用它来更改相关的单元格:

 Private Sub Worksheet_Change(ByVal Target As Range) If Target.Column = 2 Then Target.Offset(0,1).Interior.ColorIndex = Target.Value 'and for the whole row Target.EntireRow.Interior.Color = Target.Offset(0,1).Interior.Color Endif End Sub 

Nick Dewitt的代码是可以的,但是它只能为C列着色。

如果要为整行着色,则从C开始,具体取决于行中有多less列:

 Private Sub Worksheet_Change(ByVal Target As Range) Dim lastcol As Integer, i As Integer If Target.Column = 2 Then lastcol = Cells(Target.Row, Columns.Count).End(xlToLeft).Column For i = 3 To lastcol Target.Offset(0, i - 2).Interior.ColorIndex = Target.Value Next i End If End Sub 

用鼠标右键单击表单的名称,然后点击“查看代码”。

现在,您需要编写一个VBA函数,对工作表进行任何更改。 这是一个名为Worksheet_Change(Range)的内置函数。 范围对象(它的参数)是这个函数触发时改变的范围。

 Private Sub Worksheet_Change(ByVal Target As Range) End Sub 

在函数内部,您需要检查更改的单元格是否在列B中。这由目标范围的列属性完成。

 Private Sub Worksheet_Change(ByVal Target As Range) If Target.Column = 2 Then ' The changed cell was in column B End If End Sub 

现在您需要获取单元格的值并将其作为行的ColorIndex。

 Private Sub Worksheet_Change(ByVal Target As Range) If Target.Column = 2 Then ColorValue = Target.Value Target.EntireRow.Interior.ColorIndex = ColorValue End If End Sub 

编辑:要将单元格仅着色到行中的最后一个值,则需要计算行中已填充单元格的数量。 下面的代码是这样做的(请参阅注释以了解它)

 Private Sub Worksheet_Change(ByVal Target As Range) ' Check if the edited cell is in column B If Target.Column = 2 Then ' Get the value of the edited cell ColorValue = Target.Value ' Get the row number of the edited cell RowNumber = Target.Row ' Get the number of filled cells in this row CellsCount = Application.WorksheetFunction.CountA(Range(RowNumber & ":" & RowNumber)) ' Apply the color formatting till the last column in this row Range(Cells(RowNumber, 1), Cells(RowNumber, CellsCount)).Interior.ColorIndex = ColorValue End If End Sub