现在正在运作。由于某些文件名由中文字符或一些空文件组成(由我尝试制作此文件并且未从vbs中正确关闭文件而创建),因此出现了一些错误,但我添加了日志,因此我可以看到处理的最后一个文件。我不知道如何让它只显示产生错误的文件,但它也是这样的。
Const msoFileDialogOpen = 4
Const ForReading = 1
Const ForWriting = 2
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objWord = CreateObject("Word.Application")
Set WshShell = CreateObject("WScript.Shell")
Set myLog = objFSO.OpenTextFile("C:\my.log", ForWriting, True)
strInitialPath = WshShell.ExpandEnvironmentStrings("E:\Filme\")
objWord.ChangeFileOpenDirectory(strInitialPath)
Sub Modify(f)
myLog.WriteLine f
txt = f.OpenAsTextStream.ReadAll
txt = Replace(txt, "ã", "a")
txt = Replace(txt, "â", "a")
f.OpenAsTextStream(2).Write txt
End Sub
Sub Recurse(fldr)
For Each sf In fldr.SubFolders
Recurse sf
Next
For Each f In fldr.Files
ext = LCase(objFSO.GetExtensionName(f.Name))
If ext = "srt" Or ext = "sub" Or ext = "txt" Then Modify f
REM WScript.Echo f
Next
End Sub
With objWord.FileDialog(msoFileDialogOpen)
.Title = "Select the folder to process"
If .Show = -1 Then
For Each item in .SelectedItems
Recurse objFSO.GetFolder(item)
Next
Else
End If
myLog.Close
End With
答案 0 :(得分:0)
如果我理解正确,您想要选择一个文件夹,然后打开该文件夹及其所有子文件夹中包含.srt
,.sub
或.txt
扩展名的所有文件。为此,您需要一个递归过程来遍历文件夹子树。在第二个过程中放置修改文件的代码是个好主意。使代码更清晰。
Set objFSO = CreateObject("Scripting.FileSystemObject")
Sub Modify(f)
'code for modifying the files' content goes here
End Sub
Sub Recurse(fldr)
For Each sf In fldr.SubFolders
Recurse sf
Next
For Each f In fldr.Files
ext = LCase(objFSO.GetExtensionName(f.Name))
If ext = "srt" Or ext = "sub" Or ext = "txt" Then Modify f
Next
End Sub
...
With objWord.FileDialog(msoFileDialogOpen)
...
For Each item in .SelectedItems
Recurse objFSO.GetFolder(item)
Loop
End With
...
您应该对代码进行一些进一步的优化:
FileSystemObject
实例是浪费资源。在脚本开头创建一次全局实例,并在脚本的任何位置使用该实例。ReadAll
阅读该文件,然后在整个文本上运行Replace
。ReDim Preserve
绑定表现不佳,因为ReDim
重新创建变量,Preserve
将旧数组实例中的所有值复制到新数组。< / LI>
OpenAsTextStream
方法。这样的事情应该有效:
Sub Modify(f)
txt = f.OpenAsTextStream.ReadAll
txt = Replace(txt, "ã", "a")
txt = Replace(txt, "â", "a")
...
f.OpenAsTextStream(2).Write txt
End Sub