运行时错误 – 无法访问文件

我有以下VBA脚本保存工作簿,这工作正常。

但是,如果commandbutton1再次点击它正确的调出选项框

'你想replace文件吗?是,不,取消。

yes选项可以正常工作,但No和Cancel选项会显示错误框 – RunTime error 1004: Cannot access 'file'

任何人都可以指出我正确的方向来解决问题。 代码如下:

 Private Sub CommandButton1_Click() Dim Path As String Dim FileName1 As String Dim FileName2 As String Path = "C:\temp\Saved Invoices\" FileName1 = Range("R12") FileName2 = Range("S12") ActiveWorkbook.SaveAs Filename:=Path & FileName1 & "-" & FileName2 & ".xlsm", FileFormat:=52 End Sub 

如果你仍然喜欢你的用户的提示,你可以使用MsgBox。 下面是一个简单的是/否提示。

此代码使用Microsoft脚本运行时。 如果您还没有引用此引用,请转到Visual Basic编辑器(ALT-F11),然后在工具下拉菜单中select“引用…”勾选“Microsoft Scripting Runtime”旁边的checkbox,然后单击确定button。

下面的代码设置FileSystemObject,设置你提供的path和文件名,并检查文件是否已经存在。 如果没有find该文件,它将像以前一样SaveAs。 如果它已经find该文件,它会给用户一个MsgBox询问他们是否想要覆盖文件。 如果他们点击是,它会像以前一样执行SaveAs。 点击NO将不会执行任何操作。

 Private Sub CommandButton1_Click() Dim fso As FileSystemObject Dim Path As String Dim FileName1 As String Dim FileName2 As String Dim FilePath As String Set fso = CreateObject("Scripting.FileSystemObject") Path = "C:\temp\Saved Invoices\" FileName1 = Range("R12") FileName2 = Range("S12") FilePath = Path & FileName1 & "-" & FileName2 & ".xlsm" If fso.FileExists(FilePath) Then If MsgBox("Your file already exists in this location. Do you want to replace it?", vbYesNo) = vbYes Then ActiveWorkbook.SaveAs FilePath, 52 End If Else ActiveWorkbook.SaveAs FilePath, 52 End If End Sub 

由Thinkingcap提供的Application.DisplayAlerts也是一个很好的方法。 您首先收到错误的原因是因为您的脚本在点击YES时知道该做什么,但没有NO或CANCEL方向。 当提示启用时,NO是SaveAs的默认选项。 在Application.DisplayAlerts = False中包装脚本不仅会禁用提示,而且会将默认值更改为YES,因此每次都会在没有用户input的情况下replace文件。

所有你需要做的是将代码包装在Application.DisplayAlerts中

 Application.DisplayAlerts = False Dim Path As String Dim FileName1 As String Dim FileName2 As String Path = "C:\temp\Saved Invoices\" FileName1 = Range("R12") FileName2 = Range("S12") ActiveWorkbook.SaveAs Filename:=Path & FileName1 & "-" & FileName2 & ".xlsm", FileFormat:=52 Application.DisplayAlerts = True