前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >突出显示单元格文本中含有词库的内容

突出显示单元格文本中含有词库的内容

作者头像
fanjy
发布2024-01-23 13:14:45
1080
发布2024-01-23 13:14:45
举报
文章被收录于专栏:完美Excel

excelperfect

标签:VBA

下面的代码将突出显示在单元格文本字符串中用户定义的文本字符串,对其设置颜色并加粗。

VBA代码如下:

代码语言:javascript
复制
'使用颜色和加粗来突出显示词库中的文字
Sub ColorandBold()
 Dim myCell As Range
 Dim myRng As Range
 Dim FirstAddress As String
 Dim iCtr As Long
 Dim letCtr As Long
 Dim startrow As Long    '开始的单元格区域位置
 Dim endrow As Long    ' 结束的单元格区域位置
 Dim startcolumn As Integer    '开始列
 Dim endcolumn As Integer    '结束列
 Dim myWords
 
 '设置要应用突出显示词库文字的单元格区域
 '你可以根据你的需要来修改
 startrow = 2
 endrow = 5
 startcolumn = 1
 endcolumn = 2
 Set myRng = Range(Cells(startrow, startcolumn), Cells(endrow, endcolumn))
 
 '设置词库
 '即想要添加颜色和加粗的词语
 myWords = Array("完美Excel", "excelperfect", "Excel")
 
 '开始主循环---------------------------------------
 For iCtr = LBound(myWords) To UBound(myWords)
   '忽略错误
   On Error Resume Next
   With myRng
     Set myCell = .Find(What:=myWords(iCtr), After:=.Cells(1), _
        LookIn:=xlValues, LookAt:=xlPart, _
        SearchOrder:=xlByRows, _
        SearchDirection:=xlNext, _
        MatchCase:=False)
     '检查
     If Not myCell Is Nothing Then
       FirstAddress = myCell.Address
 
       Do
         For letCtr = 1 To Len(myCell.Value)
           If StrComp(Mid(myCell.Value, letCtr, _
               Len(myWords(iCtr))), _
               myWords(iCtr), vbTextCompare) = 0 Then
             myCell.Characters(Start:=letCtr, _
               Length:=Len(myWords(iCtr))) _
               .Font.ColorIndex = 5
           End If
         Next letCtr
         For letCtr = 1 To Len(myCell.Value)
           If StrComp(Mid(myCell.Value, letCtr, _
               Len(myWords(iCtr))), _
               myWords(iCtr), vbTextCompare) = 0 Then
              myCell.Characters(Start:=letCtr, _
                Length:=Len(myWords(iCtr))) _
                .Font.FontStyle = "Bold"
           End If
         Next letCtr
 
         '获取相一个地址
         Set myCell = .FindNext(myCell)
       Loop While Not myCell Is Nothing _
         And myCell.Address <> FirstAddress
     End If
   End With
 Next iCtr
End Sub

你只需对代码中设置要搜索的单元格区域的值修改为适合你工作表中的区域,定义自己的文本字符串即词库。在代码注释中我已标注出,有兴趣的朋友可以研究。

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2024-01-22,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 完美Excel 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档