vba问题与error handling

关于我的床单的所有信息在这里解释。 但我会很快解释它:

我有3张( Plan1, BANCO and DB )。 Plan1已经命名了我插入信息的范围,这些信息存储在BANCO并复制到BD (最后一个保存所有过去的信息,而BANCO只有最后一个信息被插入)。

我也有一个代码来validation命名的范围alocacao已经存在于BD ,如果存在,它们再次在Plan1Plan1 。 在此之后,您可以使用以下代码在名为substituit_aloc的范围中插入新名称后更改alocacao的名称:

 Sub SubstituirProduto_Click() Dim FoundCell As Range, FirstAddr As String, fnd As String, newAloc As Range, i As Long On Error GoTo Catch fnd = Sheets("Plan1").Range("alocacao").Value Set newAloc = Sheets("Plan1").Range("substituir_aloc") Set FoundCell = Sheets("BD").Columns(5).Find(what:=fnd, _ After:=Sheets("BD").Cells(Rows.Count, 5), Lookat:=xlPart, _ LookIn:=xlFormulas, SearchOrder:=xlByRows, SearchDirection:=xlNext) If Not FoundCell Is Nothing Then FirstAddr = FoundCell.Address End If Do Until FoundCell Is Nothing i = i + 1 FoundCell.Value = newAloc.Value Set FoundCell = Sheets("BD").Columns(5).FindNext(After:=FoundCell) If FoundCell.Address = FirstAddr Or i >= 30 Then Exit Do End If Loop Catch: MsgBox "Substituido!" End Sub 

有时会起作用,有时会得到:

运行时错误91:对象variables或未设置块variables

和高亮线:

 If FoundCell.Address = FirstAddr Or i >= 30 Then 

尽pipe有这个错误,但是它在不影响最终结果的前提下做到了。 因此,我添加了On Error GoTo Catch只是为了不显示错误消息,并完成运行代码,但我仍然收到错误消息。

有人知道为什么它仍然显示错误信息而不被我的error handling捕获?

 If Not FoundCell Is Nothing Then If FoundCell.Address = FirstAddr Or i >= 30 Then Exit Do End If End If 

在下面的代码中,在testing地址之前,FoundCell可能被设置为空(如果findnext没有返回),则会发生错误。

  Set FoundCell = Sheets("BD").Columns(5).FindNext(After:=FoundCell) If FoundCell.Address = FirstAddr Or i >= 30 Then Exit Do End If 

在地址testing之前查看FoundCell是否是一个testing可以解决这个问题:

 Do Until FoundCell Is Nothing i = i + 1 FoundCell.Value = newAloc.Value Set FoundCell = Sheets("BD").Columns(5).FindNext(After:=FoundCell) If FoundCell is nothing then Exit Do If FoundCell.Address = FirstAddr Or i >= 30 Then Exit Do Loop