VBA优化代码.PrintOut定义pdf文件名和当前位置

时间:2014-07-20 02:54:59

标签: excel vba excel-vba pdf

我有一个宏,用于从工作表中选择要在单元格A1中携带值的工作表。

我正在尝试调整代码,以便它将打印带有预定名称的pdf文件,例如“Output.pdf”,并进入当前保存excel文件的文件夹

我没有VBA技能 - 我一直试图在各种论坛中找到代码,没有运气。

我的代码目前是:

Sub Print_All_Worksheets_With_Value_In_A1()
Dim Sh As Worksheet
Dim Arr() As String
Dim N As Integer
N = 0
 Application.ActivePrinter = "Adobe PDF on Ne07:"

For Each Sh In ActiveWorkbook.Worksheets
    If Sh.Visible = xlSheetVisible And Sh.Range("A1").Value <> "" Then
        N = N + 1
        ReDim Preserve Arr(1 To N)
        Arr(N) = Sh.Name
    End If
Next

With ActiveWorkbook
      .Worksheets(Arr).PrintOut

End With
End Sub

非常感谢任何有关精炼这一领域的帮助

With ActiveWorkbook
      .Worksheets(Arr).PrintOut

1 个答案:

答案 0 :(得分:0)

我对如何做到这一点略有不同。

您已创建了一个包含Arr变量的工作表数组。我认为不是这样的:

With ActiveWorkbook
    .Worksheets(Arr).PrintOut ...
End With

这样做:

Dim path as String

'Capture the path of the current workbook
path = ActiveWorkbook.Path & "\"

'The copy method will create a NEW workbook with these sheets
ActiveWorkbook.Worksheets(arr).Copy

'The NEW workbook is now "Active", so use ActiveWorkbook and exportAsFixedFormat
ActiveWorkbook.ExportAsFixedFormat xlTypePDF, path & "output.pdf"

'Closes the temporary workbook without warning
Application.DisplayAlerts = False
ActiveWorkbook.Close
Application.DisplayAlerts = True