通过双击着色单元格

我注意到规则说不要在别人的问题上要求澄清,所以希望这是做到这一点的正确方法。 我最初find足够的答案让我在哪里我在Excel中单击鼠标单击更改单元格的颜色 。 谢谢user3159079和tigeravatar。

我有这个:

Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean) Cancel = True Worksheet_SelectionChange Target 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 change the background to the specified color Target.Interior.ColorIndex = 6 'But if the target cell is already the specified color ElseIf Target.Interior.ColorIndex = 6 Then 'Then change the background to the specified color Target.Interior.ColorIndex = 3 'But if the target cell is already the specified color ElseIf Target.Interior.ColorIndex = 3 Then 'Then clear the background color Target.Interior.ColorIndex = xlNone End If End Sub 

但我有3个问题。

1)我想指定一个范围,这种工作,而不影响其他单元格(即我希望它的工作…

 $F$4:$F$6 $D$10:$I$12 $F$17:$I$34 $N$5:$O$6 $N$10:$O$11 $O$15:$P$18 $O$24:$P$24 $O$29:$P$29 $O$34:$P$34 $U$6:$X$7 $U$10:$X$14 $AA$6:$AG$8 $F$38:$F$43 $N$38:$N$44 $E$48:$E$51 $Q$48:$R$51 $X$23:$AG$35 

…和其他地方。

2)我想这只工作在双击而不是第一次单击单元格更改

3)这个工作,直到我保存,closures并重新打开电子表格。 重新打开工作表后,点击function的颜色消失。

我对这一点都不是很了解,但是我能够很好地search,这是我得到这个目标的方法,但是我不能进一步弄明白,所以不胜感激。

我修改了下面的代码,满足1)和2)的要求。

对于要求3):将电子表格保存为.xlsm格式,并且一旦再次打开,允许运行macros。

让我知道事情的后续:

 Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean) Dim MyRange As Range '(1) Desired Range where it works: Set MyRange = Range("$F$4:$F$6,$D$10:$I$12,$F$17:$I$34,$N$5:$O$6," & _ "$N$10:$O$11,$O$15:$P$18,$O$24:$P$24,$O$29:$P$29," & _ "$O$34:$P$34,$U$6:$X$7,$U$10:$X$14,$AA$6:$AG$8," & _ "$F$38:$F$43,$N$38:$N$44,$E$48:$E$51,$Q$48:$R$51," & _ "$X$23:$AG$35") Cancel = True '(1) Check if double clicked cell is one where the code should work: If Not Intersect(Target, MyRange) Is Nothing Then Custom_ColourChange Target End If End Sub '(2) Changed from default Worksheet_Selection event to Custom Sub: Private Sub Custom_ColourChange(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 change the background to the specified color Target.Interior.ColorIndex = 6 'But if the target cell is already the specified color ElseIf Target.Interior.ColorIndex = 6 Then 'Then change the background to the specified color Target.Interior.ColorIndex = 3 'But if the target cell is already the specified color ElseIf Target.Interior.ColorIndex = 3 Then 'Then clear the background color Target.Interior.ColorIndex = xlNone End If End Sub 

编辑:

以下编辑@ BK201和@simoco评论