使用Range.Find()VBA进行错误处理

时间:2014-12-08 14:53:20

标签: excel vba excel-vba

我用这个工作代码回答了question

此vba代码将自下而上循环遍历所有ID,如果传真号已存在,则会将ID添加到C,D,E等列中的该行(始终选择下一个空白处),然后删除这条线。最后,它会交换A列和B列,因此您在Col A中留下传真号码,而Cols B,C,D,E等则是与该号码相关联的所有ID。

经过测试的工作:

Sub RemoveDups()

Dim CurRow As Long, LastRow As Long, DestLast As Long, DestRng As Range

LastRow = Range("A" & Rows.Count).End(xlUp).Row

On Error Resume Next
 For CurRow = LastRow To 3 Step -1
     Set DestRng = Range("B2:B" & CurRow - 1).Find(Range("B" & CurRow).Value, LookIn:=xlValues, LookAt:=xlWhole, SearchDirection:=xlNext)
        DestRng = DestRng
     If Err > 0 Then
        Err.Clear
     Else
        DestLast = Cells(DestRng.Row, Columns.Count).End(xlToLeft).Column + 1
        Cells(DestRng.Row, DestLast).Value = Cells(CurRow, 1).Value
        Cells(CurRow, 1).EntireRow.Delete xlShiftUp
     End If
 Next CurRow
Columns("B:B").Cut
Columns("A:A").Insert Shift:=xlToRight
Application.CutCopyMode = False

MsgBox "Done"

End Sub

我的问题是:为什么我需要额外的行DestRng = DestRng?我添加它的原因是因为代码无法运行,所以我添加了一个检查以将DestRng转储到Cells.Value。突然之间,代码工作了,所以我做了一个简单的DestRng = DestRng行,以确保仍然存在可能出错的代码。如果我注释掉该行,它将返回到无效的代码。试图找出Range.Find()不会激活错误处理程序的原因,但DestRng = DestRng将激活错误处理程序。

编辑:截图:

  • 以前的数据: DataBefore
  • DestRng = DestRngEntireRow.Delete的数据已注释掉:CommentOut
  • 数据与我的完整代码:FullCode

1 个答案:

答案 0 :(得分:2)

如果您从一个完全空的工作表开始并运行:

Sub errorTest()
    Dim r As Range
    Set r = Cells.Find(what:="something", after:=Range("A1"))
    r = r
End Sub

上的代码将失败
r=r

线。这是因为设置命令将r设置为 Nothing

r=r

相当于:

r.Value=r.Value