2017-08-25 113 views
8

我試圖使用VBA編碼 - 我很新 - 從PDF(它不是圖像)獲取一系列.doc文檔,也就是我我試圖循環播放各種PDF文件並將它們保存爲MS Word格式。我的經驗是,這個詞很好地閱讀了我所擁有的PDF文檔:word大部分時間保持了PDF文件的正確佈局。我不確定這是否是解決這個問題的正確選擇,我想要一個替代建議 - 如果可能的話使用R。將PDF文件循環並將其轉換爲文檔

總之,這裏是我發現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」宏。在彈出框中出現以下錯誤:「Sub or Function not defined」。我該如何解決?此外,由於某些原因,我現在還不清楚,我得到了一個與功能ChangeFileOpenDirectory有關的錯誤,這個錯誤似乎也沒有定義。

更新27/08/2017

我改變了代碼如下:

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 

現在我沒有得到一個彈出框任何錯誤消息,但沒有輸出在我的工作目錄中。它現在可能有什麼問題?

+2

(一)是'迪爾( 「C:\用戶\ ... T」 和 「* .PDF」) '暗示你的目錄以't'結尾?如果是這樣,那應該說'Dir(「C:\ Users \ ... t」和「* .pdf」)'(或者,爲了節省一點處理時間,'Dir(「C:\ Users \ ...牛逼\ *。PDF格式「)')。 (b)我不知道爲什麼'ChangeFileOpenDirectory'會失敗,除了你指定的目錄不存在或者你沒有權限訪問它。 – YowE3K

+1

只需刪除兩個'ChangeFileOpenDirectory ...'行。使用完整路徑打開並保存文件 – jsotola

+0

我嘗試了一些建議。我會更新這個問題。 –

回答

2

,可以閱讀PDF文件,寫Word文檔(這是XML)的任何語言都可以做到這一點,但你喜歡的轉換(這詞確實在PDF打開時),將需要使用API​​的應用程序本身。 VBA是您輕鬆的選擇。

您發佈的代碼片段(以及我的示例)使用早期綁定和枚舉常量,這意味着我們需要對Word對象庫的引用。對於您在Word文檔中編寫的任何代碼,已經設置好了,因此創建一個新的Word文檔並將代碼添加到標準模塊中。 (如果您需要更多詳細信息,請參閱此Excel tutorial,我們流程的步驟相同)。

您可以從VB編輯器(使用「運行」按鈕)或普通文檔窗口(單擊Word 2010-2016中「查看」選項卡上的「宏」按鈕)運行宏。如果您想重新使用宏而無需再次設置代碼,請將文檔保存爲DOCM文件。

現在的代碼!

正如註釋中所述,如果您只是確保文件夾路徑以反斜槓「\」字符結尾,則第二個片段纔有效。解決這個問題後,它仍然不是很好的代碼,但是這會讓你啓動並運行。

我假設你想要多花一點時間,並有一個很好的書面版本,你可以在以後重新調整或擴展。爲了簡單起見,我們將使用兩個過程:主轉換和禁止PDF轉換警告對話框(由註冊表控制)的過程。

主要步驟:

Sub ConvertPDFsToWord2() 
    Dim path As String 
    'Manually edit path in the next line before running 
    path = "C:\users\username\work_dir_example\" 

    Dim file As String 
    Dim doc As Word.Document 
    Dim regValPDF As Integer 
    Dim originalAlertLevel As WdAlertLevel 

'Generate string for getting all PDFs with Dir command 
    'Check for terminal \ 
    If Right(path, 1) <> "\" Then path = path & "\" 
    'Append file type with wildcard 
    file = path & "*.pdf" 

    'Get path for first PDF (blank string if no PDFs exist) 
    file = Dir(file) 

    originalAlertLevel = Application.DisplayAlerts 
    Application.DisplayAlerts = wdAlertsNone 

    If file <> "" Then regValPDF = TogglePDFWarning(1) 

    Do While file <> "" 
     'Open method will automatically convert PDF for editing 
     Set doc = Documents.Open(path & file, False) 

     'Save and close document 
     doc.SaveAs2 path & Replace(file, ".pdf", ".docx"), _ 
        fileformat:=wdFormatDocumentDefault 
     doc.Close False 

     'Get path for next PDF (blank string if no PDFs remain) 
     file = Dir 
    Loop 

CleanUp: 
    On Error Resume Next 'Ignore errors during cleanup 
    doc.Close False 
    'Restore registry value, if necessary 
    If regValPDF <> 1 Then TogglePDFWarning regValPDF 
    Application.DisplayAlerts = originalAlertLevel 

End Sub 

註冊表設置功能:

Private Function TogglePDFWarning(newVal As Integer) As Integer 
'This function reads and writes the registry value that controls 
'the dialog displayed when Word opens (and converts) a PDF file 
    Dim wShell As Object 
    Dim regKey As String 
    Dim regVal As Variant 

    'setup shell object and string for key 
    Set wShell = CreateObject("WScript.Shell") 
    regKey = "HKCU\SOFTWARE\Microsoft\Office\" & _ 
      Application.Version & "\Word\Options\" 

    'Get existing registry value, if any 
    On Error Resume Next 'Ignore error if reg value does not exist 
    regVal = wShell.RegRead(regKey & "DisableConvertPdfWarning") 
    On Error GoTo 0  'Break on errors after this point 

    wShell.regwrite regKey & "DisableConvertPdfWarning", newVal, "REG_DWORD" 

    'Return original setting/registry value (0 if omitted) 
    If Err.Number <> 0 Or regVal = 0 Then 
     TogglePDFWarning = 0 
    Else 
     TogglePDFWarning = 1 
    End If 

End Function 
+0

我有'TogglePDFWarning'功能的問題。我是否將其插入另一個模塊?我需要一個圖書館來正確地調用它嗎? –

+0

我已經解決了這個問題。我需要輸入私人功能作爲一個過程。既然你已經設法得到答案 - 而且我不能在適當的時候檢查你是否正確 - 有沒有辦法爲你「捐贈」額外的25分? –

+0

收到了賞金。感謝您的支持! – AjimOthy

1

正如其他人所說,問題似乎主要在於路徑&文件名。以下是您發佈的第二個版本,並進行了一些更改。

不幸的是,彈出一條警告消息並將DisplayAlerts設置爲false不會抑制它。但是,如果您在第一次彈出時單擊「不再顯示此消息」複選框,那麼它將不會繼續爲每個文件彈出。

Sub convertToWord() 

    Dim MyObj  As Object 
    Dim MySource As Object 
    Dim file  As String 
    Dim path  As String 

    path = "C:\Users\username\work_dir_example\" 
    file = Dir(path & "*.pdf") 

    Do While (file <> "") 
     Documents.Open FileName:=path & file 
     With ActiveDocument 
      .SaveAs2 FileName:=Replace(path & file, ".pdf", ".docx"), _ 
           FileFormat:=wdFormatXMLDocument 
      .Close 
     End With 
     file = Dir 
    Loop 

End Sub