首页 > 解决方案 > 当目录中存在同名文件时,“对象_workbook的方法保存失败”

问题描述

如果再次保存文件,我正在尝试将文件保存在目录中,出现 excel 消息。我是 vba 错误处理的新手,卡在这个项目代码中

在此处输入图像描述

如果按下“否”,则会给出主题错误。这是我的代码:

  Set OutApp = CreateObject("Outlook.Application")
    Set OutMail = OutApp.CreateItem(0)
    Dim x As String
    With Destwb

    On Error Resume Next

        .SaveAs TempFileName & FileExtStr, FileFormat:=FileFormatNum


       If Sheet1.Cells(2, 6) = "All" Then
Exit Sub
End If
'Destwb.Sheets("REC_INT").Range("A1").Select

If Not Sheet1.Cells(2, 6) = "All" Then
x = Sheet1.Range("L3")

        With OutMail
            .To = Sheet1.Cells(x, 3).Value
            .CC = Sheet1.Cells(x, 4).Value
            .BCC = ""
            .Subject = "Service Record"
            .Body = Sheet1.Cells(8, 7).Value
            .Attachments.Add Destwb.FullName
            'You can add other files also like this
            '.Attachments.Add ("C:\test.txt")
            '.Send   'or use
            .Display
        End With
        On Error GoTo 0
        .Close savechanges:=False
    End If
    End With

    'Delete the file you have send
    'Kill TempFilePath & TempFileName & FileExtStr

    Set OutMail = Nothing
    Set OutApp = Nothing

    With Application
        .ScreenUpdating = True
        .EnableEvents = True
    End With
    Application.Calculation = xlCalculationAutomatic
End Sub

为什么没有跳过错误?

标签: excelvbasave

解决方案


问题:

  • On Error Resume Next在保存文件的行之后

这将继续代码而不保存文件。

解决方案:

Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)

Dim x As String

On Error Resume Next


With Destwb
       .Save True
       '.SaveAs TempFileName & FileExtStr, FileFormat:=FileFormatNum

If Sheet1.Cells(2, 6) = "All" Then
    Exit Sub

Else

    x = Sheet1.Range("L3")

        With OutMail
            .To = Sheet1.Cells(x, 3).Value
            .CC = Sheet1.Cells(x, 4).Value
            .BCC = ""
            .Subject = "Service Record"
            .Body = Sheet1.Cells(8, 7).Value
            .Attachments.Add Destwb.FullName
            'You can add other files also like this
            '.Attachments.Add ("C:\test.txt")
            '.Send   'or use
            .Display
        End With

On Error GoTo 0

        .Close savechanges:=False

End If
End With

    'Delete the file you have send
    'Kill TempFilePath & TempFileName & FileExtStr

    Set OutMail = Nothing
    Set OutApp = Nothing

    With Application
        .ScreenUpdating = True
        .EnableEvents = True
        .Calculation = xlCalculationAutomatic
    End With

End Sub

推荐阅读