Salir de Excel usando VBA causa un error de tiempo de ejecución 424
Pregunta
He estado escribiendo una macro de VBA que abre un documento HTML en Excel (para poder realizar varios cálculos en él). Excel buscará el documento HTML dentro de la carpeta actual. Si no puede encontrarlo allí, producirá un cuadro de archivo abierto donde el usuario puede buscar la ubicación del documento HTML manualmente. Todo bien hasta ahora. Sin embargo, si el usuario selecciona Cancelar (en lugar de seleccionar un archivo), quiero que Excel muestre un mensaje y se cierre.
Se produce el mensaje pero luego el código se detiene con el siguiente error:
Error en tiempo de ejecución '424': objeto requerido.
Esto no suena como una molestia, pero me he topado con una pared de ladrillos tras otra para intentar detectar qué está causando el problema.
El sub que parece que no funciona es:
Sub ExitWithoutPrompt()
MsgBox "You failed to select a file, therefore Excel will now close. Please refer to the readme file."
Excel.Application.DisplayAlerts = False
Excel.Application.Quit
End Sub
Estoy usando MS Excel 2002, pero estoy ansioso por que la solución funcione con tantas variantes de Excel como sea posible.
Cualquier ayuda recibida con gratitud en cuanto a dónde me voy mal. Por cierto, soy un novato completo, así que si es posible, por favor, dale un respiro con la orientación que puedas tener para mí ...
Como podría ser de uso incluido a continuación (a riesgo de que esta publicación sea difícil de manejar) están los otros dos subs que estoy usando en la macro:
Primer sub:
Sub Endurance()
Call OpenHTML
Range("G27").Value = "Category"
Range("G28").Value = "Meat"
Range("G29").Value = "Veg"
Range("G30").Value = "PRP"
Range("F27").Value = "Fleet"
Range("E27").Value = "Consumption"
Range("E32").Value = "Endurance"
Range("E33").Value = "Lowest Category"
Range("E34").Value = "Fleet"
Range("E35").Value = "Consumption"
Range("E27, F27, G27, E32").Font.Bold = True
Range("F28").Value = WorksheetFunction.Sum(Range("E8,E9,E11,E14,E21"))
Range("E28").Value = WorksheetFunction.Sum(Range("G8,G9,G11,G14,G21"))
Range("F29").Value = WorksheetFunction.Sum(Range("E10,E16"))
Range("E29").Value = WorksheetFunction.Sum(Range("G10,G16"))
Range("F30").Value = WorksheetFunction.Sum(Range("E20,E22"))
Range("E30").Value = WorksheetFunction.Sum(Range("G20,G22"))
Columns("E:F").EntireColumn.AutoFit
Range("G28:G30, E27, F27, G27, G33").Select
With Selection
.HorizontalAlignment = xlRight
End With
Range("E27:G30, E32:G35").Select
Selection.Borders(xlDiagonalDown).LineStyle = xlNone
Selection.Borders(xlDiagonalUp).LineStyle = xlNone
With Selection.Borders(xlEdgeLeft)
.LineStyle = xlContinuous
.Weight = xlThin
.ColorIndex = xlAutomatic
End With
With Selection.Borders(xlEdgeTop)
.LineStyle = xlContinuous
.Weight = xlThin
.ColorIndex = xlAutomatic
End With
With Selection.Borders(xlEdgeBottom)
.LineStyle = xlContinuous
.Weight = xlThin
.ColorIndex = xlAutomatic
End With
With Selection.Borders(xlEdgeRight)
.LineStyle = xlContinuous
.Weight = xlThin
.ColorIndex = xlAutomatic
End With
Selection.Borders(xlInsideVertical).LineStyle = xlNone
Selection.Borders(xlInsideHorizontal).LineStyle = xlNone
Dim Endurance As Double
Endurance = WorksheetFunction.Min(Range("F28:F30"))
Range("G34").Value = WorksheetFunction.RoundDown(Endurance, 0)
Endurance = WorksheetFunction.Min(Range("E28:E30"))
Range("G35").Value = WorksheetFunction.RoundDown(Endurance, 0)
Range("G33").Value = Endurance
Dim LowCat As String
LowCat = WorksheetFunction.VLookup(Endurance, Range("E28:G30"), 3, False)
Range("G33").Value = LowCat
ActiveSheet.PageSetup.PrintArea = "$A$1:$G$35"
ActiveSheet.PageSetup.Orientation = xlLandscape
Range("G36").Select
If MsgBox("Print endurance statement?", vbYesNo + vbDefaultButton2, "Print endurance") = vbYes Then
ActiveWindow.SelectedSheets.PrintOut Copies:=1
Else
Range("G36").Select
End If
End Sub
Y el segundo sub:
Sub OpenHTML()
On Error GoTo MissingFile
Workbooks.Open FileName:=ThisWorkbook.Path & "\TRICAT Endurance Summary.html"
Exit Sub
MissingFile:
Dim Finfo As String
Dim FilterIndex As Integer
Dim Title As String
Dim FileName As Variant
' Set up list of file filters
Finfo = "HTML Files (*.html),*.html," & _
"All Files (*.*),*.*,"
' Display *.html by default
FilterIndex = 1
' Set the dialog box caption
Title = "Select TRICAT Endurance Summary"
' Get the filename
FileName = Application.GetOpenFilename(FInfor, FilterIndex, Title)
' Handle Return info from dialog box
If FileName = False Then
Call ExitWithoutPrompt
Else
MsgBox "You selected" & FileName
Workbooks.Open FileName
End If
End Sub
Si has llegado hasta aquí, gracias por leer ...
Solución
Agregue una llamada a ActiveWorkbook.Close
a ExitWithoutPrompt
:
Sub ExitWithoutPrompt()
MsgBox "You failed to select a file, therefore Excel will now close. Please refer to the readme file."
Excel.Application.DisplayAlerts = False
Excel.Application.Quit
ActiveWorkbook.Close False
End Sub
Esto me funciona en Excel 2003.
Por alguna razón, es importante el orden de llamada Application.Quit
y ActiveWorkbook.Close
. Contraintuitivamente, al menos para mí, si llama ActiveWorkbook.Close
antes de Application.Quit
, todavía recibe el error.