Home » excel » excel – Delete open book

excel – Delete open book

Posted by: admin May 14, 2020 Leave a comment


I want to create a new work book add a list into it and then save this book. If it is exist I need to delete previous variant and then save current. Here is my code:

Private Sub GenerateReport_Click()

    Dim wb As Workbook
    Dim FilePath As String

    FilePath = ThisWorkbook.Path + "\CommonReport.xls"
    Set wb = Workbooks.Add
    ActiveCell.FormulaR1C1 = "a1"
    ActiveCell.FormulaR1C1 = "b1b"
    ActiveCell.FormulaR1C1 = "3"
    ActiveCell.FormulaR1C1 = "4"
    ActiveCell.FormulaR1C1 = "5"
    ActiveCell.FormulaR1C1 = "6"
    ActiveCell.FormulaR1C1 = "7"
    wb.ActiveSheet.ListObjects.Add(xlSrcRange, wb.ActiveSheet.Range("$A$1:$G$1"), , xlYes).Name = "Ñïèñîê1"

    Application.DisplayAlerts = False

        If Dir(FilePath) = vbNullString Then
           wb.SaveAs Filename:=FilePath
        SetAttr FilePath, vbNormal
           Kill FilePath
        End If

End Sub

Is it possible to delete book when it is open. How can I handle an error when I want to delete opened book?

How to&Answers:

I think it is not necessary to delete the workbook, just overwrite it. If it is opened, close it first. Example:

Option Explicit

Private Const NEW_BOOK_NAME As String = "CommonReport"

Public Sub Test()
    Dim newWorkbook As Workbook

    Set newWorkbook = Workbooks.Add
    With newWorkbook.ActiveSheet
        [a1] = "a1"
        [b1] = "b1"
        [c1] = "c1"
    End With

    Dim filePath As String
    filePath = ThisWorkbook.Path & "\" & NEW_BOOK_NAME

    On Error Resume Next

    On Error GoTo 0
    Application.DisplayAlerts = False
    newWorkbook.SaveAs filePath
End Sub


You cannot delete an open workbook.

Check to see if a file with the same name is open using something like this: http://www.exceltip.com/st/Determine_if_a_workbook_is_already_open_using_VBA_in_Microsoft_Excel/472.html

If such a file is open, check to see if it has the same path as the file you want to delete by comparing FilePath with the open workbook (eg Workbooks("CommonReport.xls").FullName) and if so, close it by using the close command:

Workbooks("CommonReport.xls").Close SaveChanges:=False


Olle Sjögren Idea sohould work.

But it could be easier to simply use the worksheet.usedrange.clear method to empty the existing worksheet. Then you could insert your new Data.
This should be a lot faster than the delete-approach.