4. On Error GoTo -1
Este tipo se utiliza para restablecer el estado de control de errores que se aplica en el ámbito del procedimiento actual. Los errores que se manejaron anteriormente ya no afectarán el flujo del programa.
Sub ExampleGoToMinusOne()
On Error GoTo ErrorHandler
Dim result As Double
result = 5 / 0 ' This causes an error
Exit Sub
ErrorHandler:
MsgBox "Error handled."
On Error GoTo -1 ' Clears previous error status
' If the error occurs again, handling must be reset
End Sub
Con On Error GoTo -1, se eliminará el manejo de errores anterior, por lo que puede configurar un nuevo manejo si es necesario.
5. Nested Error Handling
Puede utilizar varios niveles de control de errores de forma anidada. Esto le permite manejar diferentes tipos de errores por separado.
Private Sub CommandButton4_Click()
Dim firstNum, secondNum As Double
On Error GoTo error_handler1
firstNum = InputBox("Enter the first number")
On Error GoTo error_handler2
secondNum = InputBox("Enter the second number")
MsgBox firstNum / secondNum
Exit Sub
error_handler2:
MsgBox "Error! You tried to divide a number by zero! Try again!"
Exit Sub
error_handler1:
MsgBox "You did not enter a number! Try again!"
End Sub
6. Validación de entrada mediante IsNumeric
Antes de realizar una operación aritmética, puede validar la entrada utilizando la función IsNumeric para asegurarse de que los datos introducidos son numéricos.
Private Sub CommandButton5_Click()
Dim userInput As String
userInput = InputBox("Enter your age:")
If Not IsNumeric(userInput) Then
MsgBox "The input you entered is invalid. Please enter a number."
Exit Sub
End If
MsgBox "Your age is " & userInput & " years."
End Sub
Conclusión
El manejo de errores es una parte importante de la programación en Excel VBA. Al implementar varios tipos de manejo de errores, los programadores pueden crear aplicaciones más robustas y fáciles de usar, así como reducir la probabilidad de bloqueos debido a entradas no válidas.