错误重置无效

时间:2016-01-07 18:55:43

标签: excel vba excel-vba

我正在编写一个宏来重新编号点和线。在以下代码中,Err.Number未重置,并且代码在第二个错误实例处中断。如何解决这个问题?

S = 0
SS = 0
Surfaces = Y

Do
    SS = SS + 1
Handler:
    S = S + 1

    On Error GoTo Handler

    Set hybridBodyShape1 = hybridBodyShapes1.Item("Line_Extract_" & S)
    hybridBodyShape1.Name = "Line_Extract_" & SS

    Set hybridBodyShape1 = hybridBodyShapes1.Item("Point_Extract_" & S)
    hybridBodyShape1.Name = "Point_Extract_" & SS

    On Error GoTo 0
Loop Until S = Surfaces - 1

2 个答案:

答案 0 :(得分:1)

我不知道您对循环(或您的错误"处理程序")的期望,但您可能应该将实现更改为以下内容:

Protected Sub avatar_click(sender As Object, e As EventArgs)
   Dim btn As ImageButton = CType(sender, ImageButton)
   Dim buttonClickedValue As String = btn.CommandArgument
End Sub

On Error Resume Next Do If Err.Number = 0 Then SS = SS + 1 Err.Clear S = S + 1 Set hybridBodyShape1 = hybridBodyShapes1.Item("Line_Extract_" & S) hybridBodyShape1.Name = "Line_Extract_" & SS If Err.Number = 0 Then Set hybridBodyShape1 = hybridBodyShapes1.Item("Point_Extract_" & S) hybridBodyShape1.Name = "Point_Extract_" & SS End If Loop Until S = Surfaces - 1 On Error GoTo 0 对象不会因为你在错误的情况下跳转到标签而神奇地重置自己。

答案 1 :(得分:1)

在VBA中,一旦脚本抛出错误,它就不会因为您启用了错误处理程序而自动重置。要正确重置错误,您应该在某处有Resume语句。典型的错误处理例程如下所示:

Sub ErrorProne()
    Dim i As Integer        
    Dim myArr(4) As Integer

    On Error Goto ErrHndl
    Do While True
        myArr(i) = i    '<-- will bug on 5th iteration
    Loop
PostLoop:
    'More code goes here

Exit Sub

ErrHndl:
    Resume PostLoop
End Sub    

有关如何使用错误处理的更完整描述,请参阅Chip Pearson的网站:http://www.cpearson.com/excel/errorhandling.htm