![](/img/trans.png)
[英]Use macro to compare column in two Excel worksheets and add matches to third sheet
[英]Compare two EXCEL worksheets and copy similar data onto a third sheet
我寫了一個vba代碼,可以比較兩個EXCEL工作表並將相似的行粘貼到第三工作表。 這里是:
'Same data
'If condition met, copy cells
j = 2
For i = 2 To OLast_row
IsEqual = False
For j = 2 To NLast_row
If OWS.Cells(i, 1).Value = NWS.Cells(j, 1).Value Then
For Z = 2 To OLast_clmn
If OWS.Cells(i, Z).Value = NWS.Cells(j, Z).Value Then
IsEqual = True
Else
IsEqual = False
End If
Next
If IsEqual = True Then
cnt = cnt + 1
CompareWS.Cells(cnt, 1).Value = same
For D = 1 To OLast_clmn
OWS.Cells(i, D).Copy CompareWS.Cells(cnt, D + 1)
Next
End If
Else
Next
Next
Sheet1是較早聲明的“ OWS”,Sheet2是較早聲明的“ NWS”,Sheet2是較早聲明的“ CompareWS”
問題是,此代碼停止比較單元格1級別的單元格; 例如,如果兩行(每個工作表中的每一行)以相同的數據開頭,則基於該單元格,程序將把兩行視為相同,即使其余數據不匹配也是如此。
我懷疑“ For Z ...”的條件沒有超出應有的范圍,但不知道如何修復它。
舊數據示例: OldData
新數據示例: NewData
基於這些數據,ComparedData會是什么樣子: ComparedData
希望這會有所幫助
預先感謝您對此發表看法。
最好。
感謝@Mark Balhoff:我會這樣嘗試
j = 2
For i = 2 To OLast_row
IsEqual = False
For j = 2 To NLast_row
isequal=true
For Z = 1 To OLast_clmn
If OWS.Cells(i, Z).Value <> NWS.Cells(j, Z).Value Then
IsEqual = False
exit for
End If
Next
If IsEqual = True Then
' copy cells
End If
Next
Next
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.