比较两个工作簿给出不正确的结果

时间:2016-05-24 17:34:41

标签: excel-vba vba excel

当运行下面的宏来比较3列中的10,000个数据行时,它突出显示了一些匹配的记录。有人可以帮助我纠正这个问题吗?

Sub Compare()
Call Comparitor("Sheet1", "Sheet2")
End Sub
Sub Comparitor(shtSheet1 As String, shtSheet2 As String)

Dim X As Long
Dim Y As Long
Dim Z As Long
Dim diffnd As Long
Dim cnt1 As Long
Dim cnt2 As Long


cnt2 = Worksheets("Sheet2").Cells.SpecialCells(xlCellTypeLastCell).row
cnt1 = Worksheets("Sheet1").Cells.SpecialCells(xlCellTypeLastCell).row

'Color the mismatching cells in Yellow on Sheet2
For Z = 1 To cnt2
    For Y = 1 To cnt1
        If ActiveWorkbook.Worksheets(shtSheet2).Cells(Z, 1).Value = ActiveWorkbook.Worksheets(shtSheet1).Cells(Y, 1).Value Then
            For X = 2 To 22
                If Not ActiveWorkbook.Worksheets(shtSheet2).Cells(Z, X).Value = ActiveWorkbook.Worksheets(shtSheet1).Cells(Y, X).Value Then
                    ActiveWorkbook.Worksheets(shtSheet2).Cells(Z, X).Interior.Color = vbYellow
                    diffnd = diffnd + 1
                End If
            Next
        Exit For

1 个答案:

答案 0 :(得分:0)

尝试设置一些工作簿和工作表对象以更好地管理工作表。我不完全确定这是解决方案。当你设置cnt1和cnt2时,似乎唯一没有这样做的地方就是在开头。你也不使用shtSheet1或shtSheet2变量,只是字符串名称,所以也许它看不同的表格?

我在wb,ws1和ws2中添加了它,使其更具可读性。试一试,看看它做了什么。否则,我认为你的代码是正确的。

Sub Compare()
Call Comparitor("Sheet1", "Sheet2")
End Sub

Sub Comparitor(shtSheet1 As String, shtSheet2 As String)

Dim X As Long
Dim Y As Long
Dim Z As Long
Dim diffnd As Long
Dim cnt1 As Long
Dim cnt2 As Long

Dim wb As Workbook
Dim ws1 As Worksheet
Dim ws2 As Worksheet

Set wb = ActiveWorkbook
Set ws1 = wb.Sheets(shtSheet1)
Set ws2 = wb.Sheets(shtSheet2)

cnt2 = ws2.Cells.SpecialCells(xlCellTypeLastCell).Row
cnt1 = ws1.Cells.SpecialCells(xlCellTypeLastCell).Row

'Color the mismatching cells in Yellow on Sheet2
For Z = 1 To cnt2
    For Y = 1 To cnt1
        If ws2.Cells(Z, 1).Value = ws1.Cells(Y, 1).Value Then
            For X = 2 To 22
                If Not ws2.Cells(Z, X).Value = ws1.Cells(Y, X).Value Then
                    ws2.Cells(Z, X).Interior.Color = vbYellow
                    diffnd = diffnd + 1
                End If
            Next
        Exit For