【问题标题】:How to convert multiple word docs (incl subfolders) from .doc to .docx?如何将多个单词文档(包括子文件夹)从 .doc 转换为 .docx?
【发布时间】:2022-01-26 07:09:37
【问题描述】:

有没有办法编辑下面的 VBA 代码,使其还可以转换子文件夹中的所有 .doc 文档并删除原始 .doc?

我有很多,我对 VBA 代码不太熟悉。任何帮助将不胜感激!

Sub ConvertBatchToDOCX()
    Dim sSourcePath As String
    Dim sTargetPath As String
    Dim sDocName As String
    Dim docCurDoc As Document
    Dim sNewDocName As String

    ' Looking in this path
    sSourcePath = "H:\Vanhuspalvelut\Kotihoito\Tammelan_kotihoito\TURVALLISUUS\Pelastussuunnitelmaan_tuleva\TURVALLISUUS_SUUNNITELMA_2015"
    sTargetPath = "H:\Vanhuspalvelut\Kotihoito\Tammelan_kotihoito\TURVALLISUUS\Pelastussuunnitelmaan_tuleva\TURVALLISUUS_SUUNNITELMA_2015"

   ' Look for first DOC file
    sDocName = Dir(sSourcePath & "*.doc")
    Do While sDocName <> ""
        ' Repeat as long as there are source files
        
        'Only work on files where right-most characters are ".doc"
        If Right(sDocName, 4) = ".doc" Then
            ' Open file
            Set docCurDoc = Documents.Open(FileName:=sSourcePath & sDocName)

            sNewDocName = Replace(sDocName, ".doc", ".docx")

            With docCurDoc
                .SaveAs FileName:=sTargetPath & sNewDocName, _
                  FileFormat:=wdFormatDocumentDefault
                .Close SaveChanges:=wdDoNotSaveChanges
            End With
        End If
        ' Get next source file name
        sDocName = Dir
    Loop
    MsgBox "Finished"
End Sub

【问题讨论】:

标签: vba ms-word


【解决方案1】:

请使用下一个解决方案:

  1. 在模块顶部添加下一个 API 函数(在声明区域中):
Private Declare PtrSafe Sub Sleep Lib "kernel32.dll" (ByVal dwMilliseconds As LongPtr)
  1. 使用下一个改编的 Sub:
Sub ConvertBatchToDOCX()
    Dim mainFolderPath As String, sDoc, arrDocs, boolProblematic As Boolean
    Dim docCurDoc As Document, sNewDocName As String, strMsg As String

    ' Looking in this path
   mainFolderPath =  "H:\Vanhuspalvelut\Kotihoito\Tammelan_kotihoito\TURVALLISUUS\Pelastussuunnitelmaan_tuleva\TURVALLISUUS_SUUNNITELMA_2015\"
   
   strMsg = "Problematic files: " & vbCrLf
   
   arrDocs = getAllDocs(mainFolderPath & "*.doc")
   If arrDocs(0) = "" Then MsgBox "No appropriate documents have been found...": Exit Sub
        
   For Each sDoc In arrDocs
        sNewDocName = Left(sDoc, InStrRev(sDoc, ".") - 1) & ".docx": ' Stop
        boolProblematic = False
        On Error Resume Next
         Set docCurDoc = Documents.Open(FileName:=sDoc)
         If Err.Number = 5174 Then
            Err.Clear: boolProblematic = True
            strMsg = strMsg & sDoc & vbCrLf
         End If
         If Not boolProblematic Then
            docCurDoc.SaveAs FileName:=sNewDocName, FileFormat:=wdFormatDocumentDefault
            docCurDoc.Close False
            Kill sDoc
            Sleep 1000
        End If
   Next
   If strMsg <> "Problematic files: " & vbCrLf Then MsgBox strMsg
   
  MsgBox "Finished"
End Sub
  1. 该功能也进行了调整,以处理扩展名为“.doc”的非文档的情况:
Private Function getAllDocs(strFold As String, Optional strExt As String = "*.*") As Variant
      Dim arrD, arrExt, arrFin, sDoc, i As Long
      arrD = Filter(Split(CreateObject("wscript.shell").Exec("cmd /c dir """ & strFold & strExt & """ /b /s").StdOut.ReadAll, vbCrLf), "\")
      ReDim arrFin(UBound(arrD))
      For Each sDoc In arrD
            arrExt = Split(sDoc, ".")
            If LCase(arrExt(UBound(arrExt))) = "doc" Then
                arrFin(i) = sDoc: i = i + 1
            End If
      Next
      If i > 0 Then
        ReDim Preserve arrFin(i - 1)
      Else
        ReDim arrFin(0)
      End If
      getAllDocs = arrFin
End Function

【讨论】:

  • 当我在包含一个子文件夹的测试文件夹上运行代码时,它似乎可以工作。但是,当我尝试在需要的地方运行它时,我收到运行时错误5174。知道为什么吗?
  • @BaselE 请提及错误描述和引发错误的代码行。没有人可以记住错误代码,除了一些常见的错误代码......但是上面的代码从所有子文件夹返回一个数组,直到最后一级。这可能是权限问题...
  • 我收到此错误消息 run-time error 5174´` 并突出显示以下行 Set docCurDoc = Documents.Open(FileName:=sDoc)
  • @BaselE 请在有问题的行之前插入下一个测试代码行:Debug.Print sDoc: Stop。当停在这条线上时,它会在Immediate Window 中返回什么?这不是一个有效的文件全名吗?如果正确,请按F5 并运行代码,直到它处理下一个文档。如果引发错误,请查看讨论中的文档有什么问题...
  • 我得到一个运行时错误窗口,它说找不到文件和一个文件名及其路径。
【解决方案2】:

也许这能让你走上正轨? (未经测试

Sub saveDOCsAsDOCXs()
  ChDir "C:\myFolderName\"
  Dim fIn As String, fOut As String, doc As Document
  fIn = Dir("*.doc")   'list first `doc` files in current folder (includes `docx`)
  Do
    If Right(fIn, 4) = ".doc" Then 'only process `doc` files
      Debug.Print "Opening " & fIn
      Set doc = Documents.Open(fIn) 'open the `doc`
      fOut = fIn & "x" 'output filename
      If Dir(fOut) <> "" Then
        Debug.Print fOut & " already exists."  'could instead delete existing like `Kill fOut`
      Else
        doc.SaveAs fOut, wdFormatXMLDocument 'save as `docx`
        Debug.Print "Saved " & fOut
      End If
      doc.Close 'close the file
    End If
    fIn = Dir() 'get next `doc` file
  Loop While fIn <> ""
End Sub

文档:OpenSaveAs2Dir

【讨论】:

  • 我认为 OP 也要求提供子文件夹?
  • 是的,OP 中发布的代码确实有效,但仅在特定文件夹中有效。就我而言,我有大量的 .doc 文档要转换为 docx,它们位于许多子文件夹中:(
猜你喜欢
  • 1970-01-01
  • 2012-05-11
  • 2011-06-14
  • 2015-09-13
  • 2023-03-25
  • 1970-01-01
  • 1970-01-01
  • 2011-10-03
  • 1970-01-01
相关资源
最近更新 更多