如果现有文件已打开,则将文件另存为宏会导致错误

时间:2017-01-26 12:29:12

标签: vba excel-vba excel

我创建了用于将excel工作簿保存在文件夹中的vba代码。但是我得到运行时错误1004,当已经存在的文件打开并且还创建了其他相同的excel工作簿。

Private Sub CommandButton14_Click()

    Dim folderpath As String

    Dim Fname As String

    Dim file As String


    Fname = MyForm.SCC.Value

    folderpath = ActiveWorkbook.Path

    Workbooks.Open Filename:= _

        ("" & folderpath & "\" & Fname & "- Q3 2016" & ".xlsx")

        ' for adding explaination sheet from PAM sheet into destination sheet

    ' Section E: please update the name of excel workbook if the name of this excel workbook changed

    Windows("OEM PAM Sizer 2016 - v1.xlsm").Activate

    Sheets("Automation Content definition").Visible = True

    Sheets("Automation Content definition").Select

    Sheets("Automation Content definition").Copy After:=Workbooks( _

        "" & Fname & "- Q3 2016" & ".xlsx").Sheets(1)

    ActiveWorkbook.Worksheets("sheet1").Activate

    Range("a1").Select

    file = "" & folderpath & "\" & Fname & "- Q3 2016" & ".xlsx"

    FileExist (file)


    Windows("OEM PAM Sizer 2016 - v1.xlsm").Close savechanges:=False

End sub

1 个答案:

答案 0 :(得分:2)

如果文件已打开 - 请将其关闭。 微软提供了一些技巧来了解文件是否已打开:

Function IsFileOpen(filename As String)
    Dim filenum As Integer, errnum As Integer

    On Error Resume Next   ' Turn error checking off.
    filenum = FreeFile()   ' Get a free file number.
    ' Attempt to open the file and lock it.
    Open filename For Input Lock Read As #filenum
    Close filenum          ' Close the file.
    errnum = Err           ' Save the error number that occurred.
    On Error GoTo 0        ' Turn error checking back on.

    ' Check to see which error occurred.
    Select Case errnum

        ' No error occurred.
        ' File is NOT already open by another user.
        Case 0
         IsFileOpen = False

        ' Error number for "Permission Denied."
        ' File is already opened by another user.
        Case 70
            IsFileOpen = True

        ' Another error occurred.
        Case Else
            Error errnum
    End Select

End Function

https://support.microsoft.com/en-us/help/291295/macro-code-to-check-whether-a-file-is-already-open

另一种选择是以不同方式命名文件。