萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 辦公室軟體 >  >> Excel 教學 >> Excel 綜合

Excel VBA 找出兩欄相同值並存入第三欄

以下巨集會比對 A 欄與 B 欄,將重複值標紅並彙總至 C 欄:

Sub MySubSearch()
    Dim i As Long, c As Range
    For i = 2 To Sheet1.Cells(Rows.Count, "B").End(xlUp).Row
        For Each c In Sheet1.Range("A2:A" & Sheet1.Cells(Rows.Count, "A").End(xlUp).Row)
            If Cells(i, 2).Value = c.Value Then
                Cells(i, 2).Font.ColorIndex = 3 ' 標紅
            End If
        Next c
        If Cells(i, 2).Font.ColorIndex = 3 Then
            Cells(Sheet1.Cells(Rows.Count, "C").End(xlUp).Row + 1, 3).Value = Cells(i, 2).Value
        End If
    Next i
    MsgBox "所有重複編號已找出,請查看 C 欄結果!"
End Sub

說明

  • 假設資料從第 2 列開始,第 1 列為標題。
  • 重複值會在 B 欄標紅,並依序寫入 C 欄。
  • 若資料量大,建議改用 Dictionary 或 Collection 提升效能。
copyright © 萬盛學電腦網 all rights reserved