Excel将工作表从关闭的文件打印为PDF

时间:2019-01-23 09:58:34

标签: excel vba pdf

我有一个包含项目信息的主Excel文件。 在与包含图纸的主文件相同的文件夹中,总会有另一个名为“作业导出”的excel文件-每个图纸都位于单独的图纸上。图纸将从图纸2开始到图纸n-1结束(当前代码还将打印图纸1和图纸n)。

我发现并修改了VBA代码,该代码将把每张图纸中的这些图纸打印到单独的PDF文件中,并在每张图纸的单元格C5中命名。 但这意味着我必须打开带有图纸的excel文件,然后将代码复制到该工作簿中才能打印PDF。我想将此代码添加到我的主Excel中,以便它在后台打开“作业导出” excel,并将工程图打印为单独的PDF。

下一步是根据单元格B7中的客户名称以及B11及以后的部件号将这些PDF保存到文件夹中(在这种情况下,保存的PDF也将以部件号命名)。

使用VBA可以吗?

编辑:

我一直在改变打印的PDF的保存位置。我尝试仅在文件夹“ C:\ suvaline”中进行硬编码,但不会将其保存在该位置。如我先前所写,保存文件夹应为:C:\ suvaline \“客户名称” \“零件号”,但它甚至不能与硬编码的文件夹一起使用,因此我什至没有尝试获取客户名称从Excel。有什么我想念的吗?

Sub ExportToPDFFromClosed()

Dim ws As Worksheet
Dim wbA As Workbook
Dim strPath
Dim strFile
Dim wb2 As Workbook

i = 11
j = 2

sPath = "C:\suvaline"
Application.ScreenUpdating = False
Set wbA = ActiveWorkbook
strPath = wbA.path
strPath = strPath & "\"
Set wbA = Workbooks.Open(strPath & "Job export pic3")
Set wb2 = ThisWorkbook

For Each ws In Worksheets
ws.Select
nm = wb2.Sheets("Prep+BOM").Cells(i, j).Value _

strFile = nm & ".pdf"
strPathFile = "C:\suvaline" & strFile


ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
filename:=strPathFile & ".pdf", _
Quality:=xlQualityStandard, IncludeDocProperties:=True, _
IgnorePrintAreas:=False, OpenAfterPublish:=False

 i = i + 1

Next ws
    wbA.Close


End Sub

1 个答案:

答案 0 :(得分:0)

这是对我有用的最终代码。绝对不是最优雅的:

Sub ExportToPDFFromClosed()

Dim ws As Worksheet
Dim wbA As Workbook
Dim strPath
Dim strFile
Dim wb2 As Workbook
Dim strPath2
Dim saveDest

i = 11
j = 2


Application.ScreenUpdating = False
Set wbA = ActiveWorkbook
strPath = wbA.path
strPath = strPath & "\"
Set wbA = Workbooks.Open(strPath & "Job export pic3")
Set wb2 = ThisWorkbook
strPath2 = wb2.Sheets("Prep+BOM").Range("B7")
saveDest = "C:\suvaline\" & strPath2 & "\"

For Each ws In Worksheets
ws.Select
nm = wb2.Sheets("Prep+BOM").Cells(i, j).Value _

strFile = nm & ".pdf"
strPathFile = saveDest & nm & "\" & strFile


ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
filename:=strPathFile & ".pdf", _
Quality:=xlQualityStandard, IncludeDocProperties:=True, _
IgnorePrintAreas:=False, OpenAfterPublish:=False

 i = i + 1

Next ws
    wbA.Close


End Sub