基于填充颜色和字体颜色的VBA格式单元格

时间:2019-08-28 04:10:01

标签: excel vba

我必须具备的优势

  1. 如果现有填充颜色为黄色,则删除单元格填充颜色

  2. 仅当现有字体颜色为红色时,才将单元格文本颜色设置回黑色。

我编写了一个宏,该宏只是在每个单元格上循环并检查字体颜色/填充颜色

Application.ScreenUpdating = False
Application.DisplayAlerts = False
Application.EnableEvents = False
...
For Each Cell In ws.UsedRange.Cells
   If Cell.Font.ColorIndex = 3 Then
      Cell.Font.ColorIndex = 0
   End If
   If Cell.Interior.ColorIndex = 6 Then
      Cell.Interior.Pattern = xlNone
      Cell.Interior.TintAndShade = 0
      Cell.Interior.PatternTintAndShade = 0
   End If
Next

它可以按预期工作,但运行速度很慢,可能是因为它穿过每个单元格。是否有使这项工作更快的方法?我尝试在VBA中使用条件格式,但是它似乎无法检查单元格颜色/单元格字体颜色...

1 个答案:

答案 0 :(得分:8)

无需循环。您可以使用颜色进行搜索和替换。试试这个

如果现有填充颜色为黄色,则删除单元格填充颜色

With Application.FindFormat.Interior
    .PatternColorIndex = xlAutomatic
    .Color = 65535
    .TintAndShade = 0
    .PatternTintAndShade = 0
End With
With Application.ReplaceFormat.Interior
    .Pattern = xlNone
    .TintAndShade = 0
    .PatternTintAndShade = 0
End With
Cells.Replace What:="", Replacement:="", LookAt:=xlPart, SearchOrder:= _
xlByRows, MatchCase:=False, SearchFormat:=True, ReplaceFormat:=True

如果您必须手动执行此操作,则应该已完成

enter image description here

类似字体。

仅当现有字体颜色为红色时,才将单元格文本颜色设置为黑色。

With Application.FindFormat.Font
    .Subscript = False
    .Color = 255
    .TintAndShade = 0
End With
With Application.ReplaceFormat.Font
    .Subscript = False
    .ColorIndex = xlAutomatic
    .TintAndShade = 0
End With
Cells.Replace What:="", Replacement:="", LookAt:=xlPart, SearchOrder:= _
xlByRows, MatchCase:=False, SearchFormat:=True, ReplaceFormat:=True

如果您必须手动执行此操作,则应该已完成

enter image description here

注意:VBA Find使用参数。除What:=外,其余参数都是可选的。建议您提供这些参数。否则,Find将使用现有设置。如果您不想提供可选参数,则必须在使用Find之前清除这些参数,否则会得到不希望的结果。您可以通过Application.FindFormat.Clear

类似地,Replace使用参数,如果您不想提供可选参数,请使用Application.ReplaceFormat.Clear

清除它们。
相关问题