【发布时间】:2020-12-08 12:44:37
【问题描述】:
早上好,
我想使用 Excel 宏将 PDF 文件转换为 Word 一(从 PDF 到 DOCX)。
到目前为止,我从这个视频中了解到了这个过程:
https://www.youtube.com/watch?v=Op25fUfvIl0
还有这个链接:
https://www.pk-anexcelexpert.com/pdf-to-word-converter-macro-in-excel-vba/
但问题是,该示例基于某些单元格,包括固定文件目录:
pdf_path = sh.Range("E4").Value
word_path = sh.Range("E5").Value
我希望目录始终与我正在处理的活动工作簿相同。
在这种情况下,我尝试了以下代码:
Sub Wort_To_PDF()
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Application.DisplayStatusBar = True
Dim pdf_path As String
Dim word_path As String
pdf_path = ThisWorkbook.Path & "\"
word_path = ThisWorkbook.Path & "\"
Dim fso As New FileSystemObject
Dim fo As Folder
Dim f As File
Set fo = fso.GetFolder(pdf_path)
Dim wa As Object
Dim doc As Object
Set wa = CreateObject("word.application")
wa.Visible = True
Dim file_Count As Integer
For Each f In fo.Files
Application.StatusBar = "Converting - " & file_Count + 1 & "/" & fo.Files.Count
Set doc = wa.Documents.Open(f.Path)
doc.SaveAs2 (word_path & "\" & Replace(f.Name, ".pdf", ".docx"))
doc.Close False
file_Count = file_Count + 1
Next
wa.Quit
MsgBox "All PDF files have been converted in to word", vbInformation
Application.StatusBar = ""
End Sub
我收到错误“类型不匹配”指向以下行:
Set fo = fso.GetFolder(pdf_path)
我发现了一些关于在 VBA 中使用活动工作簿目录的提示
How to get the path of current worksheet in VBA?
并尝试将其放入我的代码中:
pdf_path = Application.ActiveWorkbook.Path
word_path = Application.ActiveWorkbook.FullName
但错误是完全一样的。
谁能帮帮我?我想将 PDF 文件转换为 docx,放在存储我的活动工作簿的同一目录中。
更新:
当我将Dim fo as Folder 更改为Dim fo As Object 或Dim fo as Scripting.Folder 时,我收到另一个错误,通知我该文件已损坏。调试器显示以下行:
Set doc = wa.Documents.Open(f.Path)
我认为,这个问题可能出在我的 Excel 文档的某个地方,该文档已经打开并使用过了。一般来说,代码只执行第一张而不是全部。
【问题讨论】:
-
请尝试
pdf_path = ThisWorkbook.Path而不是pdf_path = ThisWorkbook.Path & "\" -
还是同一个伙伴。同一个地方出现同样的错误:(
-
请尝试声明
Dim fo As Object。 -
这是一个提示。我更改了它,现在又出现另一个错误:Set doc = wa.Documents.Open(f.Path) - 文件似乎已损坏
-
Word 无法简单地打开 pdf 文件。它必须转换它。通常它能够做到这一点,有时 pdf 和转换后的 docx 之间存在很大差异,但它会做到这一点。究竟如何显示错误?然后,尝试手动打开它。你能做到吗?