比较Excel中的工作表 - 我的范围与我的数组

时间:2017-09-28 17:30:24

标签: excel vba excel-vba

我想在工作簿中比较三个工作表(应该是相同的)并突出显示任何不匹配的单元格。我在Using VBA to compare two Excel workbooks上添加了以下代码:

Sub CompareWorksheets()

Dim varSheetA As Worksheet
Dim varSheetB As Worksheet
Dim varSheetC As Worksheet
Dim varSheetAr As Variant
Dim varSheetBr As Variant
Dim varSheetCr As Variant
Dim strRangeToCheck As String
Dim iRow As Long
Dim iCol As Long

Set varSheetA = Worksheets("DS") 
Set varSheetB = Worksheets("HT") 
Set varSheetC = Worksheets("NM") 

strRangeToCheck = ("A1:L30")
' If you know the data will only be in a smaller range, reduce the size of the ranges above.

varSheetAr = varSheetA.Range(strRangeToCheck).Value
varSheetBr = varSheetB.Range(strRangeToCheck).Value
varSheetCr = varSheetC.Range(strRangeToCheck).Value ' or whatever your other sheet is.


For iRow = LBound(varSheetAr, 1) To UBound(varSheetAr, 1)
    For iCol = LBound(varSheetAr, 2) To UBound(varSheetAr, 2)
        Debug.Print iRow, iCol
        If varSheetAr(iRow, iCol) = varSheetBr(iRow, iCol) And varSheetAr(iRow, iCol) = varSheetCr(iRow, iCol) Then
          varSheetA.Cells(iRow, iCol).Interior.ColorIndex = xlNone
          varSheetB.Cells(iRow, iCol).Interior.ColorIndex = xlNone
          varSheetC.Cells(iRow, iCol).Interior.ColorIndex = xlNone
        Else
          varSheetA.Cells(iRow, iCol).Interior.ColorIndex = 22
          varSheetB.Cells(iRow, iCol).Interior.ColorIndex = 22
          varSheetC.Cells(iRow, iCol).Interior.ColorIndex = 22

        End If
    Next
Next

End Sub

问题是,当“strRangeToCheck”从A1开始时,一切都按预期工作,但只要我将范围更改为类似(“B4:C6”),看起来仍然正在进行正确的比较,但突出显示的单元格总是被移回到单元格A1作为起点(而不是B4,这就是我想要的)。换句话说,突出显示“模式”是正确的,但向上移动并在几个单元格上移动。

2 个答案:

答案 0 :(得分:1)

我扩展了@Vityata示例。

try { FileStream File = new FileStream("beispiel.txt", FileMode.Open); } catch (FileNotFoundException fnfex) { //MessageBox with fnfex } finally { //idk } 在最多60个工作表上比较相同的范围,而CompareWorksheets将比较相同大小和形状的范围。

CompareRanges

答案 1 :(得分:0)

我从第一次阅读中了解到,您有3个工作表要比较。如果要比较工作簿中前三个工作表中的选定范围,则此代码有效。它在每个工作簿中为红色的不同值着色:

Option Explicit

Sub compareWorksheets()

    Dim rngCell As Range
    Dim counter As Long

    For Each rngCell In Selection

       If Worksheets(1).Range(rngCell.Address) <> Worksheets(2).Range(rngCell.Address) _
       Or Worksheets(1).Range(rngCell.Address) <> Worksheets(3).Range(rngCell.Address) Then
            For counter = 1 To 3
                Worksheets(counter).Range(rngCell.Address).Interior.Color = vbRed
            Next counter
       End If

    Next rngCell

End Sub

如果您想比较三个工作表中的范围A1:Z10,请将Selection更改为Worksheets(1).Range("A1:Z10"),或者只选择一个工作簿中的范围。