【问题标题】:Conditionally Format Specific words within cells of worksheet有条件地格式化工作表单元格中的特定单词
【发布时间】:2021-08-10 08:58:07
【问题描述】:

我的数据使得单个单元格包含多个信息。

使用条件格式 excel 可以识别包含短语的单元格,但是条件格式将应用于整个单元格。我的目标是尝试用红色突出显示特定文本“未提供”。

在网上看起来这将是一个 VBA 解决方案。

首先,我在网上找到了以下代码,但这似乎并没有根据需要改变颜色。

Sub Test1()
  Dim strString$, x&
  Dim rngCell As Range
  
  strString = Range("B1").Value
  Application.ScreenUpdating = False
  For Each rngCell In Range("G1", Range("G" & Rows.Count).End(xlUp))
    With rngCell
      .Font.ColorIndex = 1
      For x = 1 To Len(.Text) - Len(strString) Step 1
        If Mid(.Text, x, Len(strString)) = strString Then .Characters(x, Len(strString)).Font.ColorIndex = 5
      Next x
    End With
  Next rngCell
  Application.ScreenUpdating = True
End Sub

如果有人可以指出我如何让​​上面的代码工作以探索这是否对我的目的有用,或者即使有人知道如何有条件地格式化特定的单词,那会很棒。最终,我希望以这种方式突出显示工作表中的每个“未提供”实例。

【问题讨论】:

  • Next rngCellq 的末尾去掉q。你使用For Each rngCell In R....,所以你必须使用Next rngCell(或者只是Next,但最好有变量)。
  • 请在模块顶部插入Option Explicit,这将有助于强制您明确声明所有变量。您将收到编译错误,指出在您插入该行并尝试编译时未定义 rngCellq

标签: excel vba conditional-formatting


【解决方案1】:

您可以使用InStr() 来查找子字符串而不是 For 循环

Sub Test1()
    Dim strString As String, x As Long, rngCell As Range
  
    strString = Range("B1").Value
    Application.ScreenUpdating = False
    For Each rngCell In Range("G1", Range("G" & Rows.Count).End(xlUp))
        x = InStr(1, rngCell.Value2, strString, vbTextCompare)
        If x > 0 Then
            With rngCell
              .Font.ColorIndex = 1
              .Characters(x, Len(strString)).Font.ColorIndex = 3    'red color
            End With
        End If
    Next
    Application.ScreenUpdating = True
End Sub

要动态更改文本的颜色,如条件格式,可以使用Change 事件:

'place it into the Worksheet module
Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim strString As String, x As Long, rngCell As Range, rng As Range
    
    Set rng = Intersect(Target, Me.Columns("G"))
    If rng Is Nothing Then Exit Sub
        
    Application.EnableEvents = False
    Application.ScreenUpdating = False
    
    strString = Range("B1").Value
    
    For Each rngCell In rng
        x = InStr(1, rngCell.Value2, strString, vbTextCompare)
        If x > 0 Then
            With rngCell
              .Font.ColorIndex = 1
              .Characters(x, Len(strString)).Font.ColorIndex = 3    'red color
            End With
        End If
    Next
    Application.ScreenUpdating = True
    Application.EnableEvents = True
End Sub

【讨论】:

    猜你喜欢
    • 2020-09-09
    • 2023-03-15
    • 1970-01-01
    • 2015-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-03
    • 2020-12-02
    相关资源
    最近更新 更多