Excel VBA如果填充颜色为X的单元格更改为无填充颜色,则将单元格填充颜色返回给X.

我在Excel中有一个包含一堆date的表格。 表的logging链接到一个日历(在另一个表),所以如果你点击表中的date,你将被带到日历中的date单元格。 在我的日历表中,我有下面的VBA,它将以黄色突出显示该表的活动单元格。 请参阅下面的代码:

Private Sub Worksheet_SelectionChange(ByVal Target As Range) Application.ScreenUpdating = False Dim cell As Range 'Turn off ScreenUpdating (speeds up code) Application.ScreenUpdating = False 'Loop through each cell in the ActiveSheet For Each cell In ActiveSheet.UsedRange 'Check for a specific fill color If cell.Interior.Color = RGB(255, 255, 0) Then 'Remove Fill Color cell.Interior.Color = xlNone End If Next cell ' Highlight the active cell Target.Interior.ColorIndex = 6 Application.ScreenUpdating = True End Sub 

它的function就像一个魅力,除了事实上,如果用户激活日历表上的另一个单元格,原来包含填充颜色,它将清除该单元格的原始颜色。 对于没有填充的单元格来说,这是可以的,但是当激活之前填充的单元格并点击时,它会使日历显得糟糕透顶。

我不知道是否我所要求的是甚至可能的,但是我想要做的是以这种方式设置我的代码,以便表格中的任何单元格从填充颜色X(在我的情况中为紫色)到没有填充颜色,那么我希望这个单元格被还原回X的颜色。

我基本上需要在Excel中填充颜色图层。 我应该向微软build议。

我是一个完全的VBA noob,所以请让我知道这是甚至可能的,或者如果我说这个问题的方式糟透了。

请检查这个(我使用2个范围(a2,a3)保存以前的情况,你可以select任何你想要的:

  Option Explicit Private Sub Worksheet_SelectionChange(ByVal Target As Range) Application.ScreenUpdating = False Dim cell As Range Dim i As String Dim i1 As Long On Error Resume Next i = Range("a3").Value i1 = Range("a2").Value 'Turn off ScreenUpdating (speeds up code) Application.ScreenUpdating = False 'Loop through each cell in the ActiveSheet For Each cell In ActiveSheet.UsedRange 'Check for a specific fill color If cell.Interior.Color = RGB(255, 255, 0) Then 'Remove Fill Color cell.Interior.Color = xlNone End If Next cell Range(i).Interior.Color = i1 ' Highlight the active cell ' If Target.Interior.ColorIndex = -4142 Then Range("a3").Value = Target.Address Range("a2").Value = Target.Interior.Color Target.Interior.ColorIndex = 6 ' End If Application.ScreenUpdating = True End Sub 

尝试使用下面的代码。 如果您一次只select一个单元,这将起作用。 您正在使用帮助单元格M1N1来存储以前的单元格区域和内部颜色索引。 由于此代码使用ColorIndex而不是RGB值,因此单元格中的颜色将稍微偏离原始RGB颜色,因此如果可能,请尝试将RGB颜色调整为ColorIndex spectar。

 Private Sub Worksheet_SelectionChange(ByVal Target As Range) Application.ScreenUpdating = False Dim cell As Range 'Turn off ScreenUpdating (speeds up code) Application.ScreenUpdating = False Range(Range("M1")).Interior.ColorIndex = Range("N1").Value Range("M1").Value = Target.Address Range("N1").Value = Range(Target.Address).Interior.ColorIndex ' Highlight the active cell Range("M1").Value = Target.Address Range("N1").Value = Range(Target.Address).Interior.ColorIndex Target.Interior.ColorIndex = 6 Application.ScreenUpdating = True End Sub