用户按“否”或“取消”时如何处理错误

时间:2018-10-09 22:02:01

标签: excel vba

我正在研究将一些数据导出到新工作簿的宏。一切正常。

但是,如果导出的文件已经存在于目录中,程序会询问您是否要用新文件替换它。

如果按“是”,则一切正常,但是如果按“否”或“取消”程序将抛出错误:

运行时错误“ 1004”: 对象“ _Workbook”的方法SaveAs失败

我想我应该对这一行有所了解:

wkb.SaveAs Filename:=relativePath

但是我不知道该怎么做。

Sub ExportData()

    'create and save new workbook
    Dim wkb As Workbook
    Set wkb = Workbooks.Add
    relativePath = ThisWorkbook.Path & "\" & "WorkbookName.xlsx"
    wkb.SaveAs Filename:=relativePath
End Sub

1 个答案:

答案 0 :(得分:0)

我终于能够以这种方式解决问题。

Dim wkb As Workbook
Set wkb = Workbooks.Add
relativePath = ThisWorkbook.Path & "\" & "WorkbookName.xlsx"

If Not Dir(relativePath, vbDirectory) = vbNullString Then
If MsgBox("File already exists, do you want to continue and replace it?", vbYesNo, "Wanna replace existing file?") = vbNo Then
ActiveWorkbook.Close savechanges:=False
wkbcurrent.Activate
Columns("U:U").Select
Selection.Delete Shift:=xlToLeft
Exit Sub
End If
Else
End If

Application.DisplayAlerts = False
wkb.SaveAs Filename:=relativePath