简体   繁体   中英

How to compare two sheets in different work books and highlight the difference in 2nd sheet?

Sub compare2sheetsex() 'and highlight the diffrence
    Dim wb1 As Workbook, wb2 As Workbook, sh1 As Worksheet, sh2 As Worksheet
    Set wb1 = Workbooks(InputBox("enter b1"))
    Set wb2 = Workbooks(InputBox("enter b2"))
    Set sh1 = wb1.Sheets(InputBox("enter s1"))
    Set sh2 = wb2.Sheets(InputBox("enter s2"))
    rcount = sh1.UsedRange.Rows.Count
    ccount = sh1.UsedRange.Columns.Count
    Dim r As Long, c As Integer
    For r = 1 To rcount
        For c = 1 To ccount
            If sh1.Cells(r, c) <> sh2.Cells(r, c) Then
                sh2.Cells(r, c).Interior.ColorIndex = 6
            End If
        Next c
    Next r
    Set sh1 = Nothing
    Set sh2 = Nothing
End Sub

Q:I tried to compare 2 sheets in different workbooks but i am unable to execute the code above.

Aside from some undeclared variables (using Option Explicit will prevent this, and typos in variable names), your code works fine for me with some minor modifications:

Option Explicit
Sub compare2sheetsex() 'and highlight the diffrence
    Dim wb1 As Workbook, wb2 As Workbook, sh1 As Worksheet, sh2 As Worksheet
    Dim rCount As Long, cCount As Long
    Set wb1 = Workbooks(InputBox("enter b1"))
    Set wb2 = Workbooks(InputBox("enter b2"))
    Set sh1 = wb1.Sheets(InputBox("enter s1"))
    Set sh2 = wb2.Sheets(InputBox("enter s2"))
    rCount = sh1.UsedRange.Rows.Count
    cCount = sh1.UsedRange.Columns.Count
    Dim r As Long, c As Integer
    For r = 1 To rCount
        For c = 1 To cCount
            If sh1.Cells(r, c) <> sh2.Cells(r, c) Then
                sh2.Cells(r, c).Interior.ColorIndex = 6
            End If
        Next c
    Next r
    Set sh1 = Nothing
    Set sh2 = Nothing
End Sub

Screenshot:

在此处输入图片说明

The only thing I notice is that both workbooks must be open for this code to work. If you are entering a filename & path, you'll need to use the Workbooks.Open method with your input boxes, eg:

Set wb1 = Workbooks.Open(InputBox("enter b1"))
Set wb2 = Workbooks.Open(InputBox("enter b2"))

Otherwise, you don't have any error-handling with your inputboxes so it's possible that if you receive Subscript out of Range errors, that you did not correctly input the Workbook or Worksheet names to the inputboxes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM