在word VBA的模块里写入以下代码,可实现选中文件夹的所有doc格式的word自动转换成docx格式,再转换成PDF,转换成功后doc文件自动删除。
Private Sub ConvertPDF_Click()
Application.ScreenUpdating = False
Dim sDocPath As String
Dim MyDoc As Object
Dim sNewPath As String
Dim MyDocx As Object
Dim FileCount As Integer
Dim i As Integer
Dim sDocName As String
Dim sArr(100) As String
Dim sDocxName As String
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "选择需要PDF转换的文件夹"
If .Show = -1 Then
sDocPath = .SelectedItems(1)
Else
Exit Sub
End If
End With
sDocName = Dir(sDocPath & "\*.doc")
Do While sDocName <> ""
If (Right(sDocName, 3) = "doc") Then
sArr(FileCount) = sDocName
If sDocName = "" Then
Exit Do
End If
FileCount = FileCount + 1
End If
sDocName = Dir
Loop
For i = 0 To FileCount - 1
Set MyDoc = Documents.Open(sDocPath & "\" & sArr(i), , , , , , , , , , , msoFalse)
sNewPath = VBA.Strings.Replace(sDocPath & "\" & sArr(i), ".doc", ".docx")
If Dir(sNewPath, vbDirectory) = "" Then
MyDoc.SaveAs2 filename:=sNewPath, FileFormat:=wdFormatDocumentDefault 'MyDoc会变为doc
End If
sDocxName = Dir(sNewPath)
Set MyDocx = Documents.Open(sDocPath & "\" & sDocxName, , , , , , , , , , , msoFalse)
sNewPath = VBA.Strings.Replace(sDocPath & "\" & sDocxName, ".docx", ".pdf")
MyDocx.SaveAs2 filename:=sNewPath, FileFormat:=wdFormatPDF 'MyDocx仍为docx
If Right(MyDoc, 4) <> "docx" Then
MyDoc.Close SaveChanges:=False
MyDocx.Close SaveChanges:=False
Else
MyDoc.Close SaveChanges:=False
End If
Kill (VBA.Strings.Replace(sDocPath & "\" & sArr(i), ".doc", ".docx"))
Set MyDoc = Nothing
Set MyDocx = Nothing
Next
Application.ScreenUpdating = True
End Sub