簡體   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