批量转换 Word 文档格式 (doc <-> docx)
该宏用于将批量的 Word 文档格式从 doc 转换为 docx 或从 docx 转换为 doc。
首先,宏会弹出一个文件选择对话框,允许用户选择要转换的 Word 文档文件。用户可以选择多个文件。
然后,对于每个被选择的文件,宏会打开该文档,将其保存为新格式,并关闭该文档。如果文件格式不是 doc 或 docx,则会弹出一个提示框告诉用户无法识别该文件格式。
最后,宏会弹出一个提示框告诉用户转换完成。
注意,该宏只能在 Microsoft Word 中运行,不能在其他程序中运行。
Sub ConvertDocToDocx()
Dim dialog As FileDialog
Set dialog = Application.FileDialog(msoFileDialogFilePicker)
' 设置对话框属性及筛选
With dialog
.Title = '选择要转换的 Word 文档'
.Filters.Clear
.Filters.Add 'Word 文档 (*.doc;*.docx)', '*.doc;*.docx', 1
.AllowMultiSelect = True ' 可以多选'
.InitialView = msoFileDialogViewDetails
If .Show <> -1 Then
Exit Sub ' 用户按下取消按钮'
End If
End With
' 转换 Word 文档格式
Dim file As Variant
For Each file In dialog.SelectedItems
If Right(file, 4) = '.doc' Then
' 打开文档
Documents.Open fileName:=file
' 设置文档格式为 docx
ActiveDocument.SaveAs2 fileName:=Replace(file, '.doc', '.docx'), _
FileFormat:=wdFormatXMLDocument
' 关闭文档
ActiveDocument.Close SaveChanges:=False
ElseIf Right(file, 5) = '.docx' Then
' 打开文档
Documents.Open fileName:=file
' 设置文档格式为 doc
ActiveDocument.SaveAs2 fileName:=Replace(file, '.docx', '.doc'), _
FileFormat:=wdFormatDocument
' 关闭文档
ActiveDocument.Close SaveChanges:=False
Else
' 仅能转换后缀名为 'doc' 和 'docx' 的 Word 文档
MsgBox '无法识别的文件格式!'
End If
Next
' 弹窗提示完成
MsgBox '文档格式已转换完成!'
End Sub
原文地址: https://www.cveoy.top/t/topic/m06o 著作权归作者所有。请勿转载和采集!