【问题标题】:Highlight intersection cell of row and column based on Text matching using VBA基于使用VBA的文本匹配突出显示行和列的交叉单元格
【发布时间】:2020-01-19 13:09:17
【问题描述】:

我正在尝试使用 VBA,当列标题中的文本与行中的文本相同时,行和列的交叉单元格会以某种颜色突出显示。

示例:我尝试使用以下代码,但没有给出所需的输出

Sub cellintersection()
Application.EnableEvents = False
    Application.ScreenUpdating = False

    Dim ws As Worksheet
    Set ws = ActiveSheet

    Dim cols As Range, rws As Range
    Dim lastRow As Integer: lastRow = ws.UsedRange.Rows.Count
    Dim lastColumn As Integer: lastColumn = ws.UsedRange.Columns.Count

    For Each cols In ws.Range(ws.Cells(1, 1), ws.Cells(1, lastColumn))
        If (Not (cols.Value = vbNullString)) Then
            For Each rws In ws.Range("A1:A" & lastRow)
                If (rws.Value = cols.Value) Then ws.Cells(rws.Row, cols.Column).Interior.Color = 5296210
            Next
        End If
    Next

    Application.EnableEvents = True
    Application.ScreenUpdating = True

End Sub

必需的输出:通过将文本与蓝色匹配来将单元格显示为绿色。

【问题讨论】:

  • 所以不适合使用条件格式?
  • 我不太擅长Excel公式,请教我如何使用公式?

标签: excel vba conditional-formatting


【解决方案1】:

所以根据我的评论使用条件格式:

  • 选择范围B4:D6
  • 开始>条件格式>新规则>公式:

    =B$2=$A4
    
  • 选择您的填充颜色并确认

请注意,通过 VBA 填充单元格是静态的,而条件格式是动态的,并且会根据对数据所做的更改而变化。

【讨论】:

  • 太棒了!它工作得很好,不是这样想的。谢谢。
  • 一个小问题,当我将单元格 A4 中的文本从 A11 更改为 A22 时使用条件格式,单元格 C4 没有突出显示。
  • @Sant,它对我来说完美无缺。你确定你使用了正确的公式吗?
【解决方案2】:

我修复了一些我发现的错误:

Sub cellintersection()
Application.EnableEvents = False
Application.ScreenUpdating = False

Dim ws As Worksheet
Set ws = ActiveSheet

Dim cols As Range, rws As Range
Dim lastRow As Integer: lastRow = ws.UsedRange.Rows.Count
Dim lastColumn As Integer: lastColumn = ws.UsedRange.Columns.Count

For Each cols In ws.Range(ws.Cells(2, 1), ws.Cells(2, lastColumn))
    If cols.Value <> vbNullString Then
        For Each rws In ws.Range("A1:A" & lastRow)
            If rws.Value = cols.Value Then ws.Cells(rws.Row, cols.Column).Interior.Color = 5296210
        Next
    End If
Next

Application.EnableEvents = True
Application.ScreenUpdating = True

End Sub

当开始第一个 For...Each 循环时,您正在查看第 1 行,其中没有任何值。您的标题在第 2 行。此外,您的一些 If 语句也非常复杂,例如

If (Not (cols.Value = vbNullString)) Then

相同
If cols.Value <> vbNullString Then

【讨论】:

    猜你喜欢
    • 2015-01-26
    • 2020-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-27
    • 1970-01-01
    • 2020-05-15
    相关资源
    最近更新 更多