首页 > 解决方案 > 为什么这个宏不能正确打印 PDF

问题描述

这是上一个关于打印到 PDF 的问题的后续,我已经让我的宏运行没有错误,但是,它并没有完全符合我的要求。它似乎将我的下拉列表中的每个值插入到正确的单元格中,但只打印最后一个 PDF。

我希望我的宏

  1. 将第一个下拉值插入正确的单元格
  2. 让公式计算
  3. 将该页面打印为 PDF 并将其保存到正确的文件路径
  4. 对下拉列表中的每个值重复 1-3

我如何调整宏来做到这一点?

Sub Print_To_PDF()
Sheets("MS Wall Summary Daily View").Activate
    Dim vRws As Long, vRng As Range
    Dim d As Range, d8 As Range, Wst As Worksheet
    Dim fPathFile As String

fPathFile = [NewStoreRollout]
Set Wst = Worksheets("MS Wall Summary Daily View")
Set d8 = Wst.Range("D8")

With Wst
   vRws = .Cells(.Rows.Count, "A").End(xlUp).Row
    Set vRng = Range(.Cells(2, "A"), .Cells(vRws, "A"))
    .PageSetup.PrintArea = "$C$2:$M$116"

End With
For Each d In vRng.Cells

d8 = d
Wst.ExportAsFixedFormat Type:=xlTypePDF, Filename:=fPathFile, _
Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=False


Next d

MsgBox "Finished"
End Sub

文件路径为: 在此处输入图像描述

P7 中的值链接到另一个选项卡上的 D8,下拉列表被插入,因此每当下拉列表中的值更改时,这应该创建一个唯一的文件路径。

标签: excelvba

解决方案


您应该使用动态文件路径来确保每个文件都单独保存。您尝试通过使用命名范围作为文件路径变量的参考来完成此操作:

Dim fPathFile As String

fPathFile = [NewStoreRollout]

这存储[NewStoreRollout]into的值fPathFilefPathFile但是,这不会在您的变量和您的命名范围之间创建某种链接。为了提取命名范围的最新值,您需要在运行的循环的每次迭代中更新变量。您应该在使用变量保存 pdf 文件之前执行此操作。您可以像第一次一样通过再次分配来更新该值。

For Each d In vRng.Cells

d8 = d
fPathFile = [NewStoreRollout] 'Update the value of fPathFile to create unique files to save
Wst.ExportAsFixedFormat Type:=xlTypePDF, Filename:=fPathFile, _
Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=False


Next d

为了完成这一点,我在原始代码中的行fPathFile = [NewStoreRollout]之后插入了行。d8 = d


推荐阅读