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张,但我无法执行上面的代码。
答案 0 :(得分: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
截图:
我唯一注意到的是,两个工作簿必须必须才能使此代码正常工作。如果您输入文件名&amp;路径,您需要在输入框中使用Workbooks.Open
方法,例如:
Set wb1 = Workbooks.Open(InputBox("enter b1"))
Set wb2 = Workbooks.Open(InputBox("enter b2"))
否则,您的输入框没有任何错误处理,因此如果您收到Subscript out of Range
错误,则表明您没有正确地将工作簿或工作表名称输入到输入框中。