【问题标题】:Highlight cells that meet criteria突出显示符合条件的单元格
【发布时间】:2017-12-28 20:31:03
【问题描述】:

我刚开始使用 VBA,需要一些指导。 目标:在这 4 个条件下突出显示单元格。必须满足所有条件

  1. 同一天
  2. 同名
  3. 差异地址
  4. 重叠时间

    示例:

    data 1> start time: 09:00 end time: 09:35

    data 2> start time: 09:20 end time: 10:00

    `当第二个数据的开始时间与第二个数据的结束时间重叠时 第一个数据,应该突出显示

样本数据:

样本输出:

我已经做了什么:

 Sub HighlightCells()
    Dim cel As Variant
    Dim rng As Range
    Dim clr As Long

    Application.ScreenUpdating = False
    Application.Calculation = xlCalculationManual

    Set rng = Range("A1:A" & Range("A1048576").End(xlUp).Row)
    rng.Interior.ColorIndex = xlNone
    clr = 3

    For Each cel In rng
       If Application.WorksheetFunction.CountIf(rng, cel) > 1 Then
         If WorksheetFunction.CountIf(Range("A1:A" & cel.Row), cel) = 1 Then
           cel.Interior.ColorIndex = clr
           clr = clr + 1
         Else
           cel.Interior.ColorIndex = rng.Cells(WorksheetFunction.Match(cel.Value, rng, False), 1).Interior.ColorIndex
         End If
       End If
    Next

    Application.ScreenUpdating = True
    Application.Calculation = xlCalculationAutomatic
 End Sub

它只突出显示第一列中的重复项

【问题讨论】:

  • 为什么不使用条件格式?
  • 我的项目需要我在 VBA 中完成,也因为我希望它是自动化的:)
  • 和条件格式不允许我看到我猜的重叠时间

标签: vba excel


【解决方案1】:

如果您只需要包含所有 5 列,那么这应该可以工作...

 Sub HighlightCells()
    Dim cel As Range 'I think you want range for better functionality.
    Dim rng As Range
    Dim clr As Long
    Dim AdditionalColumnsToHighlight As Integer

    AdditionalColumnsToHighlight = 4 ' means 5 columns total

    Application.ScreenUpdating = False
    Application.Calculation = xlCalculationManual

    Set rng = Range("A1:A" & Range("A1048576").End(xlUp).Row)
    rng.Interior.ColorIndex = xlNone
    clr = 3

    For Each cel In rng
       If Application.WorksheetFunction.CountIf(rng, cel) > 1 Then
         If WorksheetFunction.CountIf(Range("A1:A" & cel.Row), cel) = 1 Then
           Range(cel, cel.Offset(0, AdditionalColumnsToHighlight)).Interior.ColorIndex = clr 'this allows you to make the range as many columns over as specified above.
           clr = clr + 1
         Else
           Range(cel, cel.Offset(0, AdditionalColumnsToHighlight)).Interior.ColorIndex = rng.Cells(WorksheetFunction.Match(cel.Value, rng, False), 1).Interior.ColorIndex
         End If
       End If
    Next

    Application.ScreenUpdating = True
    Application.Calculation = xlCalculationAutomatic
 End Sub

【讨论】:

  • 非常感谢您提供的代码。它可以工作,但存在一个问题,如果它是相同的日期和重叠的时间,它会突出显示该行,但不检查名称是否相同并且地址是否不同。你知道我应该如何编码吗?谢谢!
  • 既然我已经回答了您的问题,“它只突出显示第一列中的重复项”也许您可能想接受答案并发布一个清楚说明您的问题的新问题?在您的整个项目正确完成之前,让人们回答更多问题有点不礼貌。在您接受此答案后,我很乐意查看您发布的新问题。祝你好运。
猜你喜欢
  • 1970-01-01
  • 2018-05-02
  • 1970-01-01
  • 1970-01-01
  • 2019-01-21
  • 2021-12-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多