【问题标题】:Excel - Highlight selected/active cell keeping old colorExcel - 突出显示选定/活动单元格保持旧颜色
【发布时间】:2022-01-30 00:37:32
【问题描述】:

这里 (How do I set the background color of Excel cells using VBA?) 有一些关于在 excel 中突出显示活动/选定单元格的信息,但我无法恢复在选择之前设置的单元格的旧背景颜色。有没有人建议如何解决这个问题?谢谢!!!

【问题讨论】:

  • 在更新颜色之前,将旧颜色和单元格引用存储在全局变量中,然后在选择另一个单元格时将其更改回来。有意义吗?
  • 是的,逻辑是有道理的,但由于我是 VBA 新手,我会很感激任何一段代码。
  • 在我给你代码之前你能告诉我你所做的尝试吗?这就是 Stackoverflow 的全部意义所在。
  • 当然,这就是我的作品: Private Sub Workbook_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Range) 'ActiveSheet.Unprotect "Password" 'Sh.UsedRange.Interior.ColorIndex = 27 'change colorindex to select background color 'MsgBox ("Background color: " & Target.Interior.ColorIndex) Target.Interior.ColorIndex = 32 '改变colorindex选择活动单元格颜色End Sub

标签: excel


【解决方案1】:

所以,如果有人想使用它,这是我的解决方案:

在一个模块中放入以下代码:

Option Explicit

Public oldCellAddr As String
Public oldCellBackgroundColor As Long

Public Function InitializeGlobalVariables() As Boolean

    Set oldCellAddr = ""
    Set oldCellBackgroundColor = 0
    
End Function

在工作簿表中输入以下代码:

Option Explicit

Private Sub Workbook_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Range)

    Dim thisCellAddr As String

    thisCellAddr = ActiveCell.Address
    
    If (oldCellAddr <> "" And thisCellAddr <> oldCellAddr) Then
        Range(oldCellAddr).Interior.ColorIndex = oldCellBackgroundColor
    End If
    
    oldCellBackgroundColor = Target.Interior.ColorIndex
    oldCellAddr = thisCellAddr
    
    Target.Interior.ColorIndex = 24

End Sub

完成。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-12
    • 2021-05-25
    • 1970-01-01
    • 2014-02-21
    • 1970-01-01
    • 2022-01-10
    • 1970-01-01
    相关资源
    最近更新 更多