[英]compare data from two worksheets based on values of column a column d
我正在尋找一個VBA代碼,該代碼循環遍歷sheet1中的所有行,以基於sheet1中的colmn a和d值在sheet2中的a列和d列中找到匹配的數據來查找數據匹配。 示例列a 1011列d john。 如果在sheet2的某處,列a = 1011,列d同一行= john,則找到匹配項。 我需要將所有不匹配項保存到新工作簿中。
嘗試這個。 將結果放入此工作簿的Sheet3中。 >>
Option Explicit ' it is your friend
Sub do_FindOrphans()
' create or find Sheet3, and clear it out
If Not Evaluate("ISREF('Sheet3'!A1)") Then
Sheets.Add After:=ActiveSheet
ActiveSheet.Name = "Sheet3"
Else
Sheets("Sheet3").Activate
End If
Cells.Select
Selection.ClearContents
' initialize max row#, and copy in column headings
Sheets("Sheet1").Select
Dim s1row As Long, s1max As Long, s1col As Long, s1endcol As Integer
s1max = Sheets("Sheet1").Cells(Rows.Count, 1).End(xlUp).Row
Sheets("Sheet2").Select
Dim s2row As Long, s2max As Long
s2max = Sheets("Sheet2").Cells(Rows.Count, 1).End(xlUp).Row
Dim s3row As Long, matched As String
With ActiveSheet
s1endcol = .Cells(1, .Columns.Count).End(xlToLeft).Column
End With
s3row = 1
For s1col = 1 To s1endcol
Sheets("Sheet3").Cells(s3row, s1col) = Sheets("Sheet1").Cells(1, s1col)
Next s1col
' step thru sheet1
For s1row = 2 To s1max
matched = "N"
' step thru sheet2
For s2row = 2 To s2max
' Compare the keys
If Sheets("Sheet1").Cells(1, s1row) = Sheets("Sheet2").Cells(1, s2row) _
And Sheets("Sheet1").Cells(4, s1row) = Sheets("Sheet2").Cells(4, s2row) Then
matched = "Y"
Exit For
End If
Next s2row
If matched = "N" Then
s3row = s3row + 1
For s1col = 1 To s1endcol
Sheets("Sheet3").Cells(s3row, s1col) = Sheets("Sheet1").Cells(s1row, s1col)
Next s1col
End If
Next s1row
End Sub
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.