2016-11-30 71 views
0

基于语言表,列A =语言,B =号,C = coloredcell细胞内部显色指数的Excel VBA

我想知道什么是VBA所以每当我在B列输入一个数字(使用Workbook_SheetChange),C被着色,ColorIndex等于输入的数字。另一方面,我肯定是上一个问题的解决方案的一部分,关于VBA,我该如何编写cell.Interior.ColorIndex =(特定的单元格值,如果B2 = 4 - >对于行,整个或直到最后一列有数据,cell.Interior.ColorIndex = 4)并为整行着色。

谢谢

回答

1

表明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 
+0

谢谢。第二部分缺失,但感谢 – andnand

+0

你也可以得到整个行,通常这个网站上的每个帖子都有一个问题和答案;-) –

+0

增加了一点点来将整行设置为相同的'颜色',注意使用'颜色'而不是'colorindex'的'wholeRow' –

0

右键单击您要在此功能表的名称,并单击“查看代码”。

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

Private Sub Worksheet_Change(ByVal Target As Range) 
End Sub 

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

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 
+0

谢谢,效果很好,如何处理直到最后一列有部分行数据 – andnand

0

尼克德威特的代码是好的,但如果你想颜色在整个排它仅彩色列C.

,开始从C取决于列中有多少列:

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