Pergunta

Eu tenho escrito uma macro VBA que abre um documento HTML dentro de Excel (a fim de realizar vários cálculos sobre ele). Excel irá procurar o documento HTML dentro da pasta atual. Se não puder encontrá-lo lá que irá produzir uma caixa de abertura de arquivo onde o usuário pode navegar até o local do documento HTML manualmente. Tudo bem até agora. No entanto, se o usuário selecione Cancelar (em vez de selecionar um arquivo), eu quero Excel para exibir uma mensagem e sair.

A mensagem é produzido, mas, em seguida, o código pára com o seguinte erro:

Erro em tempo de execução '424':. Objeto necessário

Esta não soa como muito trabalho, mas eu tenho corrido em uma parede de tijolos após o outro tentando prego o que está causando o problema.

O sub que simplesmente não parecem funcionar é:

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

Estou usando o MS Excel 2002, mas estou afiado para a solução de trabalho em tantas variantes do Excel quanto possível.

Qualquer ajuda gratamente recebidas a respeito de onde estou indo errado. Eu sou um novato completo pelo caminho, então se possível por favor, ser prolixo com qualquer orientação que você pode ter para mim ...

Como poderia ser de uso incluído abaixo (com o risco de fazer este post pesado) são os outros dois subs que estou usando na macro:

Primeiro 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

E a segunda 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

Se você chegou até aqui, obrigado pela leitura ....

Foi útil?

Solução

Adicionar uma chamada para ActiveWorkbook.Close para 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

Isso funciona para mim sob Excel 2003.

Por alguma razão, a fim de chamar Application.Quit e ActiveWorkbook.Close é importante. Contra-intuitivamente, pelo menos para mim, se você chamar ActiveWorkbook.Close antes Application.Quit você ainda obter o erro.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top