![](/img/trans.png)
[英]Excel VBA check cell color with Activecell.Interior.color not working
[英]Cell Interior Color Index Excel VBA
根据语言表,列A =语言,B =数字,C =彩色单元格
我想知道什么是VBA,所以每当我在B列上键入数字(使用Workbook_SheetChange)时,C的Colorindex就会与键入的数字相等。
另一方面,我确定这是上一个问题的解决方案的一部分,在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
右键单击要使用此功能的工作表名称,然后单击“查看代码”。
现在,您需要编写一个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
尼克·德威特(Nick Dewitt)的代码还可以,但仅使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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.