如何在匹配范围的文件夹中创建PDF文件

时间:2019-02-01 16:32:49

标签: excel vba

我正在尝试ExportAsFixedFormat特定文件夹中的所有excel文件(如果它们从我的B3范围匹配到lr)。 (范围是文件名减去扩展名)

这是我到目前为止所拥有的。当前,它尝试打开每个文件(不是全部是excel文件,有些不是autocad)并将.xlsx导出为pdf。它会以PDF格式显示当前页面(我不想要),并以PDF格式列出我列表中的.xlsx文件之一。

我不想只打印该文件夹中的所有excel文件。

感谢您的任何反馈。

Sub ExcelPrint()
Dim myFile As String, myFolder As String
Dim LoginName As String, destFolder As String
myFolder = Range("B1").Value
lr = Cells(Rows.Count, "B").End(xlUp).Row
LoginName = UCase(GetUserID)
destFolder = "C:\Users\" & LoginName & "\Desktop\_PDF\_Temp\"

If Len(Dir("C:\Users\" & LoginName & "\Desktop\_PDF\", vbDirectory)) = 0 Then
    MkDir "C:\Users\" & LoginName & "\Desktop\_PDF\"
End If

If Len(Dir("C:\Users\" & LoginName & "\Desktop\_PDF\_Temp\", vbDirectory)) = 0 Then
    MkDir "C:\Users\" & LoginName & "\Desktop\_PDF\_Temp\"
End If

For i = 3 To lr
    myFile = Cells(i, 2).Value & ".xlsx"
    On Error Resume Next
    Workbooks.Open _
            FileName:=myFolder & myFile, _
            ReadOnly:=True

    With ActiveSheet.PageSetup 'How to print only the .xlsx files from 3 to lr?
        .Orientation = xlLandscape
        .FitToPagesTall = 1
        .FitToPagesWide = 1
    End With

        ActiveSheet.ExportAsFixedFormat _
        Type:=xlTypePDF, _
        FileName:=destFolder & ActiveSheet.Name, _ 'How to save as Workbook name?
        IgnorePrintAreas:=False, _
        From:=1, _
        To:=1, _
        OpenAfterPublish:=False
        ActiveSheet.Close
Next i
End Sub

1 个答案:

答案 0 :(得分:0)

您的问题出在On Error Resume Next上。举例来说,假设它失败的第一次迭代。 On Error Resume Next将允许它继续运行而无需打开任何内容,您当前的工作簿为ActiveWorkbook,然后它将执行您列出的其余操作。另外,ActiveSheet不支持.Close。我想您正在寻找ActiveWorkbook.Close

我建议使用FileSystemObject并检查文件扩展名,但是,如果这不是一个选择,请使用合法的错误处理程序来尝试打开不存在的工作簿。

On Error Goto eHandler
For i = 3 to lr
    'Do Stuff
nextLine:
Next i
Exit Sub
eHandler:
If Err.Number = 1004 Then 'Use whatever error number it raises without `On Error Resume Next`
    Resume nextLine
End If
Msgbox Err.Number & vbcrlf & Err.Description
End Sub

此外,您可以添加一个变量来存储打开的工作簿,因此您不必使用ActiveSheet。从技术上讲,这还将解决您在注释行'How to save as Workbook name?中的第二个问题,因为您可以只使用带有工作簿存储变量的前缀.Name