Excel 代码会产生不同的结果,具体取决于我是单步执行代码还是让它运行



我有一段代码,它循环遍历我工作簿中的所有工作表(第一个除外(,并将它们打印成PDF,将所有列和行都适合一页。 如果我使用 F8 单步执行代码,这有效,但如果我只是让代码运行,就像它完全忽略了我的 With ActiveSheet.PageSetup 代码部分以及每个 PDF 输出的两页。

以下是我正在使用的代码(从这个问题的公认答案中获取和调整:excelsheet 的所有列都不适合同一页 pdf;使用 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"。

将第二个Application.PrintCommunication = False更改为Application.PrintCommunication = True

相关内容

最新更新