delete and clear the data by vba

roger@
StarLounger
Posts: 84
Joined: 23 Apr 2019, 19:00

delete and clear the data by vba

Post by roger@ »

vba code to delete 1.xls file
and delete all the data of 1..csv file
both file are loacted in desktop
vba code is placed in seperate file

User avatar
HansV
Administrator
Posts: 78545
Joined: 16 Jan 2010, 00:14
Status: Microsoft MVP
Location: Wageningen, The Netherlands

Re: delete and clear the data by vba

Post by HansV »

Please study the code carefully.

Code: Select all

Sub DeleteAndClear()
    Dim strDesktop As String
    Dim wbk As Workbook

    Application.ScreenUpdating = False

    ' Path of the user's desktop
    strDesktop = CreateObject("WScript.Shell").SpecialFolders("Desktop") & "\"

    On Error Resume Next
    ' Try to delete 1.xls
    Kill strDesktop & "1.xls"
    If Err Then
        MsgBox "Couldn't find or delete 1.xls", vbExclamation
    End If
    On Error GoTo ErrHandler

    ' Open 1..csv
    Set wbk = Workbooks.Open(strDesktop & "1..csv")
    ' Clear the entire sheet
    wbk.Worksheets(1).Cells.Clear
    ' Save the file without displaying a prompt
    Application.DisplayAlerts = False
    wbk.Close SaveChanges:=True
    
ExitHandler:
    Application.DisplayAlerts = True
    Application.ScreenUpdating = True
    Exit Sub

ErrHandler:
    MsgBox Err.Description, vbExclamation
    Resume ExitHandler
End Sub
Best wishes,
Hans

roger@
StarLounger
Posts: 84
Joined: 23 Apr 2019, 19:00

Re: delete and clear the data by vba

Post by roger@ »

Thnx HansV Sir for giving ur precious time and great support to this post