您可以使用 R 将 .docm 文件转换为 .docx 吗?

Can you convert .docm files to .docx using R?

我有大约 100 个 .docm 文件需要转换为 .docx。我这样做是因为我正在使用 officer 库从 .docx 文件导入表格(这不适用于 .docm)。谢谢!

基本上您正在寻找的似乎是“我如何使用 R 将一堆文档从启用宏转换为不启用宏”。

我会按原样说:可能不能不冒险进入 RDComClient 包。我会说创建一个单独的 word 文件并使用快速 VBA 脚本来完成工作(例如下面的 convert_files 函数)会更容易。

Function GetFolderFiles(folder As String) As Variant
    ' Extract files from folder
    Dim oFSO As Object
    Dim oFolder As Object
    Dim oFile As Object
    Dim i As Long
    Set oFSO = CreateObject("Scripting.FileSystemObject")
    Set oFolder = oFSO.GetFolder(folder)
    Dim result() As Variant
    ReDim result(0 To oFolder.files.Count - 1)
    i = 0
    For Each oFile In oFolder.files
        If InStr(1, oFile.Name, "docm") Then
            result(i) = oFile.Path
            i = i + 1
        End If
    Next oFile
    ReDim Preserve result(0 To i - 1)
    GetFolderFiles = result
End Function
Sub convert_files(Optional ByVal folder As String = "path-to-folder")
    ' Iterate through docm files in a folder and save them as docx
    Dim files As Variant
    files = GetFolderFiles(folder)
    Dim i As Variant
    Dim wordDoc As Word.Document
    On Error GoTo safeExit
    For Each i In files
        ' Open Document (invisibly for speed)
        Set wordDoc = Word.Documents.Open(i, Visible:=False, ReadOnly:=True)
        ' Save document replacing docm with docx
        wordDoc.SaveAs2 Replace(i, "docm", "docx"), FileFormat:=wdFormatDocumentDefault   ' replace docm with docx
        ' Close the document
        wordDoc.Close wdDoNotSaveChanges
    Next i
    Exit Sub
safeExit:
    ' In case we stop early due to an error or esc press we want to ensure no invisible documents hang around.
    On Error Resume Next
    wordDoc.Close
    On Error GoTo 0
    MsgBox "Error happened did not finish after file '" & i & "'.", vbExclamation
End Sub

一旦您在保存的文档中定义了它,您就可以通过 cmd 或使用 RDComclient 使用 this example.

从 R 中跟进 运行 它