2016-10-13 114 views
2

我想重命名一個文件夾如何有很多子文件夾和主文件夾內的文件 重命名是基於許多值和它的需要是動態的(我正在更改電影&字幕名稱)vba - 循環和重命名文件和文件夾

我的問題是 - 當文件夾名稱回答名稱的值更改宏無法找到一個路徑來繼續循環(如果文件夾不回答價值,那麼宏工作正常)

這裏我到目前爲止:

Sub moviestest() 
    Call VideoLibrary("C:\movies") 
End Sub 

Private Sub VideoLibrary(path As String) 
    Dim fso As New Scripting.FileSystemObject 
    Dim fld As folder, f As folder, fl As File 

    Set fso = CreateObject("Scripting.FileSystemObject") 
    Set fld = fso.GetFolder(path) 

    For Each Q In Range("Qname") 
     For Each fl In fld.Files 

      myMovie = fl.Name 
      extension = InStrRev(myMovie, ".") 
      myNewMovie = _ 
       Replace(_ 
        Replace(_ 
         Replace(_ 
          Replace(_ 
           Left(myMovie, extension - 1), _ 
          ".", " "), _ 
         "-", " "), _ 
        "_", " "), _ 
       Q, "") & _ 
       Mid(myMovie, extension) 
      fso.MoveFile myMovie, myNewMovie 
     Next 
    Next 


    For Each f In fld.SubFolders 
      Call VideoLibrary(f.path) 
    Next 
End Sub 

文件名正在尋找這樣的事情:

  • The.something.2013.1080p.BluRay.x264.YIFY.mkv The.something.2013.1080p.BluRay.x264.YIFY.sub Zero.something。 2016.1080p.BluRay.x264- [YTS.AG] .AVI(以及更多 名稱)

QName的範圍是somethig這樣的: (在Excel命名範圍)

bdrip 
x264 
veto 
heb 
BRRip 
XviD 
AC3 
EVO 
blaa 
1080p 
BluRay 
YIFY 

這是我第一次在這個論壇上發問。我希望我儘可能地明確我的問題 任何幫助將不勝感激

+0

你在用'Q'做什麼? - 你不會在你的內循環中使用它。 –

+0

@TimWilliams它隱藏在4或5個嵌套'Replace'語句中。 – Tim

+0

@Tim - 謝謝:沒有滾動到... –

回答

0

最好的辦法是使一個函數,將返回新的名稱。這也將使代碼更易於閱讀,修改和調試。

Sub moviestest() 
    Call VideoLibrary("C:\movies") 
End Sub 

Private Sub VideoLibrary(path As String) 
    Dim fso As New Scripting.FileSystemObject 
    Dim fld As folder, f As folder, fl As File 

    Set fso = CreateObject("Scripting.FileSystemObject") 
    Set fld = fso.GetFolder(path) 

    For Each fl In fld.Files 
     fso.MoveFile fl.path, fl.ParentFolder & "\" & getNewMoiveName(fl.Name) 
    Next 

    For Each f In fld.SubFolders 
     Call VideoLibrary(f.path) 
    Next 
End Sub 

Function getNewMoiveName(myMovie As String) As String 
    Dim Q 
    Dim loc As Long 
    Dim extension As String 
    loc = InStrRev(myMovie, ".") 
    extension = Right(myMovie, Len(myMovie) - loc) 
    myMovie = Left(myMovie, loc - 1) 
    myMovie = Replace(myMovie, ".", " ") 
    myMovie = Replace(myMovie, "-", " ") 

    For Each Q In Range("Qname") 
     myMovie = Replace(myMovie, Q, "") 
    Next 

    getNewMoiveName = myMovie & "." & extension 
End Function 
+0

Thomas Inzina謝謝!代碼馬上更加漂亮和整齊 – whylikethis

+0

Thomas Inzina謝謝你!代碼現在更加漂亮整齊 但是,我仍然收到錯誤53「找不到文件」 並調試此行(它發生在功能區中創建新名稱後) For Each fl In fld。文件 fso.MoveFile fl.Name,getNewMoiveName(fl.Name) Next 文件夾名稱是否也發生變化?也許這就是爲什麼它不能找到文件 – whylikethis

+0

現在爲一些rision的代碼刪除擴展名.. – whylikethis