On error goto 0
dará la mano a básico visual para el tratamiento de error (en la caja de mensaje general)
On error goto label
a dirigir su código para etiqueta:
On error resume next
ignorará el error y continuar
Resume next
redirigir el código a la línea siguiente en popa er el error se eleva
que significa que las combinaciones de instrucciones tales como
On Error goto 0
...
On Error goto 0
no tienen sentido
y si quieres volver a dirigir una instrucción "On Error" que tendrá que hacer de esta manera:
Do While Not rs.EOF
On Error Resume Next
rs2.Open strsql
On error Goto 0
rs2.moveNext
Loop
Si desea redirigir un error en una etiqueta (para el tratamiento o lo que sea) y luego volver al código donde ocurrió el error, usted tiene que escribir algo como:
On error goto label
...
...
On error goto 0
exit sub (or function)
label:
....
resume next
end function
Pero realmente le aconsejo que sea más riguroso en la gestión de errores. Primero debe ser capaz de hacer algo así:
Set objexcel = CreateObject("excel.Application")
objexcel.Visible = True
On Error GoTo error_Treatment
wbExists = False
Set wbexcel = objexcel.Workbooks.Open("C:\REPORT3.xls")
Set objSht = wbexcel.Worksheets("Sheet1")
objSht.Activate
wbExists = True
On error GoTo 0
Set db = DBEngine.opendatabase("C:\book.mdb")
Set rs = db.OpenRecordset("records")
Set rs2 = CreateObject("ADODB.Recordset")
rs2.ActiveConnection = CurrentProject.Connection
For Each tdf In CurrentDb.TableDefs
....
'there are a number of potential errors here in your code'
'you should make sure that rs2 is closed before reopening it with a new instruction'
'etc.'
Next tdf
Exit sub
error_treatment:
SELECT Case err.number
Case **** '(the err.number raised when the file is not found)'
objexcel.Workbooks.Add
Set wbexcel = objexcel.ActiveWorkbook
Set objSht = wbexcel.Worksheets("Sheet1")
Resume next 'go back to the code'
Case **** '(the recordset cannot be opened)'
....
....
Resume next 'go back to the code'
Case **** '(whatever other error to treat)'
....
....
Resume next 'go back to the code'
Case Else
debug.print err.number, err.description '(check if .description is a property of the error object)'
'your error will be displayed in the immediate windows of VBA.'
'You can understand it and correct your code until it runs'
End select
End sub
El siguiente paso será el de anticipar los errores en su código para que no se planteó el objeto Err.Por ejemplo, puede escribir una función genérica como éste:
Public function fileExists (myFileName) as Boolean
A continuación, puede tomar ventaja de esta función en el código mediante pruebas de la existencia de su archivo xls:
if fileExists("C:\REPORT3.xls") Then
Set wbexcel = objexcel.Workbooks.Open("C:\REPORT3.xls")
Else
objexcel.Workbooks.Add
Set wbexcel = objexcel.ActiveWorkbook
Endif
Set objSht = wbexcel.Worksheets("Sheet1")
objSht.Activate
No es necesario su variable wbExist más ...
De la misma manera, debe anticipar el caso donde su recordset no tiene registros. Anotar rs.MoveFirst antes de probar podría generar un error. A continuación, debe escribir
If rs.EOF and rs.BOF then
Else
rs.moveFirst
Do while not rs.EOF
rs.moveNext
Loop
Endif
Gracias que hizo el trabajo. Pero, como una duda, no es posible cancelar el manejo de errores una vez que se haya utilizado antes de seguir adelante en el programa. – tksy
Pregunta: en VBA es más eficiente cuando se prueba una cadena de longitud cero para usar vbNullString en lugar de "" porque esa constante de acceso ya tiene asignada su memoria. No importa en esta constante, pero es bueno adoptar el hábito para que siempre use vbNullString dentro de los bucles. –
@tksy: "En caso de error GoTo 0" hace exactamente eso. Devuelve VBA a su manejo de error habitual. No significa "On Go Go Start", que creo que su pregunta implica. –