File System Object
FSO - Check If a file exists, if exists then delete the file.
Dim fso As Scripting.FileSystemObject
Sub test()
Application.ScreenUpdating = False
Set fso = New Scripting.FileSystemObject
Dim flname As String
flname = "D:\Excel Practice\Test.txt"
If Not fso.FileExists(flname) Then
Exit Sub
Else
'flname.Delete--------Incorrect
fso.DeleteFile (flname) '---Correct
MsgBox "file deleted", vbInformation
End If
Application.ScreenUpdating = True
End Sub
'---------------------------------------------
Sub DeleteAllFilesFromAFolder()
Dim fso As Object
Dim fd As Object
Dim fl As Object
Dim str_Path As String
str_Path = "D:\New Folder\"
Set fso = CreateObject("Scripting.FileSystemObject")
Set fd = fso.getfolder(str_Path)
For Each fl In fd.Files
fl.Delete
Next fl
End Sub
Delete a file without using Loop
If obj_fso.fileexists(ThisWorkbook.Path & "\" & "xyz.xlsx") Then
obj_fso.Deletefile ThisWorkbook.Path & "\" & "xyz.xlsx", True
End If
Move a file from one folder to another without using Loop
If obj_fso.fileexists(ThisWorkbook.Path & "\" & "xyz.xlsx") Then
obj_fso.movefile ThisWorkbook.Path & "\" & "xyz.xlsx", ThisWorkbook.Path & "\" & "Target folder name" & "\"
End If
Copy a file from one folder to another without using Loop
If obj_fso.fileexists(ThisWorkbook.Path & "\" & "xyz.xlsx") Then
obj_fso.copyfile ThisWorkbook.Path & "\" & "xyz.xlsx", ThisWorkbook.Path & "\" & "Target folder name" & "\"
End If
Rename a file without using Loop
If obj_fso.fileexists(ThisWorkbook.Path & "\" & "xyz.xlsx") Then
obj_fso.getfile(ThisWorkbook.Path & "\" & "xyz.xlsx").Name = "abc.xlsx"
End If
Comments
Post a Comment