[英]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
必需的輸出:通過將文本與藍色匹配來使綠色的單元格。
我更正了一些發現的錯誤:
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.