用鼠标点击改变细胞的颜色

时间:2012-01-09 20:44:55

标签: excel

Excel 2003,我想只需点击鼠标即可更改单元格的颜色。我已经这样做了,我的问题是如何在单元格上再次点击鼠标才能恢复原始颜色。我希望能够将单元格的颜色从白色更改为绿色,然后在每次单击鼠标时再将其返回。

1 个答案:

答案 0 :(得分:3)

这是我在其中一张纸上使用的内容。用户基本上双击一个单元格以显示用户表单;当它们提交校正时,它会突出显示细胞黄色。如果他们犯了错误,那么他们双击以删除突出显示。您应该能够根据需要提取下面代码的中间部分。

Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)

 Application.EnableEvents = False

    Dim TargRow As Variant
    Dim TargCol As Variant

    TargRow = Target.Row
    TargCol = Target.Column

    Header = 8
    FirstCol = 0
    LastCol = 13
    CommentCol = 13

    If TargRow > Header And TargCol > FirstCol And TargCol < LastCol Then
        'If the cell is clear
        If Target.Interior.ColorIndex = xlNone Then
            Cancel = True

            'Then change the background to yellow
            Target.Interior.ColorIndex = 6
            Corrections.Show

            'Else if the cell background color is already yellow
            ElseIf Target.Interior.ColorIndex = 6 Then

            'Then clear the background
            Target.Interior.ColorIndex = xlNone
        End If
    End If

    'This is to prevent the cell from being edited when double-clicked
    Cancel = True

    Application.EnableEvents = True
End Sub

以下评论中的编辑代码:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

    'If the target cell is clear
    If Target.Interior.ColorIndex = xlNone Then

        'Then change the background to the specified color
        Target.Interior.ColorIndex = 4

        'But if the target cell is already the specified color
        ElseIf Target.Interior.ColorIndex = 4 Then

        'Then clear the background color
        Target.Interior.ColorIndex = xlNone

    End If

End Sub