繁体   English   中英

使用excel VBA比较不同工作表中的两个数据集并打印其他工作表中的差异?

[英]Compare two data sets in different sheet and print difference in other sheet using excel VBA?

我在两个不同的工作表中有两个数据集Sheet1是我的原始参考,sheet2用于比较。 Sheet2数据应与Sheet1进行比较,并打印出sheet2的整个不匹配的行,并突出显示具有不匹配数据的单元格,并且此差异应与其他指定的Sheet中的列标题和指定范围一起打印

此外,不匹配单元格计数应在任何sheet3指定范围的单元格中更新

下面是尝试的代码。 任何帮助将不胜感激。

Sub CompareDataSet()
Call compareSheets("Sheet1", "Sheet2")
End Sub
Sub compareSheets(Sheet1 As String, Sheet2 As String)
Dim Cell As Range
Dim CellMisMatch As Integer
For Each Cell In ActiveWorkbook.Worksheets(Sheet1).UsedRange
If Not Cell.Value = ActiveWorkbook.Worksheets(Sheet2).Cells(Cell.Row, Cell.Column).Value Then
Let Worksheets("Sheet3").Cells(Cell.Row, Cell.Column) = Cell
Cell.Interior.Color = vbYellow
CellMisMatch = CellMisMatch + 1
End If
Next
ThisWorkbook.Sheets("Sheet3").Cells(1, 1).Value = CellMisMatch
End Sub

这是将对sheet1和sheet2(对应的单元格)进行比较并根据结果将正确的值或Mismatch转换为sheet3的代码。 Sheet1和sheet2的行和列数相同,并且标题相同,因此可以将其保留在sheet3中。 希望能帮助到你。

Sub Compare()

'Clearing the contents of the third sheet for the fresh comparison

usedCoulms = Sheets("Sheet3").UsedRange.Columns.Count
usedRows = Sheets("Sheet3").UsedRange.Rows.Count
For i = 2 To usedRows
For j = 1 To usedCoulms
   Sheets("Sheet3").Cells(i, j).Value = ""
   Sheets("Sheet3").Cells(i, j).Interior.Color = RGB(255, 255, 255)
Next
Next

'Coulmn count of first sheet
ColumnCount = Sheets("Sheet1").UsedRange.Columns.Count
'row count of first sheet
RowCount = Sheets("Sheet1").UsedRange.Rows.Count

For i = 2 To RowCount
For j = 1 To ColumnCount
    If Sheets("Sheet1").Cells(i, j).Value <> Sheets("Sheet2").Cells(i, j).Value Then    'Comparing if values are not equal
        Sheets("Sheet3").Cells(1, j).Value = Sheets("Sheet1").Cells(1, j).Value 'Copying the Header of the Mismatched Cell
        Sheets("Sheet3").Cells(i, j).Value = CStr("MisMatch")   'If mismatch setting set value as MisMatch
        Sheets("Sheet3").Cells(i, j).Interior.Color = 65535     'Highlighting with Yellow color

    Else
        Sheets("Sheet3").Cells(i, j).Value = Sheets("Sheet1").Cells(i, j).Value
        'If values are same copy the first sheets value if dont want to copy can skip this
    End If
Next
Next

End Sub

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM