根据值更改单元格颜色,其中有单个单元格和多个单元格变化

问题描述 投票:0回答:1

我正在为学生创建一个日历样式的时间表。

我们有很多课,所以为了方便安排,我制作了一个星期天开始的日历表,日历中的那些课是通过依赖下拉列表制作的。
例如水平三个级别,第一级“初学者”,第二级“AndroidSmartphone”,第三级“相机”。

因此,我必须根据特定的单个单元格值更改单元格颜色并应用于多个单元格。

也许用户会在工作表中输入多个值,例如一整天; 1, 2, 3, periods, same classes.

用户可能会改变主意并立即删除这些类的值,在这种情况下,可能会删除 3 x 3 个单元格。

以下代码显示错误代码 13.

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim trlRed As Long
    Dim adrBlue As Long
    
    trlRed = RGB(230, 37, 30)
    adrBlue = RGB(126, 199, 216)
    
    If Not Intersect(Target, Range("M31:AM53")) Is Nothing Then
        For Each cell In Target.Cells
            If cell.Value = "Session" And cell.Offset(0, -2).Value = "Trial" Then
                cell.Offset(0, -2).Resize(1, 3).Interior.Color = trlRed 

            ElseIf cell.Value = "AndroidSmartphone" And cell.Offset(0, -1).Value <> "trial" Then
                cell.Offset(0, -1).Resize(1, 3).Interior.Color = adrBlue
            Else
                cell.Resize(1, 3).Interior.ColorIndex = xlColorIndexNone
            End If
        Next cell
    End If
End Sub

我想创建可以根据值、单个单元格、多个单元格以及删除值动态更改单元格颜色的工作表。

excel vba calendar background-color
1个回答
1
投票

您的代码检查

Target
中是否有任何单元格也在M31:AM53中,然后循环遍历Target中的
all
单元格。您应该只遍历感兴趣范围内的
Target
单元格。

如果循环所有

Target
单元格,您可能会尝试访问(例如)
cell.Offset(0, -2)
以获取A 列或B 列中的单元格...

Private Sub Worksheet_Change(ByVal Target As Range)
    
    Dim trlRed As Long, adrBlue As Long, rng As Range, cell As Range
    
    trlRed = RGB(230, 37, 30)
    adrBlue = RGB(126, 199, 216)
    
    Set rng = Application.Intersect(Target, Me.Range("M31:AM53"))
    If Not rng Is Nothing Then 'only loop though any cells in M31:AM53
        For Each cell In rng.Cells
            If cell.Value = "Session" And cell.Offset(0, -2).Value = "Trial" Then
                cell.Offset(0, -2).Resize(1, 3).Interior.Color = trlRed
            ElseIf cell.Value = "AndroidSmartphone" And cell.Offset(0, -1).Value <> "trial" Then
                cell.Offset(0, -1).Resize(1, 3).Interior.Color = adrBlue
            Else
                cell.Resize(1, 3).Interior.ColorIndex = xlColorIndexNone
            End If
        Next cell
    End If
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.