2016-11-07 222 views
-1

所以我想製作一個.vbs文件,它可以編輯文件夾中的所有.txt文件。這是我使用的代碼,文件夾是C:\test folder需要幫助處理子文件夾

Const ForReading = 1 
Const ForWriting = 2 

newline = "" 
line = 1 

Set objFSO = CreateObject("Scripting.FileSystemObject") 

objStartFolder = "C:\test folder\" 

Dim lineCount : lineCount = 0 
Dim firstContent : firstContent = "" 

Set objFolder = objFSO.GetFolder(objStartFolder) 
Set colFiles = objFolder.Files 

For Each objFile in colFiles 
    If LCase(objFSO.GetExtensionName(objFile)) = "txt" Then 
     lineCount = 0 
     firstContent = "" 

     FileName = objStartFolder & objFile.Name 

     Set objStream = objFSO.OpenTextFile(FileName, ForReading) 
     Do Until objStream.AtEndOfStream 
      lineCount = lineCount + 1 
      firstContent = firstContent & objStream.ReadLine & vbCrLf 
      If lineCount = line Then 
       firstContent = firstContent & newline & vbCrLf 
      End If 
     Loop 
     Set objStream = objFSO.OpenTextFile(FileName, ForWriting) 
     objStream.WriteLine firstContent 
     objStream.Close 
    End If 
Next 

它的工作原理。並將所有文本文件更改爲我想讓他們說的內容,但是當我在C:\test folder中創建了一個名爲SFC:\test folder\SF)的文件夾時,SF中的所有文本文件都不會更改。我如何使它與子文件夾一起使用?

回答

0

遞歸是一個調用自己的函數。它用於走樹。

ProcessFolder DirName 

Sub ProcessFolder(FolderPath) 
' On Error Resume Next 
    Set fldr = fso.GetFolder(FolderPath) 

    Set Fls = fldr.files 

    For Each thing in Fls 
     msgbox Thing.Name & " " & Thing.path 
    Next 

    Set fldrs = fldr.subfolders 
    For Each thing in fldrs 
     ProcessFolder thing.path 
    Next 

End Sub 
+0

我是否用這個替換我的.vbs或者添加它? –

+0

也沒有,你從中學習。我爲什麼要寫你的​​代碼? – 2016-11-07 20:56:23

+0

第5行的錯誤。「Object required:objFSO」。我是否將Set objFSO = CreateObject(「Scripting.FileSystemObject」)? –