【发布时间】:2018-02-04 00:31:15
【问题描述】:
我正在尝试使用 VBA 编码(我很陌生)从 PDF(不是图像)中获取一系列 .doc 文档,也就是说,我正在尝试遍历各种 PDF 文件并保存它们MS Word 格式。我的经验是 word 可以很好地阅读我拥有的 PDF 文档:word 大部分时间都保持 PDF 文件的正确布局。我不确定这是否是解决此问题的正确选择,我要求提供替代建议 - 如果可能,请使用 R。
不管怎样,这是我找到的代码here:
Sub convertToWord()
Dim MyObj As Object, MySource As Object, file As Variant
file = Dir("C:\Users\username\work_dir_example" & "*.pdf") 'pdf path
Do While (file <> "")
ChangeFileOpenDirectory "C:\Users\username\work_dir_example"
Documents.Open Filename:=file, ConfirmConversions:=False, ReadOnly:= _
False, AddToRecentFiles:=False, PasswordDocument:="", PasswordTemplate:= _
"", Revert:=False, WritePasswordDocument:="", WritePasswordTemplate:="", _
Format:=wdOpenFormatAuto, XMLTransform:=""
ChangeFileOpenDirectory "C:\Users\username\work_dir_example"
ActiveDocument.SaveAs2 Filename:=Replace(file, ".pdf", ".docx"), FileFormat:=wdFormatXMLDocument _
, LockComments:=False, Password:="", AddToRecentFiles:=True, _
WritePassword:="", ReadOnlyRecommended:=False, EmbedTrueTypeFonts:=False, _
SaveNativePictureFormat:=False, SaveFormsData:=False, SaveAsAOCELetter:= _
False, CompatibilityMode:=15
ActiveDocument.Close
file = Dir
Loop
End Sub
将代码粘贴到开发者窗口后,我将代码保存在模块中 -> 关闭开发者窗口 -> 点击“宏”按钮 -> 执行“convertToWord”宏。我在弹出框中收到以下错误:“未定义子或功能”。我该如何解决?另外,以前,由于某些我现在不清楚的原因,我收到了与函数ChangeFileOpenDirectory 相关的错误,该函数似乎也没有定义。
2017 年 8 月 27 日更新
我把代码改成如下:
Sub convertToWord()
Dim MyObj As Object, MySource As Object, file As Variant
file = Dir("C:\Users\username\work_dir_example" & "*.pdf")
ChDir "C:\Users\username\work_dir_example"
Do While (file <> "")
Documents.Open Filename:=file, ConfirmConversions:=False, ReadOnly:= _
False, AddToRecentFiles:=False, PasswordDocument:="", PasswordTemplate:= _
"", Revert:=False, WritePasswordDocument:="", WritePasswordTemplate:="", _
Format:=wdOpenFormatAuto, XMLTransform:=""
ActiveDocument.SaveAs2 Filename:=Replace(file, ".pdf", ".docx"), FileFormat:=wdFormatXMLDocument _
, LockComments:=False, Password:="", AddToRecentFiles:=True, _
WritePassword:="", ReadOnlyRecommended:=False, EmbedTrueTypeFonts:=False, _
SaveNativePictureFormat:=False, SaveFormsData:=False, SaveAsAOCELetter:= _
False, CompatibilityMode:=15
ActiveDocument.Close
file = Dir
Loop
End Sub
现在我在弹出框中没有收到任何错误消息,但我的工作目录中没有输出。现在可能有什么问题?
【问题讨论】:
-
(a)
Dir("C:\Users\...t" & "*.pdf")是否暗示您的目录以t结尾?如果是这样,那应该是Dir("C:\Users\...t\" & "*.pdf")(或者,为了节省一点处理时间,Dir("C:\Users\...t\*.pdf"))。 (b) 我不确定为什么ChangeFileOpenDirectory会失败,除了您指定的目录可能不存在或您无权访问它。 -
只需删除两个
ChangeFileOpenDirectory ...行。使用完整路径打开和保存文件 -
我尝试了一些建议。我会更新问题。
-
另外,为了避免误会,我把目录路径改成了
C:\Users\username\work_dir_example。 -
我知道您请求了 VBA,但正如您所提到的,您可以使用其他选择:如果您可以访问 *nix 机器和 LibreOffice,您可以尝试一下:stackoverflow.com/questions/26358281/…