2017-10-09 59 views
0

我發現在這個網站上的類似實例的幾個問題,但沒有解決方案爲我工作。得到腳本工作一次,然後停止運行時錯誤'1004'

我的目標是允許用戶單擊電子表格中的按鈕,並a)在本地保存整個工作簿或b)僅將本書的一部分導出爲PDF。

「另存爲」代碼工作得很好,導出到PDF代碼工作一次後停止工作。這裏是代碼:

Option Explicit 

Sub Button1_Click() 

Dim workbook_file_name As String 
Dim datasheet As String 
Dim saveworkbook As Double 
Dim PDFdata As Object 

saveworkbook = MsgBox("Would you like to save a local copy of entire workbook? Click No to only store as PDF", vbYesNo, "Save File As") 

If saveworkbook = vbYes Then 

    workbook_file_name = "Sherman and Reilly Brake Test" 

     With Application.FileDialog(msoFileDialogSaveAs) 
      .InitialFileName = CreateObject("WScript.Shell").Specialfolders("My Documents") & "\" & workbook_file_name 
      .FilterIndex = 2 

       If .Show Then .Execute 
     End With 

    GoTo noPDF 

Else 

    GoTo exportsheet 

End If 

exportsheet: 

datasheet = "C:\Brake_Test_Data.pdf" 

If Dir(datasheet) <> vbNullString Then 
    Kill datasheet 
End If 

Set PDFdata = Sheets("Data Sheet").Range("A93:I138") 

With PDFdata 

    .ExportAsFixedFormat Type:=xlTypePDF, Filename:=datasheet, _ 
    Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=True 


End With 

noPDF: 

End Sub 

我已經厭倦了將PDF數據標註爲變體。這個問題似乎是在這裏:

.ExportAsFixedFormat Type:=xlTypePDF, Filename:=datasheet, _ 
Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=True 

我得到運行時錯誤1004,並且說該文件沒有保存該文檔可能打開消息框或錯誤保存時出現。

+0

不是VBA I/O方面的專家,但這不是因爲該文件已經存在 – Casey

+0

@Casey我想到了這一點,這就是爲什麼我添加了目錄搜索。即使如此,當腳本正常工作時,我已經離開並刪除了第一個pdf文件,因此不再存在該文件。 – ThirstyVoltage

+0

我把你的代碼從'saveworkbook = ...'下移到'exportsheet:',然後運行它。我沒有多次運行它(只要我記得在每次執行後關閉Acrobat Reader)。 – YowE3K

回答

0

@ YowE3K,我想通了

Option Explicit 

Dim workbook_file_name As String 
Dim datasheet As String 
Dim saveworkbook As Double 
Dim PDFdata As Range 
Dim mydocuments As Object 
Dim saveto As String 

Sub Button1_Click() 


saveworkbook = MsgBox("Would you like to save a local copy of entire workbook? Click No to only store as PDF", vbYesNo, "Save File As") 

If saveworkbook = vbYes Then 

    workbook_file_name = "*****" 

     With Application.FileDialog(msoFileDialogSaveAs) 
      .InitialFileName = CreateObject("WScript.Shell").specialfolders("My Documents") & "\" & workbook_file_name 
      .FilterIndex = 2 

       If .Show Then .Execute 
     End With 

    GoTo noPDF 

Else 

    GoTo exportsheet 

End If 

exportsheet: 

Set mydocuments = CreateObject("WScript.Shell").specialfolders 
saveto = mydocuments("mydocuments") 
Set PDFdata = Sheets("Data Sheet").Range("A93:I138") 

With PDFdata 

    .ExportAsFixedFormat Type:=xlTypePDF, Filename:=saveto & "\*****.pdf", _ 
    Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=True 


End With 

noPDF: 


Sheets("Data Sheet").Protect Password:="*****" 

End Sub 

我所做的就是讓代碼找到mydocs文件夾,然後設置爲一個字符串什麼。謝謝你的幫助!