使用Application.FileDialog(msoFileDialogSaveAs)时出错

时间:2013-08-09 06:01:14

标签: excel vba filedialog save-as

我有这个代码,用于准备保存和保存文件,但它会导致Excel“遇到错误”并关闭。我已将错误固定到.execute行。

为什么会导致崩溃并且有解决方法?

Sub Save_close()

    Dim Ws As Worksheet
    Dim Wb As Workbook

    Application.DisplayAlerts = False

    MsgBox "Do you want to Save a new copy", vbYesNo, "Save New"

    If vbYes Then

        Workbooks("A380 Master.xlsm").Sheets("OutPutSheet").Range("C:C", "F:F").Delete

    For Each Ws In ActiveWorkbook.Sheets
        If Not Ws.Name = "OutputSheet" Or Ws.Name = "Sheet1" Then
            Ws.Delete

        ElseIf Ws.Name = "OutputSheet" Or Ws.Name = "Sheet1" Then

        End If
    Next Ws

    With Application.FileDialog(msoFileDialogSaveAs)
        .Show
        .Execute
    End With

    ElseIf vbNo Then

        'Workbooks("A380 Master.xlsm").Sheets("OutPutSheet").Range("A1").Select
    End If

End Sub

1 个答案:

答案 0 :(得分:1)

总结上述评论,解决方案是:

Sub Save_close()

Dim Ws As Worksheet
Dim Wb As Workbook
Dim i as Long

Application.DisplayAlerts = False

Set Wb = Workbooks("A380 Master.xlsm")

If (MsgBox("Do you want to Save a new copy", vbYesNo, "Save New")) = vbYes Then

    Wb.Sheets("OutPutSheet").Range("C:C", "F:F").Delete

    For i = Wb.Sheets.Count to 1 step -1
        Set Ws = Wb.Sheets(i)
        ' Delete all except "OutputSheet" and "Sheet1"
        If Not (Ws.Name = "OutputSheet" Or Ws.Name = "Sheet1") Then
            Ws.Delete
    '    ElseIf Ws.Name = "OutputSheet" Or Ws.Name = "Sheet1" Then

        End If
    Next i

    Wb.SaveAs 

Else

    'Workbooks("A380 Master.xlsm").Sheets("OutPutSheet").Range("A1").Select
End If

End Sub