比较两个单元格,如果相等,则比较两个不同的单元格,如果不相等则突出显示结果

时间:2016-08-01 21:12:06

标签: excel vba excel-vba

我正在尝试比较两个不同工作簿上的两个单元格。如果相等,脚本应该进一步比较那些(相同)工作簿上的其他两个不同的单元格,并突出显示那些不相等的单元格。

我尝试了以下内容:

Add-Migration

然而,这不起作用。它会抛出Sub Compare() Dim mycell As Range Dim shtSheet1 As Worksheet Dim shtSheet2 As Worksheet Set shtSheet1 = Workbooks("100Series").Worksheets("Report") Set shtSheet2 = Workbooks("UserWorkbook").Worksheets("User") For Each mycell In shtSheet2.UsedRange If Not mycell.Value = shtSheet1.Cells(mycell.Row, mycell.Column).Value Then mycell.Interior.Color = vbRed End If Next End Sub 错误。我不确定什么是超出范围。每个工作表长3500行,宽2列。

我目前的代码出了什么问题?

2 个答案:

答案 0 :(得分:0)

这样的东西?

Dim sht1 As Worksheet, sht2 As Worksheet
Dim y As Integer, x As Integer

Private Sub CompareStuff()

    Set sht1 = Workbooks("Wb1.xlsm").Worksheets("Sheet1")    'Make sure to pick the right name.
    Set sht2 = Workbooks("Wb2.xlsm").Worksheets("Sheet2")
    y = 1

    Do While y <= ActiveSheet.Columns("A").Cells.Find("*", _
                  SearchOrder:=xlByRows, LookIn:=xlValues, SearchDirection:=xlPrevious).Row
        For x = 1 To 2
            If sht1.Cells(y, x).Value <> sht2.Cells(y, x).Value Then
                sht1.Cells(y, x).Interior.ColorIndex = 3
                sht2.Cells(y, x).Interior.ColorIndex = 3
            End If
        Next x
        y = y + 1
    Loop

End Sub

答案 1 :(得分:0)

谢谢,我想出了以下内容,看起来工作正常。问题是我希望它停止前两列(在两个工作簿中)并忽略值中的空格。我该怎么做呢?

Sub Compare()
    Dim shtSheet1 As Worksheet
    Dim shtSheet2 As Worksheet
    Set shtSheet1 = Workbooks("100Series").Worksheets("Report")
    Set shtSheet2 = Workbooks("UserWorkbook").Worksheets("User")
        For Each mycell In shtSheet1.UsedRange
          If Not mycell.Value = shtSheet2.Cells(mycell.Row, mycell.Column).Value Then
            mycell.Interior.Color = vbRed
           ElseIf mycell.Value = shtSheet2.Cells(mycell.Row, mycell.Column).Value Then
            If Not mycell.Offset(0, 1).Value = shtSheet2.Cells(mycell.Row, mycell.Column + 1).Value Then
                mycell.Interior.Color = vbRed
                End If
           End If
        Next
    End Sub