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

时间:2014-07-18 14:22:19

标签: excel excel-vba vba

我有以下VBA脚本保存工作簿,这很好用。

但是,如果再次单击commandbutton1,它会正确显示选项框

  

'你想要替换文件' - 是,否,取消。

“是”选项正常,但“否”和“取消”选项会显示错误框 - 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

2 个答案:

答案 0 :(得分:2)

您需要做的就是将代码包装在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

答案 1 :(得分:0)

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

此代码使用Microsoft Scripting Runtime。如果您还没有引用此参考,请转到Visual Basic编辑器(ALT-F11),然后在工具下拉列表中选择"参考..."勾选" Microsoft Scripting Runtime"旁边的复选框。然后单击“确定”按钮。

下面的代码设置FileSystemObject,设置您提供的路径和文件名,并检查该文件是否已存在。如果它没有找到该文件,它将像以前一样保存。如果它已经找到该文件,它将向用户提供一个MsgBox,询问他们是否要覆盖该文件。如果他们点击YES,它会像以前一样进行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也是一个很好的方法。您首先收到错误的原因是因为您的脚本在单击“是”但没有“否”或“取消”的指示时知道该怎么做。启用提示时,NO是SaveAs的选定默认值。在Application.DisplayAlerts = False中包装脚本不仅会禁用提示,而且会将默认值更改为YES,因此每次都会在没有用户输入的情况下替换该文件。

相关问题