2017-10-09 31 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文件夹,然后设置为一个字符串什么。谢谢你的帮助!