您可以使用 R 将 .docm 文件转换为 .docx 吗? [关闭]
Posted
技术标签:
【中文标题】您可以使用 R 将 .docm 文件转换为 .docx 吗? [关闭]【英文标题】:Can you convert .docm files to .docx using R? [closed] 【发布时间】:2022-01-19 16:31:45 【问题描述】:我有大约 100 个 .docm 文件需要转换为 .docx。我这样做是因为我正在使用官员库从 .docx 文件中导入表(这不适用于 .docm)。谢谢!
【问题讨论】:
【参考方案1】:基本上,您正在寻找的似乎是“如何将一堆文档从启用宏转换为不使用 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 从 R 运行它或使用this example 使用 RDComclient 来跟进。
【讨论】:
以上是关于您可以使用 R 将 .docm 文件转换为 .docx 吗? [关闭]的主要内容,如果未能解决你的问题,请参考以下文章