excel - 为细胞着色的另一种更快的方法

标签 excel vba performance conditional-formatting

我的这部分宏是用来给 B 行中的单元格着色,这取决于它们的值和 Q 行中相应单元格的值。效果很好,但是当文件很大时(有时超过 500,000 行),这一步真的可以减慢宏的整个执行速度。还有可能我需要在路上添加更多颜色,这将意味着更多的 IF 语句行,这将进一步减慢速度。

Dim LastRow As Long
LastRow = Cells(Rows.Count, 2).End(xlUp).Row 
Dim i As Long, r1 As Range, r2 As Range
For i = 11 To LastRow
  Set r1 = Range("B" & i)
  Set r2 = Range("Q" & i)
If r2 = "001111" Then r1.Interior.Color = vbGreen
If (r1 < 4 Or r1 > 0) And (r2 <> "001111") Then r1.Interior.Color = vbYellow
If (r1 > 3 Or r1 < 1) And (r2 <> "001111") Then r1.Interior.Color = vbRed
Next i

我尝试使用一些代码对整行进行条件格式设置。这要快得多,但我无法弄清楚如何将 Q 列中单元格的值作为条件包含在内。我也被限制在不超过三个条件。
有没有办法以比我当前的代码更快的方式完成这项任务,并且将来还允许更多的条件/颜色?

最佳答案

划掉我之前的尝试。我同意 Range.AutoFilter甚至可能会更好:

Sub Test()

Dim lr As Long, rng As Range

With Sheet1

    'Get last used row of data and set range
    lr = .Cells(.Rows.Count, 2).End(xlUp).Row
    Set rng = .Range("B10:Q" & lr)

    'Apply first filter and color Green
    rng.AutoFilter 16, "001111"
    If rng.Columns(1).SpecialCells(12).Count > 1 Then rng.Columns(1).Offset(1).Resize(lr - 10).Interior.Color = vbGreen

    'Apply second filter and color Yellow
    rng.AutoFilter 16, "<>*001111*"
    rng.AutoFilter 1, "<4", xlAnd, ">0"
    If rng.Columns(1).SpecialCells(12).Count > 1 Then rng.Columns(1).Offset(1).Resize(lr - 10).Interior.Color = vbYellow

    'Apply third filter and color Red
    rng.AutoFilter 1, ">3", xlOr, "<1"
    If rng.Columns(1).SpecialCells(12).Count > 1 Then rng.Columns(1).Offset(1).Resize(lr - 10).Interior.Color = vbRed

    'Remove AutoFilter
    rng.AutoFilter

End With

End Sub

关于excel - 为细胞着色的另一种更快的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60077746/

相关文章:

excel - VBA 单元格值问题以及是否

Java 泛型 : Type Inference Performance

android - 默认情况下在 "allow"中设置 "Asus auto start manager"权限

performance - Perl6 : What is the best way for dealing with very big files?

vba - 爬行 ActiveX 按钮

excel - Excel 中具有多个条件的 SumIf 公式

java - 如何获取工作表

excel - 无法自动调整单元格的行高

sorting - 对excel中的多列独立排序

excel - VBA宏跳转到另一个?