【发布时间】:2019-12-16 08:39:04
【问题描述】:
我有一段代码循环遍历我的工作簿中的所有工作表(第一个工作表除外)并将它们打印为 PDF,使所有列和行仅适合单个页面。如果我使用 F8 单步执行代码,这将起作用,但如果我只是让代码运行,它就像它完全忽略了我的 With ActiveSheet.PageSetup 代码部分,并且每个 PDF 输出有两页。
以下是我正在使用的代码(从这个问题的公认答案中提取和调整:All columns of excelsheet are not fitted in same page of pdf; while converting using Excel VBA)
Dim ctr
ctr = 2
Do While (ctr <= ActiveWorkbook.Sheets.Count)
On Error Resume Next
ActiveWorkbook.Sheets(ctr).Select
Application.PrintCommunication = False
With ActiveSheet.PageSetup
.LeftMargin = Application.InchesToPoints(0.25)
.RightMargin = Application.InchesToPoints(0.25)
.TopMargin = Application.InchesToPoints(0.25)
.BottomMargin = Application.InchesToPoints(0.25)
.HeaderMargin = Application.InchesToPoints(0.25)
.FooterMargin = Application.InchesToPoints(0.25)
.Orientation = xlPortrait
.PaperSize = xlPaperLetter
.Zoom = 100
.FitToPagesWide = 1
.FitToPagesTall = 1
End With
Application.PrintCommunication = False
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
Filename:=ActiveWorkbook.Path & "\" & ActiveWorkbook.ActiveSheet.Name & ".pdf", _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=True
ctr = ctr + 1
Loop
我希望无论我是使用 F5 运行代码还是使用 F8 单步执行代码,它的行为方式都相同,但这里似乎并非如此,我不知道为什么。
更新:Rory 回答了下面的问题,第二个“Application.PrintCommunication = False”应该是“Application.PrintCommunication = True”。
【问题讨论】:
-
删除
select和activesheets并放入显式引用,看看是否可以解决它。同时删除on error resume next,如果有错误你不会看到它。 -
将第二个
Application.PrintCommunication = False更改为True。如果这没有帮助,请将它们都删除。 -
感谢@Rory 做到了!如果您将其作为答案提交,我可以将其标记为已接受。我复制的链接有那个代码,但我不小心删除了那行,只是重新输入而不是撤消,直到我把它找回来(在我注意到之前做了一些其他的改变,不想必须全部重做)。
标签: excel vba pdf-generation