我想比较2个动态命名范围(OriData和Filterdata),如果OriData和Filterdata完全相同,则将Filterdata设置为""(空)(Filterdata是OriData的两次预先过滤的结果) ,如果两者都相同,我想把它归零。我几乎无法提出这个代码但是 它总是显示"不同的范围"。我的代码有什么问题,如果您能够根据我的需要提出编辑后的代码,我会深表感激(如果相同,则为Filterdata为零)
Sub Santa()
Dim Dn As Range
For Each Dn In Range("OriData")
If Not Dn = Range("Filterdata").Cells(Dn.Row, Dn.Column) Then MsgBox "Disimilar ranges": Exit Sub
Next Dn
MsgBox "Both Ranges have the same data"
End Sub
我在vba中真的很新,所以请耐心等待... 提前谢谢!
答案 0 :(得分:0)
Dn.Row
和Dn.Column
是工作表上的行和列,而不是Range(“OriData”)中的相对行。当您尝试引用Range(“Filterdata”)中的姐妹单元格时,您没有引用相同的单元格位置。
Sub Santa()
Dim r As Long, c As Long
If Range("OriData").Count <> Range("Filterdata").Count Then
MsgBox "Dissimilar range sizes"
Exit Sub
End If
For r = 1 To Range("OriData").Rows.Count
For c = 1 To Range("OriData").Columns.Count
If Not Range("OriData").Cells(r, c) = Range("Filterdata").Cells(r, c) Then
MsgBox "Dissimilar range values"
Exit Sub
End If
Next c
Next r
MsgBox "Both Ranges have the same data"
End Sub
答案 1 :(得分:0)
这使用了一种不同的方法。当范围很大时,循环遍历工作表是低效的。这里,首先将范围复制到变量中,然后进行比较。如果相同,则清除命名范围(删除值)或删除(值和命名范围) - 如果需要,取消注释。
包含错误检查。
代码使用有意义的变量名来帮助理解和维护它:
Sub DeleteIfIdentical()
Dim r As Long, c As Long
Dim ub1 As Long, ub2 As Long
Dim original, filtered ' arrays holding the named ranges' values
On Error GoTo NoSuchRange
original = Range("original")
filtered = Range("filtered")
On Error GoTo 0
ub1 = UBound(original, 1)
ub2 = UBound(original, 2)
If Not (UBound(filtered, 1) = ub1) And _
(UBound(filtered, 2) = ub2) Then
MsgBox "Ranges are not identical!"
Exit Sub
End If
For r = 1 To ub1
For c = 1 To ub2
If original(r, c) <> filtered(r, c) Then
MsgBox "Ranges are not identical!"
Exit Sub
End If
Next c
Next r
MsgBox "Both Ranges have the same data"
Range("filtered").Clear ' to clear all values
' Range("filtered").Delete ' to clear all values and delete the named range
Exit Sub
NoSuchRange:
MsgBox "Error accessing named ranges 'orginal' and/or 'filtered'"
End Sub