ExcelVBA运用Excel的【条件格式】(二)

发布于:2024-07-08 ⋅ 阅读:(54) ⋅ 点赞:(0)
ExcelVBA运用Excel的【条件格式】(二)

前面知识点回顾

1. 访问 FormatConditions 集合

     Range.FormatConditions

2. 添加条件格式

     FormatConditions.Add 方法

语法

表达式。添加 (类型、 运算符、 Expression1、 Expression2)

3. 修改或删除条件格式

4. 清除所有条件格式

一、下面我们可以应用宏录制功能

【问题】查找包含“飞狐外传”的单元格显示的自定义格式

操作试一下

c519beaaf67f2691f65a79a330dd429d.png

得到代码如下

Sub 宏4()
'
' 宏4 宏
'
    Range("A1:F36").Select
    Selection.FormatConditions.Add Type:=xlTextString, String:="飞狐外传", _
        TextOperator:=xlContains
    Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
With Selection.FormatConditions(1).Font
        .Color = -16383844
        .TintAndShade = 0
End With
With Selection.FormatConditions(1).Interior
        .PatternColorIndex = xlAutomatic
        .Color = 13551615
        .TintAndShade = 0
End With
    Selection.FormatConditions(1).StopIfTrue = False
End Sub

二、学习相关知识

可以看到是几个参数:

Type:=***,String:=***,TextOperator:=***

网站查询一下

22b7af5c03c1b3b3bfdbbeb099ed6096.png

三、下面我们自己进行相关的修改及优化

(1)【问题】查找包含“飞狐外传”的单元格显示的自定义格式

效果先看图

1b01e5b71c6acf23d1fafcd7720108b5.png

修改完成代码如下

Sub HighlightCellsContainingText飞狐外传()
    Dim ws As Worksheet
    Dim searchText As String
    Dim lastRow As Long, lastCol As Long
    Dim cell As Range
    ' 设置工作表
    Set ws = ActiveSheet
    ' 设置要搜索的文本
    searchText = "飞狐外传"   ' 修改为你需要搜索的字符
    ' 清除之前的条件格式
    ws.Cells.FormatConditions.Delete
    ' 添加新的条件格式
    With ws.UsedRange.Cells.FormatConditions.Add(Type:=xlTextString, String:=searchText, TextOperator:=xlContains)
        .Interior.Color = RGB(255, 0, 0)                       ' 设置为红色背景
        .StopIfTrue = False
    End With
    MsgBox "所有包含 '" & searchText & "' 的单元格已被高亮显示。", vbInformation
End Sub

继续拓展一下功能

(2)【问题】查找开头为文字‘开头’两个字的单元格显示自定义格式

看效果图

7a3518edf3ea7e3e675cf30bf5ebd248.png

代码如下

Sub HighlightCellsContainingText开头文字()
    Dim ws As Worksheet
    Dim searchText As String
    Dim cell As Range
    ' 设置工作表
    Set ws = ActiveSheet
    ' 设置要搜索的文本
    searchText = "开头"
    ' 清除之前的条件格式
    ws.Cells.FormatConditions.Delete
    ' 添加新的条件格式
    With ws.UsedRange.Cells.FormatConditions.Add(Type:=xlTextString, String:=searchText, TextOperator:=xlBeginsWith)
        .Interior.Color = RGB(10, 255, 0) '设置为xx背景
        .StopIfTrue = False
    End With
    MsgBox "‘开头’为" & searchText & "' 的单元格已被高亮显示。", vbInformation
End Sub

如果你想要其他功能就自己可以拓展

如:

(3)结尾是“***”文字的情况

(4)不包含‘***’文字的情况

---------------

如果你在此学习到东西,请转发给大家免费学习

7faa84e5cd10d05da439bb53ce395c18.jpeg


网站公告

今日签到

点亮在社区的每一天
去签到