使用VBA打印到PDF现有宏

时间:2019-03-15 15:24:58

标签: excel vba

因此,我在网上找到了此代码,并能够对其进行编辑以实现我希望除保存为PDF之外的功能,它当前设置为仅向我显示打印预览。有人可以解释如何编辑此文件以另存为PDF,文件名最终显示在单元格“ A2”中

Sub testme()

Dim TempWks As Worksheet
Dim wks As Worksheet

Dim myRng As Range
Dim myCell As Range

'change to match your worksheet name
Set wks = Worksheets("Sheet3")
Set TempWks = Worksheets.Add

wks.AutoFilterMode = False 'remove the arrows

'assumes headers only in row 1
wks.Columns(1).AdvancedFilter Action:=xlFilterCopy, _
    CopyToRange:=TempWks.Range("A1"), Unique:=True

With TempWks
    Set myRng = .Range("a2", .Cells(.Rows.Count, "A").End(xlUp))
End With

With wks
    For Each myCell In myRng.Cells
        .UsedRange.AutoFilter Field:=1, Criteria1:=myCell.Value
        Dim MyFileName As Variant
Dim MyfilePath As Variant
Dim rng As Range
Set wks = Worksheets("Sheet3")
Set rng = wks.Cells(2, 1)

MyfilePath = "C:\Users\mmunoz\Desktop\Teresa" 'this is whatever location you wish to save in

MyFileName = MyfilePath & "\" & rng.Value & ".pdf" 'You can do the below in just a couple of lines, but this is way more effective and stops issues later on

    ChDir _
    MyfilePath ' hold your save location


wks.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
    MyFileName, Quality:= _
     xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, _
    OpenAfterPublish:=False 'did you want to open the file after saving?
    Next myCell
End With

Application.DisplayAlerts = False
TempWks.Delete
Application.DisplayAlerts = True

结束子

我需要过滤一堆数据,以仅显示客户的数据行,并将其另存为PDF以发送给客户。

谢谢

2 个答案:

答案 0 :(得分:0)

这是您想要的要点。我添加了评论来解释

Dim MyFileName As Variant
Dim MyfilePath As Variant
Dim rng As Range

Set rng = wks.Cells(2, 1)

MyfilePath = "N:\Desktop" 'this is whatever location you wish to save in

MyFileName = MyfilePath & "\" & rng.Value & ".pdf" 'You can do the below in just a couple of lines, but this is way more effective and stops issues later on

    ChDir _
    MyfilePath ' hold your save location


 wks.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
   MyFileName, Quality:= _
    xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, _
    OpenAfterPublish:=True 'did you want to open the file after saving?

答案 1 :(得分:0)

显式选项 子testme()

let url = "mongodb://username:" + encodeURIComponent("p@ssword") + "@localhost:27017/database"

结束子