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

|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| ExcelVBA运用Excel的【条件格式】(二) |
| 前面知识点回顾 1. 访问 FormatConditions 集合 Range.FormatConditions 2. 添加条件格式 FormatConditions.Add 方法 语法 表达式。添加 (类型、 运算符、 Expression1、 Expression2) 3. 修改或删除条件格式 4. 清除所有条件格式 |

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

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

操作试一下

得到代码如下

sql 复制代码
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:=***

网站查询一下

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

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

效果先看图

修改完成代码如下

php 复制代码
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)【问题】查找开头为文字'开头'两个字的单元格显示自定义格式

看效果图

代码如下

properties 复制代码
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)不包含'***'文字的情况


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

相关推荐
siwangqishiq213 分钟前
Vulkan Tutorial 教程翻译(四) 绘制三角形 2.2 呈现
前端
李三岁_foucsli15 分钟前
js中消息队列和事件循环到底是怎么个事,宏任务和微任务还存在吗?
前端·chrome
尽欢i15 分钟前
HTML5 拖放 API
前端·html
PasserbyX31 分钟前
一句话解释JS链式调用
前端·javascript
1024小神32 分钟前
tauri项目,如何在rust端读取电脑环境变量
前端·javascript
Nano37 分钟前
前端适配方案深度解析:从响应式到自适应设计
前端
古夕42 分钟前
如何将异步操作封装为Promise
前端·javascript
小小小小宇42 分钟前
前端定高和不定高虚拟列表
前端
呆萌的代Ma1 小时前
Cursor实现用excel数据填充word模版的方法
word·excel
Tender_光1 小时前
iptables实验
运维·服务器