vba clear file code example

Example 1: vba clear a worksheet

'VBA methods to quickly clear a sheet.

'Remove values 
'but not formatting:
Sheet1.UsedRange.ClearContents

'Remove formatting
'but not values:
Sheet1.UsedRange.ClearFormats

'Remove everything:
Sheet1.UsedRange.Clear

'Remove everything potentially faster:
Sheet1.UsedRange.Delete

'Remove everything, fastest:
With Application
	.Calculation = xlManual
    .ScreenUpdating = False
    
    Sheet1.UsedRange.Delete
    
    .ScreenUpdating = True
    .Calculation = xlAutomatic
End With

Example 2: vba delete file

' Needs to add "Microsoft Scripting Runtime" reference to your file
Function FileExists(ByVal FileToTest As String) As Boolean
   FileExists = (Dir(FileToTest) <> "")
End Function

Sub DeleteFile(ByVal FileToDelete As String)
   If FileExists(FileToDelete) Then 'See above          
      ' First remove readonly attribute, if set
      SetAttr FileToDelete, vbNormal          
      ' Then delete the file
      Kill FileToDelete
   End If
End Sub

Tags:

Vb Example