寫一段VBS,想把某個檔案夾下面所有子檔案夾的檔案加后綴全部移出便于整理,但是總是莫名說檔案已存在
代碼如下
Function FilesTree(sPath)
'遍歷一個檔案夾下的所有檔案夾檔案夾
Set oFso = CreateObject("Scripting.FileSystemObject")
Set oFolder = oFso.GetFolder(sPath)
Set oSubFolders = oFolder.SubFolders
sMoveToPath = oFolder.ParentFolder.Path
sAddName = oFolder.Name
sAddName = "-[" & sAddName & "]"
if oSubFolders.count>0 then
For Each oSubFolder In oSubFolders
FilesTree(oSubFolder)'遞回
if oSubFolder.size<50 then
oSubFolder.delete
end if
Next
end if
Set oFiles = oFolder.Files
For Each oFile In oFiles
sNewName = ofile.name
sNewName = mid(sNewName,1,instrrev(sNewName,".")-1) & sAddName & mid(sNewName,instrrev(sNewName,"."))
ofile.name = sNewName
'就是這里有問題
'msgbox sMoveToPath& "\n"& ofile.path'從msgbox看不存在重名
oFso.movefile ofile.path,sMoveToPath
'用這個移動也不行
'ofile.Move(sMoveToPath)
Next
Set oFolder = Nothing
Set oFso = Nothing
End Function
set oSubFolders = CreateObject("Scripting.FileSystemObject").GetFolder(".").SubFolders
For Each oSubFolder In oSubFolders
FilesTree(oSubFolder.path)'遞回
Next
Set oSubFolders = Nothing
由于檔案數目較多(5000+),大小較大(1GB左右),為了保證速度可能不能用Copy+Delete
求助,拜謝
uj5u.com熱心網友回復:
另外百度過也沒有找到合適的解決辦法,告訴我用什么關鍵詞搜索也行uj5u.com熱心網友回復:
你的 sMoveToPath變數值不正確吧!如果sMoveToPath代表一個“目錄”,它的值在 oFso.movefile ofile.path,sMoveToPath 這兒, 必須以“\”結尾。
而我看你前面對其賦值的只有這處: sMoveToPath = oFolder.ParentFolder.Path
應該改為: sMoveToPath = oFolder.ParentFolder.Path & "\"
uj5u.com熱心網友回復:
非常感謝,已經解決!
另外可以麻煩順便講一下洗掉已經被移空的檔案夾那部分代碼哪里有缺陷嗎?空檔案夾套一個空檔案夾的時候會報錯“oSubFolder不存在”,報錯位置是13行
uj5u.com熱心網友回復:
我這兒, 按我在2樓說的修正后,VB6和VBS中都是“執行正常”。
uj5u.com熱心網友回復:
你用 oSubFolder.Size < 50來判斷“空檔案夾”,可靠嗎?
會不會有“隱藏的、0位元組(或幾位元組)的檔案”呢?
你最好在“計算機”中,直接查看“檔案夾屬性”確認一下操作失敗的目錄。
uj5u.com熱心網友回復:
已經試驗出 VBS代碼“出錯”了。但相同的情況下,VB6正常執行,VBS會出錯。
這個錯誤感覺很奇怪:
FilesTree (oSubFolder.path) 去“遞回”處理、洗掉了一個空檔案夾,
而在這個“遞回”呼叫回傳之后,在VBS中,oSubFolder這個“物件”竟然會失效!
這個難道是VBS的Bug嗎???

開始的試驗,“最內層”是有檔案的,回傳后 oSubFolder仍然“正常”,
但為什么“最內層”是個空檔案夾時,回傳后oSubFolder會“失效”呢!!! 這根本不合常理的啊!
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/45299.html
標籤:VB基礎類
上一篇:跪求大佬!!幫忙,vb編程連接到資料庫,adapter.fill為什么會出錯???
下一篇:VBA中出現錯誤script engine for the specified language can not be created
