[英]Compare two EXCEL worksheets and copy similar data onto a third sheet
I wrote a vba code that would allow me to compare two EXCEL worksheets and paste similar rows to a third sheet. 我写了一个vba代码,可以比较两个EXCEL工作表并将相似的行粘贴到第三工作表。 Here it is: 这里是:
'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 being "OWS" declared earlier, Sheet2 being "NWS" declared earlier, Sheet2 being "CompareWS" declared earlier Sheet1是较早声明的“ OWS”,Sheet2是较早声明的“ NWS”,Sheet2是较早声明的“ CompareWS”
The problem is, this code stops comparing the cells at cell 1 level; 问题是,此代码停止比较单元格1级别的单元格; for example, if two rows (one in each worksheet) start with the same data, based on this cell the program will consider both rows as identical even if the rest of data don't match. 例如,如果两行(每个工作表中的每一行)以相同的数据开头,则基于该单元格,程序将把两行视为相同,即使其余数据不匹配也是如此。
I suspect "For Z..." condition for not going further than it should, but have no idea how as to how to repair it. 我怀疑“ For Z ...”的条件没有超出应有的范围,但不知道如何修复它。
Example of Old data: OldData 旧数据示例: OldData
Example of New data: NewData 新数据示例: NewData
Based on these data, ComparedData would look like: ComparedData 基于这些数据,ComparedData会是什么样子: ComparedData
Hope this will help 希望这会有所帮助
Thank you in advance for shedding light on this. 预先感谢您对此发表看法。
Best. 最好。
Credits to @Mark Balhoff: I would try it this way 感谢@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.