EXCEL VBA Color 将选中区域 的指定字符,设置字体颜色(比如红)

EXCEL VBA Color 将选中区域 的指定字符,设置字体颜色(比如红)

vba脚本 如下:

bash 复制代码
Sub HighlightTextSimple()
Dim rng As Range
Dim cell As Range
Dim searchText As String
Dim i As Long
Dim startPos As Long
Dim selectedColor As Long
' 检查是否有选中的区域
If TypeName(Selection) <> "Range" Then
MsgBox "请先选择一个单元格区域!", vbExclamation
Exit Sub
End If
Set rng = Selection
' 获取搜索文本
searchText = InputBox("请输入要标红加粗的文本:", "查找文本", "UDP")
If searchText = "" Then Exit Sub
' 使用简单的颜色选择
Dim colorChoice As String
colorChoice = InputBox("选择颜色:" & vbCrLf & _
"R - 红色 " & vbCrLf & _
"G - 绿色 " & vbCrLf & _
"B - 蓝色 " & vbCrLf & _
"Y - 黄色 " & vbCrLf & _
"P - 紫色 " & vbCrLf & _
"O - 橙色 ", "选择颜色", "R")
' 转换为大写
colorChoice = UCase(colorChoice)
' 根据选择设置颜色
Select Case colorChoice
Case "G"
selectedColor = RGB(0, 176, 80) ' 绿色
Case "B"
selectedColor = RGB(0, 112, 192) ' 蓝色
Case "Y"
selectedColor = RGB(255, 255, 0) ' 黄色
Case "P"
selectedColor = RGB(112, 48, 160) ' 紫色
Case "O"
selectedColor = RGB(255, 192, 0) ' 橙色
Case Else
selectedColor = RGB(255, 0, 0) ' 默认红色
End Select
Application.ScreenUpdating = False
Dim count As Long
count = 0
' 遍历选中区域
For Each cell In rng
If VarType(cell.Value) = vbString Then
If cell.Value <> "" Then
startPos = 1
' 查找所有匹配的文本
Do
i = InStr(startPos, cell.Value, searchText, vbTextCompare)
If i > 0 Then
With cell.Characters(Start:=i, Length:=Len(searchText)).Font
.Color = selectedColor
.Bold = True
End With
count = count + 1
startPos = i + Len(searchText)
Else
Exit Do
End If
Loop
End If
End If
Next cell
Application.ScreenUpdating = True
If count > 0 Then
MsgBox "已将 " & count & " 处 '" & searchText & "' 文本设置为选定颜色并加粗!", vbInformation
Else
MsgBox "未找到文本 '" & searchText & "'", vbExclamation
End If
End Sub

2 操作步骤

2.1 EXCEL中选中要设置的区域 ,执行脚本

输入 关键字,这里我们要将Cisco 字符设置为红色

2.2 指定颜色,红色为 R

2.3 执行完成

相关推荐
fengyehongWorld2 小时前
VBA 操作PowerQuery表格和带名字的表格
excel·vba
tangyal3 小时前
Linux 核心操作合集(网络配置、XShell远程连接、vim文本编辑与操作、权限管理 实操手册)
excel
softbangong21 小时前
815-批量Excel文件合并工具,批量excel文件、工作表合并软件
linux·windows·excel·文件合并·excel合并·数据整理
城数派21 小时前
2000-2024年1km精度人口分布栅格数据(全球/全国/分省/分市)
arcgis·信息可视化·数据分析·excel
城数派21 小时前
1984-2024年中国10米分辨率城市土地利用栅格数据(商业、公服、居住等9类)
arcgis·信息可视化·数据分析·excel
城数派1 天前
2015-2024年我国1km分辨率逐日地表温度(LST)栅格数据
数据库·arcgis·信息可视化·数据分析·excel
城数派1 天前
中国全国土壤有机碳密度数据集(2010-2024年)
数据库·arcgis·信息可视化·数据分析·excel
Python大数据分析@1 天前
Pandas相比Excel的优势是哪些?
excel·pandas
fengyehongWorld1 天前
Excel 添加自定义选项卡
excel
斯特凡今天也很帅2 天前
Excel在保留下拉选项的基础上,通过输入四级目录数据,在一级目录、二级目录、三级目录、五级目录的显示
excel