2021年8月7日 星期六

VBA:刪除檔案 KILL v.s filesystemobject

基本上先來 MSDN 一下

MSDN看無不打緊

沒關係,基本上概念就是路徑+指令;也就是跟KILL這個指令說,請刪除位於某資料夾的XX檔案。

但如果很多同質性檔案要刪除怎辦?

例如:刪除c:\test 資料夾內的純文字檔案;可以用kill c:\test\*.txt

或是類似檔案名稱:

例如:刪除c:\test 資料夾內的1開頭純文字檔案;可以用kill c:\test\1*.txt

p.s *是萬國碼

如果實在要刪除的檔案太多,真誠建議組合filesystemobject.SubFolders 做使用,針對資料夾內子資料們做大檢查,然後刪除特定條件檔案即可。

p.s特定條件指自己設定的檔案名稱條件。

引用MSDN例子修改一下做應用

Sub ShowFolderList(folderspec,sub_name)

    Dim fs, f, f1, s, sf

    Set fs = CreateObject("Scripting.FileSystemObject")

    Set f = fs.GetFolder(folderspec)

    Set sf = f.SubFolders

    For Each f1 In sf

                 ShowFolderList f1,sub_name

       Next

        Set s = f.Files

            For Each f1 In s

                If InStr(f1.Name, sub_name) > 0 Then

                        fs.DeleteFile folderspec & "\" & f1.Name

                End If

        Next

End Sub

做一個按鈕,插入以下vba

Private Sub CommandButton1_Click()

  Call ShowFolderList("D:\新增資料夾", ".txt") 

'小編是用D:\新增資料夾做測試歐,這裡要自己設定,跟設定副檔名

End Sub

Sub ShowFolderList(folderspec, sub_name) '路徑與副檔名設定

    Dim fs, f, f1, s, sf

    Set fs = CreateObject("Scripting.FileSystemObject")

    Set f = fs.GetFolder(folderspec)

    Set sf = f.SubFolders

    For Each f1 In sf

                 ShowFolderList f1, sub_name

    Next

    Set s = f.Files

            For Each f1 In s

                If InStr(f1.Name, sub_name) > 0 Then

                        fs.DeleteFile folderspec & "\" & f1.Name

                 End If    

    Next

End Sub

有機會再發發FileSystemObject的應用好了



沒有留言:

張貼留言

指數變化(2024.05.17)

指數變化(2024.05.17) 上周焦點:         5/9當周焦點                          事實:fed與非農就業,引起投資市場對降息有加速,但肯定的是,fed說不加息了。                        美國密西根大學信心指數 ...