比较2列中的两个数据

时间:2013-09-04 09:07:41

标签: vba

我现在正在学习VBA Excel的第一门课程。我是VBA的新人,所以在你的帮助下,我将获得在VBA编程方面做到最好的知识。我需要比较2列。我需要做的是寻找相同的数据并突出显示它,但是发生了什么,只有同一行上的相同数据才是突出显示的数据。忽略不同行中的数据。请帮帮我。

这是我的代码:

Sub Compare()
Dim Col1 As Range
Dim Col2 As Range

    Set Col1 = Application.InputBox("Select First Column to Compare", Type:=8)


    If Col1.Columns.Count > 1 Then

      Do Until Col1.Columns.Count = 1

        MsgBox "You can only select 1 column"
        Set Col1 = Application.InputBox("Select First Column to Compare", Type:=8)

      Loop

    End If


    Set Col2 = Application.InputBox("Select Second Column to Compare", Type:=8)


    If Col2.Columns.Count > 1 Then

      Do Until Col2.Columns.Count = 1

        MsgBox "You can only select 1 column"
        Set Col2 = Application.InputBox("Select Second Column to Compare", Type:=8)

      Loop

    End If


  If Col2.Rows.Count <> Col1.Rows.Count Then

    Do Until Col2.Rows.Count = Col1.Rows.Count

      MsgBox "The second column must be the same size as the first"
      Set Col2 = Application.InputBox("Select Second Column to Compare", Type:=8)

    Loop

  End If


  If Col1.Rows.Count = 65536 Then


    Set Col1 = Range(Col1.Cells(1), Col1.Cells(ActiveSheet.UsedRange.Rows.Count))
    Set Col2 = Range(Col2.Cells(1), Col2.Cells(ActiveSheet.UsedRange.Rows.Count))


  End If



  Dim intCell As Long


  For intCell = 1 To Col1.Rows.Count


    If Col1.Cells(intCell) = Col2.Cells(intCell) Then

      Col1.Cells(intCell).Interior.Color = vbYellow
      Col2.Cells(intCell).Interior.Color = vbYellow

    End If
  Next

End Sub

0 个答案:

没有答案