比较两个范围VBA

时间:2017-06-15 18:36:12

标签: excel vba excel-vba

我尝试使用以下VBA代码与excel中的范围进行比较:

Sub CompareTwoRanges()
Dim wb As Workbook
Dim ws1 As Worksheet
Dim ws2 As Worksheet
Dim rng1 As Range
Dim rng2 As Range

Set wb = ThisWorkbook
Set ws1 = wb.Sheets("Sheet1")
Set ws2 = wb.Sheets("Sheet2")
Set rng1 = ws1.Range("A14:C14")
Set rng2 = ws2.Range("N3:P3")

If rangesAreEqual(rng1, rng2, ws1, ws2) Then
MsgBox "The ranges are equal."
Else
MsgBox "Sorry. The ranges are NOT equal."
End If
End Sub

Function rangesAreEqual(rng1 As Range, rng2 As Range, _
ws1 As Worksheet, ws2 As Worksheet) As Boolean
' booleans default to false
' verify ranges have same dimensions
If rng1.Columns.Count <> rng2.Columns.Count Then Exit Function
If rng1.Rows.Count <> rng2.Rows.Count Then Exit Function

' ranges are the same size. are their contents equal?
rangesAreEqual = ws1.Evaluate("=AND(EXACT(" & ws1.Name & "!" & _
rng1.Address & "," & ws2.Name & "!" & rng2.Address & "))")
End Function

但是我收到错误类型不匹配。

任何人都有关于问题的想法吗?

我从其他帖子(Compare Two Ranges)获得此代码但是我无法发表评论,要求发布代码的人为什么我可能会遇到此问题。

1 个答案:

答案 0 :(得分:1)

已回答:Fastest way to check if two ranges are equal in excel vba

请注意,链接的问题也标记为重复。转到原始帖子以查看完整答案。如果应该帮助你,并回答所有问题。

话虽如此,请使用此工作表:https://msdn.microsoft.com/en-us/library/office/ff838238.aspx查看范围对象在VBA中可以执行的所有操作。