我有一列中有 600 个连续单元格。我想读取这个范围内每个单元格的颜色。
我可以使用
range.value
轻松地将范围内单元格的值读取到数组中,它可以一次读取全部内容,或者至少我不必迭代整个 600 个单元格,这将导致 excel 和VBA,从而使其效率低下且耗时。
但我无法有效读取细胞的颜色。我必须循环遍历整个 600 个单元格并使用 range.Interior.Color
,这使得该过程非常慢。
我发现一个问题问同样的问题,我发现无法像值一样一次性检索所有颜色,但我想知道如何有效或正确地检索它们,因为循环超过 600 个或更多单元格需要时间,我可以已经看到我的工作表滞后了。
如果要查找给定范围内具有特定颜色的单元格,可以使用带有格式模式的
Find
方法。这是代码的方案:rng
是您要查看的范围,单元格D1
是颜色模式。结果是一个 found
范围,其中包括所有找到的给定颜色的单元格。如果 What
方法的 Find
参数设置为空文本,则将找到指定颜色的所有单元格,无论其内容如何。
Sub FindFormattedCells()
Dim rng As Range, adr As String
Dim found As Range, newf As Range
Application.FindFormat.Clear
With Application.FindFormat.Interior
.Color = Range("D1").Interior.Color ' color pattern
End With
Set rng = Range("A1:A20") ' where to find
Set found = rng.Find(What:="", SearchFormat:=True)
If found Is Nothing Then Exit Sub
adr = found.Address
Set newf = found
Do
Set newf = rng.Find(What:="", After:=newf, SearchFormat:=True)
Set found = Union(found, newf)
Loop Until newf.Address = adr
Debug.Print found.Address
Application.FindFormat.Clear
End Sub