2014-10-09 70 views
0

我需要重命名多個文件夾中的文件。如果文件名是「1」或「主」或「主」,我想重新命名爲不同。如果我想要重命名所有文件,但現在顯示的類型不匹配錯誤,代碼將正常工作。如何調試運行時錯誤13類型不匹配?

Sub rename() 

    Dim fso, fsoFolder, fsoFile, strPath, strName, fsoSubFolder, i, a 

    i = 1 

    Set fso = CreateObject("Scripting.FileSystemObject") 

    Set fsoFolder = fso.GetFolder("C:\Users\anu\Desktop\Black") 

    For Each fsoSubFolder In fsoFolder.Subfolders 

     For Each fsoFile In fsoSubFolder.Files 

      strName = fsoFile.Name 
      strPath = Left(fsoFile.Path, Len(fsoFile.Path) - Len(strName)) 
      a = fsoFile.Name 
      If a = "main" Or "Main" Or "MAIN" Or "1" Then 
       fso.CopyFile strPath & strName, strPath & fsoSubFolder.Name & "_" & "Main" & ".jpg" 
       fso.DeleteFile strPath & strName 
      Else 
       fso.CopyFile strPath & strName, strPath & fsoSubFolder.Name & "_" & i & ".jpg" 
       fso.DeleteFile strPath & strName 
       i = i + 1 
      End If 

     Next 
     i = 1 
    Next 

End Sub 

如何在沒有發現錯誤的情況下檢查該狀況?

+0

你能告訴我它打破? – NMK 2014-10-09 17:49:52

+0

它沒有運行。它只是顯示運行時錯誤13.如果我從If If Else中刪除部分,即不檢查該條件,它工作正常。 – 2014-10-09 17:53:25

+3

這個 - >'如果a =「main」或者「Main」或者「MAIN」或者「1」Then''不會對每個都測試'a'。 – crashmstr 2014-10-09 17:53:46

回答

1

只是改變了這一點,它對我來說很好。請嘗試:

Sub rename() 

    Dim fso, fsoFolder, fsoFile, strPath, strName, fsoSubFolder, i, a 

    i = 1 

    Set fso = CreateObject("Scripting.FileSystemObject") 

    Set fsoFolder = fso.GetFolder("C:\Users\anu\Desktop\Black") 

    For Each fsoSubFolder In fsoFolder.Subfolders 

     For Each fsoFile In fsoSubFolder.Files 

      strName = fsoFile.Name 
      strPath = Left(fsoFile.Path, Len(fsoFile.Path) - Len(strName)) 
      a = fsoFile.Name 
      If ((a = "main") Or (a = "Main") Or (a = "MAIN") Or (a = "1")) Then '-----Line changed----- 
       fso.CopyFile strPath & strName, strPath & fsoSubFolder.Name & "_" & "Main" & ".jpg" 
       fso.DeleteFile strPath & strName 
      Else 
       fso.CopyFile strPath & strName, strPath & fsoSubFolder.Name & "_" & i & ".jpg" 
       fso.DeleteFile strPath & strName 
       i = i + 1 
      End If 

     Next 
     i = 1 
    Next 

End Sub 
0

此行很可能會出現問題。 (不帶任何附加信息)

Dim fso, fsoFolder, fsoFile, strPath, strName, fsoSubFolder, i, a 

正如你應該輸入所有的變量,特別是需要在代碼Set任何物體的習慣得到了最佳實踐。

像這樣的東西,而不是(你可能需要確認,因爲我不知道到底應該是什麼類型)

Dim fso as 'insert your object here 
Dim fsoFolder as 'insert your object here 
Dim fsoFile as 'insert your object here 
Dim strPath as String 
Dim strName as String 
Dim fsoSubFolder as 'insert your object here 
Dim i as Integer 
Dim a as String 
相關問題