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

use*_*568 2 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
Run Code Online (Sandbox Code Playgroud)

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

Sid*_*out 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
Run Code Online (Sandbox Code Playgroud)

如果必须手动执行此操作,则应执行此操作

在此处输入图片说明

字体也一样。

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

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
Run Code Online (Sandbox Code Playgroud)

如果必须手动执行此操作,则应执行此操作

在此处输入图片说明

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

同样Replace使用参数,如果您不想提供可选参数,请使用清除它们Application.ReplaceFormat.Clear

  • +一种有用的技术。我偶尔会自己使用它,发现如果您多次使用它,则需要使用`Application.FindFormat.Clear`和`Application.ReplaceFormat.Clear`才能使其正常运行(或者每个脚本之后的两个脚本)其他),因为至少对于我来说,格式不只是清除而是保留(您可以在“查找/替换”窗口中检查)。我通常在代码前后使用这些行。 (2认同)