【问题标题】:How to use the Worksheet_Change event for Conditional Formatting?如何将 Worksheet_Change 事件用于条件格式?
【发布时间】:2023-04-01 14:49:01
【问题描述】:

我有一个包含任务列表的工作表,每行一个。 A列是任务名称,B列是必须完成的日期,C列是必须完成的人。 D 列用于指示何时完成。如果此列包含任何内容,则整行的背景颜色应为灰色,否则应为白色。

我认为worksheet_change 事件是处理此问题的最佳方式。我想我可以使用条件格式,但如果单元格被拖拽,这似乎很容易被破坏 - 我需要它尽可能“防弹”!

在伪代码中,我试图实现以下目标:

Private Sub Worksheet_Change(ByVal Target As Range)
    If Target includes a cell in column "D"
        If "D" is not empty
            Set entire row background to grey
        Else
            Set entire row background to white
        End If
    End If
End Sub

任何人都可以给我任何关于实现这一点的最佳方法的建议吗?我是否在正确的路线上,还是有更好的方法?

【问题讨论】:

    标签: excel vba


    【解决方案1】:

    我认为您可以在每个单元格上使用以下条件:

    =INDIRECT("$D" & ROW())>0
    

    我做了一些复制/粘贴并拖动单元格,条件格式没有中断。

    【讨论】:

      【解决方案2】:

      使用条件格式:

      转到Tools->Options->General 并激活R1C1 reference style

      条件:=ISEMPTY(RC4)

      使用 VBA:

      Private Sub Worksheet_Change(ByVal Target As Range)
      Dim found As Range
      Dim cell As Range
      Dim colStart As Integer
      Dim colEnd As Integer
      
          Set found = Intersect(Target, Me.Columns(4))
          colStart = 1
          colEnd = 4
      
          If Not found Is Nothing Then
              For Each cell In found
                  With Me.Range(Me.Cells(cell.Row, colStart), Me.Cells(cell.Row, colEnd)).Interior
                      If IsEmpty(cell) Then
                          .ColorIndex = 15
                      Else
                          .ColorIndex = xlNone
                      End If
                  End With
              Next cell
          End If
      
          Set found = Nothing
      End Sub
      

      我建议使用条件格式

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-08-17
        • 2021-05-26
        • 1970-01-01
        • 2021-06-01
        • 2018-09-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多