0
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

问:我尝试比较不同工作簿中的 2 张工作表,但无法执行上面的代码。

4

1 回答 1

0

除了一些未声明的变量(使用 Option Explicit 将防止这种情况,以及变量名中的拼写错误),您的代码对我来说很好,只需进行一些小的修改:

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

截屏:

在此处输入图像描述

我唯一注意到的是,必须打开两个工作簿才能使此代码正常工作。如果要输入文件名和路径,则需要在Workbooks.Open输入框中使用该方法,例如:

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

否则,您的输入框没有任何错误处理,因此如果您收到Subscript out of Range错误,则可能是您没有将工作簿或工作表名称正确输入到输入框中。

于 2013-08-29T03:44:11.290 回答