将txt转换为doc后删除源文件

时间:2016-07-30 14:31:42

标签: vbscript

以下VBScript将txt文件转换为doc文件。

这完美无缺!但它还保留源文件夹“FolderWithTxtFiles”中的源txt文件。我希望在将源txt文件转换为doc后将其删除。

VBScript代码:

strFolder = "D:\FolderWithTxtFiles"

If Right(strFolder, 1) <> "\" Then
    strStartFolder = strFolder & "\"
Else
    strStartFolder = strFolder

End If

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objWord = CreateObject("Word.Application")

objWord.Visible = False

Const wdFormatDocument = 0

For Each objFile In objFSO.GetFolder(strFolder).Files
    If LCase(objFSO.GetExtensionName(objFile.Path)) = "txt" Then
        ' See: http://msdn.microsoft.com/en-us/library/aa220317(office.11).aspx
        objWord.Documents.Open objFile.Path, False, True, False
        If Right(strFolder, 1) = "\" Then
            strNewName = Left(strFolder, Len(strFolder) - 1)
        Else
            strNewName = strFolder
        End If

        strRootFolder = Left(strNewName, InStrRev(strNewName, "\"))
        strNewName = Left(strNewName, InStrRev(strNewName, "\")) & "FolderWithConvertedDocFiles"

        If objFSO.FolderExists(strNewName) = False Then objFSO.CreateFolder(strNewName)

        strNewName = strNewName & "\" & Left(objFile.Name, Len(objFile.Name) - 3) & "doc"

        ' See: http://msdn.microsoft.com/en-us/library/aa220734(office.11).aspx
        objWord.DisplayAlerts = False
        objWord.ActiveDocument.SaveAs strNewName, wdFormatDocument, , , False
        objWord.DisplayAlerts = True
        objWord.ActiveDocument.Close False
    End If
Next

For Each objSubFolder In objFSO.GetFolder(strFolder).SubFolders
    RecurseSubFolders objSubFolder
Next

objWord.Quit

Sub RecurseSubFolders(objFolder)
    For Each objFile In objFolder.Files
        If LCase(objFSO.GetExtensionName(objFile.Path)) = "txt" Then
            ' See: http://msdn.microsoft.com/en-us/library/aa220317(office.11).aspx
            objWord.Documents.Open objFile.Path, False, True, False

            If Right(objFolder.Path, 1) = "\" Then
                strFolderName = Left(objFolder.Path, Len(objFolder.Path) - 1)
            Else
                strFolderName = objFolder.Path
            End If

            strNewName = strRootFolder & "FolderWithConvertedDocFiles" & "\" & Replace(LCase(strFolderName), LCase(strStartFolder), "")

            If objFSO.FolderExists(strNewName) = False Then objFSO.CreateFolder(strNewName)

            strNewName = strNewName & "\" & Left(objFile.Name, Len(objFile.Name) - 3) & "doc"
            objWord.DisplayAlerts = False
            objWord.ActiveDocument.SaveAs strNewName, wdFormatDocument, , , False
            objWord.DisplayAlerts = True
            objWord.ActiveDocument.Close False
        End If
    Next

    For Each objSubFolder In objFolder.SubFolders
        RecurseSubFolders objSubFolder
    Next
End Sub

0 个答案:

没有答案
相关问题