excel 查找一個表的數據在另一個表中是否存在

Sub test()

Rem    MsgBox ("AAAAA")

Dim pos, pos1, tmp, total1, total2, tmpStr, tmpStr1, col, sheetR

sheetR = 2

Rem 獲取Sheet1的行數
total1 = Sheet1.UsedRange.Rows.Count
Rem 獲取Sheet1的列數,後面把不滿足的條目複製到Sheet3中
col = Sheet1.UsedRange.Columns.Count
Rem 獲取Sheet2的行數
total2 = Sheet2.UsedRange.Rows.Count

MsgBox "sheet1 行: " & total1 & "  sheet2 行:" & total2 & "    " & col
 

Rem 開始循環,第一個循環是遍歷Sheet1中第六列的所有行數據,從2到total1
  For pos = 2 To Sheet1.UsedRange.Rows.Count

    tmpStr = Sheet1.Cells(pos, 6)
    Sheet1.Cells(pos, 6).Interior.ColorIndex = 2
    Rem MsgBox "***********sheet1*********** Row :" & pos & " data :" & tmpStr

    Rem 在Sheet2的指定列(這裏第4列)的所有行數據中查找
    For pos1 = 2 To Sheet2.UsedRange.Rows.Count
      tmpStr1 = Sheet2.Cells(pos1, 4)
      tmp = Sheet2.Cells(pos1, 5)
      
      Rem 找到指定數據,sheet2中的第5列是輔助查找結果的,sheet1中是第7列。
      If tmpStr = tmpStr1 Then
        Rem 在Sheet2中找到了,首先查看Sheet2中的輔助列是不是填了值,填了值說明以前sheet1中的數據在Sheet2中匹配過,這個就不能用,要繼續查找
        If Sheet2.Cells(pos1, 5) = "" Then
          Rem MsgBox "########sheet2######## NULL :" & Sheet2.Cells(pos1, 5) & " Row : " & pos1
          Rem Sheet2中的輔助列保存Sheet1 數據的行號
          Sheet2.Cells(pos1, 5) = "Row" & pos
          Rem Sheet1中的輔助列保存Sheet2 數據的行號
          Sheet1.Cells(pos, 7) = "Row" & pos1
          Rem MsgBox "########sheet2########" & tmpStr1 & " sheet1 : " & pos & " sheet2 : " & pos1
          Exit For
        Else
          Rem MsgBox "########sheet2######## not NULL :" & Sheet2.Cells(pos1, 5) & " Row : " & pos1
 
        End If
      
      End If
    
    Next
    
    If pos1 >= total2 Then
      Rem MsgBox "can't find " & tmpStr & " in sheet2 " & " Row : " & pos1
      Rem 將Sheet1中沒找到的數據設置成紅色
      Sheet1.Cells(pos, 6).Interior.ColorIndex = 3
      
      Dim i
      For i = 1 To col
        Rem 將Sheet1中沒找到的數據行復制到Sheet3
        Sheet3.Cells(sheetR, i) = Sheet1.Cells(pos, i)
      Next
      
      sheetR = sheetR + 1
    End If

  Next
  MsgBox ("Done!!!")
End Sub

Rem開頭的是註釋

Sheet3中保存的數據就是未匹配的項,以Sheet1中的某一列數據爲匹配對象在Sheet2中查找

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章