比较2个excel工作簿并突出显示差异

时间:2016-10-26 09:45:59

标签: vba excel-vba excel

我正在尝试创建一个宏来比较2个excel工作簿,然后突出显示差异。我已经看过以前的解决方案并且他们帮了很多忙,但是我仍然无法让这个宏运行。我创建了2个脚本来查看哪个脚本效果最好。

1

Sub CompareWorkbooks()

Dim varSheetA As Variant
Dim varSheetB As Variant
Dim strRangeToCheck As String
Dim iRow As Long
Dim iCol As Long

strRangeToCheck = "A1:AK900"

'Get worksheets from the workbooks
Set wbkN = Workbooks.Open(Filename:="U:\gebouwensep.xlsx")
Set Nieuweversie = wbkN.Worksheets("gebouwen")


Set wbkO = Workbooks.Open(Filename:="U:\gebouwenaug.xlsx")
Set Oudeversie = wbkO.Worksheets("gebouwen")

If Nieuweversie <> Oudeversie Then
    Nieuweversie.Sheets(gebouwen).Cells(iRow, iCol).Interior.Color = vbYellow
End If

End Sub

2

Sub CompareWorkbooks()

Dim varSheetA As Variant
Dim varSheetB As Variant
Dim strRangeToCheck As String
Dim iRow As Long
Dim iCol As Long
Dim mycell As Range
Dim mydiffs As Integer

Nlin = 1
Ncol = 1

'get worksheets from the workbooks
Set wbkA = Workbooks.Open(Filename:="U:\gebouwensep.xlsx")
Set varSheetA = wbkA.Worksheets("gebouwen") 

Set wbkB = Workbooks.Open(Filename:="U:\gebouwenaug.xlsx")
Set varSheetB = wbkB.Worksheets("gebouwen")

strRangeToCheck = "A1:AK900"

varSheetA = varSheetA.Range(strRangeToCheck)
varSheetB = varSheetB.Range(strRangeToCheck)

For iRow = LBound(varSheetA, 1) To UBound(varSheetA, 1)
    For iCol = LBound(varSheetA, 2) To UBound(varSheetA, 2)
        If Not varSheetA(iRow, iCol) = varSheetB(iRow, iCol) Then

        Else
              Nieuweversie.Sheets(gebouwen).Cells(iRow, iCol).Interior.Color = vbYellow
        End If
    Next iCol
Next iRow

End Sub

1 个答案:

答案 0 :(得分:0)

我的解决方案是代码2

您的主要问题似乎是以下一行:

Nieuweversie.Sheets(gebouwen).Cells(iRow, iCol).Interior.Color = vbYellow

您没有为“Nieuweversie”或“gebouwen”设置变量。前者似乎是代码1遗留的代码2中的残余,我假设你真正需要的是这一行:

wbkA.Sheets("gebouwen").Cells(iRow, iCol).Interior.Color = vbYellow

我自己测试了这个解决方案,看来修复工作表引用会导致sub正确运行

同样 - 由于相同的行,这在代码1中不起作用(虽然我没有检查其余代码,但可能还有其他问题)。您的变量“Nieuwerversie”是一个工作表,您所做的是指“Worksheet.Sheets”对象,它不是有效的引用。如果您刚刚使用

Nieuweversie.Cells(iRow, iCol).Interior.Color = vbYellow

然后这应该修复代码1中的相同行,尽管我说我还没有测试其余的代码