首页 文章

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

提问于
浏览
1

我在Excel中有一个包含大量日期的表 . 表格的记录链接到日历(在另一张表格上),这样,如果您点击表格中的日期,您将被带到日历中该日期的单元格 . 在我的日历表上,我有以下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

它的作用就像一个魅力,除了这样一个事实:如果用户激活日历表上的另一个单元格,最初包含填充颜色,它将清除该单元格的原始颜色 . 这对于没有填充开始的单元格是可以的,但是当激活先前填充的单元格并单击它时,它会使日历看起来很糟糕 .

我不确定我要求的是否可能,但我想做的是以这样的方式设置我的代码,以便工作表上的任何单元格从填充颜色X(紫色,在我的情况下)到没有填充颜色,然后我想要将该单元格还原为颜色X.

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

我是一个完整的VBA菜鸟,所以请告诉我,如果这是可能的,或者我说这个问题的方式很糟糕 .

2 回答

  • 0

    请检查这个(我使用2个范围(a2,a3)来保存以前你可以选择的情况:

    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
    
  • 0

    尝试使用下面的代码 . 这将适用于您一次只选择一个单元格的情况 . 您正在使用帮助单元格 M1N1 来存储以前的单元格范围和内部颜色索引 . 由于此代码使用的是 ColorIndexRGB 值,因此单元格中的颜色将略微偏离原始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
    

相关问题