用excel VBA 在工作表2中,檢查H-V欄的每個單元格是否包含B欄中的任何內容,如果包含,則將該單元格的文字和對應B欄的文字顏色設為紅色
- User
用excel VBA 在工作表2中,檢查H-V欄的每個單元格是否包含B欄中的任何內容,如果包含,則將該單元格的文字和對應B欄的文字顏色設為紅色
Assistant
以下是實現您需求的 Excel VBA 程式碼:
Sub 檢查並標記重複內容() Dim ws1 As Worksheet, ws2 As Worksheet Dim lastRowB As Long, lastRowH As Long Dim i As Long, j As Long ' 設定工作表 Set ws1 = ThisWorkbook.Worksheets(1) ' B欄所在的工作表 Set ws2 = ThisWorkbook.Worksheets(2) ' H-V欄所在的工作表 ' 找出B欄的最後一行 lastRowB = ws1.Cells(ws1.Rows.Count, "B").End(xlUp).Row ' 找出H-V欄的最後一行 lastRowH = ws2.Cells(ws2.Rows.Count, "H").End(xlUp).Row ' 遍歷H-V欄的每個單元格 For j = 8 To 22 ' H到V欄(假設H是第8欄,V是第22欄) For i = 1 To lastRowH ' 檢查當前單元格是否包含B欄的任何內容 If WorksheetFunction.CountIf(ws1.Range("B1:B" & lastRowB), ws2.Cells(i, j).Value) > 0 Then ' 將單元格文字顏色設為紅色 ws2.Cells(i, j).Font.Color = vbRed ' 找出對應的B欄單元格並將其文字顏色設為紅色 Dim k As Long For k = 1 To lastRowB If ws1.Cells(k, 2).Value = ws2.Cells(i, j).Value Then ws1.Cells(k, 2).Font.Color = vbRed Exit For End If Next k End If Next i Next j MsgBox "檢查完成!", vbInformation End Sub
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.