Vba 如何比较不同工作手册中的两张工作表,并在第二张工作表中突出差异? Sub compare2sheetsex()”并突出显示差异 将wb1作为工作簿,wb2作为工作簿,sh1作为工作表,sh2作为工作表 设置wb1=工作簿(输入框(“输入b1”)) 设置wb2=工作簿(输入框(“输入b2”)) 设置sh1=wb1.Sheets(输入框(“输入s1”)) 设置sh2=wb2.Sheets(输入框(“输入s2”)) rcount=sh1.UsedRange.Rows.Count ccount=sh1.UsedRange.Columns.Count Dim r为长,c为整数 对于r=1,则为rcount 对于c=1的情况,应计算 如果是sh1.Cells(r,c)sh2.Cells(r,c),那么 sh2.单元(r,c).内部.ColorIndex=6 如果结束 下一个c 下一个r 设置sh1=无 设置sh2=无 端接头
问:我试图比较不同工作簿中的两张工作表,但我无法执行上面的代码。除了一些未声明的变量(使用Option Explicit将防止出现这种情况,并在变量名称中键入错误),您的代码对我来说运行良好,只需做一些小的修改:Vba 如何比较不同工作手册中的两张工作表,并在第二张工作表中突出差异? Sub compare2sheetsex()”并突出显示差异 将wb1作为工作簿,wb2作为工作簿,sh1作为工作表,sh2作为工作表 设置wb1=工作簿(输入框(“输入b1”)) 设置wb2=工作簿(输入框(“输入b2”)) 设置sh1=wb1.Sheets(输入框(“输入s1”)) 设置sh2=wb2.Sheets(输入框(“输入s2”)) rcount=sh1.UsedRange.Rows.Count ccount=sh1.UsedRange.Columns.Count Dim r为长,c为整数 对于r=1,则为rcount 对于c=1的情况,应计算 如果是sh1.Cells(r,c)sh2.Cells(r,c),那么 sh2.单元(r,c).内部.ColorIndex=6 如果结束 下一个c 下一个r 设置sh1=无 设置sh2=无 端接头,vba,excel,Vba,Excel,问:我试图比较不同工作簿中的两张工作表,但我无法执行上面的代码。除了一些未声明的变量(使用Option Explicit将防止出现这种情况,并在变量名称中键入错误),您的代码对我来说运行良好,只需做一些小的修改: Sub compare2sheetsex() 'and highlight the diffrence Dim wb1 As Workbook, wb2 As Workbook, sh1 As Worksheet, sh2 As Worksheet Set wb1 =
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
否则,您的输入框不会有任何错误处理,因此,如果您收到
下标超出范围的错误,则可能是您没有正确地将工作簿或工作表名称输入到输入框中。当您尝试执行上述代码时会发生什么?你有错误吗?或者只是意外的结果?我无法执行,是的,我收到一条错误消息。对不起,我无法完美地执行上述代码。我收到“订阅超出范围”错误哪一行引发错误?并且,在运行宏之前,两个工作簿都打开了吗?输入book1名称后,我收到运行时错误9“订阅超出范围”。那么这是两件事中的一件(两者实际上是同一件事):您键入的名称错误,或者指定的工作簿当前未打开。是的,David…工作表名称区分大小写。感谢您的帮助:)
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
Set wb1 = Workbooks.Open(InputBox("enter b1"))
Set wb2 = Workbooks.Open(InputBox("enter b2"))