VBA statements for pagesetup only executed in debug mode

守給你的承諾、 提交于 2019-12-11 05:07:19

问题


The following sub is supposed to prepare pagesetup for a PDF output. For instance, if due to other attached printers the pagebrakes are messed up, the sub should fix it back to 1 page wide and 3 pages tall.

Sub adjustPB(ws As Variant, ps As XlPaperSize)
'On Error Resume Next
Application.DisplayAlerts = False
Application.PrintCommunication = False
With ws.PageSetup
    .LeftMargin = Application.InchesToPoints(0)
    .RightMargin = Application.InchesToPoints(0)
    .TopMargin = Application.InchesToPoints(0)
    .BottomMargin = Application.InchesToPoints(0)
    .HeaderMargin = Application.InchesToPoints(0)
    .FooterMargin = Application.InchesToPoints(0)
    .Orientation = xlLandscape
    '.Orientation = xlPortrait
    .PaperSize = ps
    .Zoom = 100
    .Zoom = False
    Debug.Print .Zoom
    .FitToPagesWide = 1
    Debug.Print .Zoom
    Debug.Print .FitToPagesWide
    .FitToPagesTall = 3
End With
Application.DisplayAlerts = True
Application.PrintCommunication = True
End Sub

The sub actually works as expected in single step (F8), when I add a breakpoint at 'With ws.PateSetup'. If I run it using F5, however, it ignores the statements. The debug prints show, that the values for the properties didn't change.

Things tried so far: add delays before .zoom and .FitPagesWide with DoEvents for up to 1 sec. No change. Zoom for instance remains 55. In singlestep, Zoom reads FALSE in the end. Any explanations / hints what's going wrong here?


回答1:


.PrintCommunication may be the key. The documentation is rather obscure at this point but it looks like Excel caches all commands when .PrintCommunication is OFF and dumps them to page setup engine when you turn .PrintCommunication ON. That may be the reason for not seeing any changes when running with F5. (The services of the debugger are even more obscure for me.)

Try applying

With ActiveSheet.PageSetup
     ' .... 
    .Parent.Application.PrintCommunication = True
    .Zoom = 100
    .Zoom = False
    Debug.Print .Zoom
    .FitToPagesWide = 1
    Debug.Print .Zoom
    Debug.Print .FitToPagesWide
   .FitToPagesTall = 3
   .Parent.Application.PrintCommunication = False
   ' .... 
End With
Application.PrintCommunication = True

I'am also curious to see the result :)



来源:https://stackoverflow.com/questions/48803981/vba-statements-for-pagesetup-only-executed-in-debug-mode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!