如何使用Excel VBA将包含指定文本的单元格填充为黄色
Excel VBA 匹配指定文本填充单元格背景实现方案
下面提供两种常用实现方式,可根据你的数据量选择:
方式1:遍历单元格实现(适合数据量较小的场景)
Sub HighlightNoGameCells() Dim targetRange As Range, cell As Range ' 定义需要处理的范围:B列、F列的已使用单元格 Set targetRange = Union(ActiveSheet.Range("B:B"), ActiveSheet.Range("F:F")).SpecialCells(xlCellTypeConstants) For Each cell In targetRange ' 完全匹配文本"No Game" If cell.Value = "No Game" Then ' 填充黄色背景 cell.Interior.ColorIndex = 6 End If Next cell End Sub
相关说明:
- 需要固定作用于某张工作表的话,把
ActiveSheet替换为Sheets("你的工作表名称")即可 - 如果需要模糊匹配(只要单元格内容包含"No Game"就算匹配),把判断条件替换为
If InStr(1, cell.Value, "No Game", vbTextCompare) > 0 - 要调整背景色可以修改
ColorIndex值,或者用RGB写法:cell.Interior.Color = RGB(255, 255, 0)
方式2:Find方法实现(适合数据量较大的场景,效率更高)
Sub HighlightNoGameFast() Dim targetRange As Range, foundCell As Range, firstFound As String Set targetRange = Union(ActiveSheet.Range("B:B"), ActiveSheet.Range("F:F")) Set foundCell = targetRange.Find(What:="No Game", LookIn:=xlValues, LookAt:=xlWhole) If Not foundCell Is Nothing Then firstFound = foundCell.Address Do foundCell.Interior.ColorIndex = 6 Set foundCell = targetRange.FindNext(foundCell) Loop While Not foundCell Is Nothing And foundCell.Address <> firstFound End If End Sub
相关说明:
- 该方法只会遍历实际存在匹配内容的单元格,不会遍历空单元格,数据量超过1000行时优先选这个方案
- 要开启模糊匹配把参数
LookAt:=xlWhole改为LookAt:=xlPart即可
内容的提问来源于stack exchange,提问作者Pierre Auger
相关产品推荐
相关产品推荐

