簡體   English   中英

使用VBA基於文本匹配突出顯示行和列的相交單元格

[英]Highlight intersection cell of row and column based on Text matching using VBA

我正在嘗試使用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

必需的輸出:通過將文本與藍色匹配來使綠色的單元格。

產量

因此,根據我的評論使用條件格式:

在此處輸入圖片說明

  • 選擇范圍B4:D6
  • 開始>條件格式>新規則>公式:

     =B$2=$A4 
  • 選擇您的填充顏色並確認

請注意,通過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(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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM