VBA - PRINT VIEW 在一页上显示选择范围

VBA - PRINT VIEW show selection range on ONE page

我正在尝试获取一个代码,它会自动围绕一定范围的单元格(选定的单元格 - 因为它必须是动态的)设置打印视图模式并删除页码(黑色的第 1 页叠加在细胞)。

我尝试了以下方法(如下),但它不起作用,因为它获取所有 sheet 数据并将其放在一页上,而不是仅在一页上显示所选范围。

Dim myRange As Range
Set myRange = Selection

ActiveWindow.View = xlPageBreakPreview
myRange.Select
Application.PrintCommunication = False
With ActiveSheet.PageSetup
    .PrintTitleRows = ""
    .PrintTitleColumns = ""
End With
Application.PrintCommunication = True
ActiveSheet.PageSetup.PrintArea = ""
Application.PrintCommunication = False
With ActiveSheet.PageSetup
    .LeftHeader = ""
    .CenterHeader = ""
    .RightHeader = ""
    .LeftFooter = ""
    .CenterFooter = ""
    .RightFooter = ""
    .LeftMargin = Application.InchesToPoints(0.708661417322835)
    .RightMargin = Application.InchesToPoints(0.708661417322835)
    .TopMargin = Application.InchesToPoints(0.748031496062992)
    .BottomMargin = Application.InchesToPoints(0.748031496062992)
    .HeaderMargin = Application.InchesToPoints(0.31496062992126)
    .FooterMargin = Application.InchesToPoints(0.31496062992126)
    .PrintHeadings = False
    .PrintGridlines = False
    .PrintComments = xlPrintNoComments
    .PrintQuality = 600
    .CenterHorizontally = False
    .CenterVertically = False
    .Orientation = xlPortrait
    .Draft = False
    .PaperSize = xlPaperA4
    .FirstPageNumber = xlAutomatic
    .Order = xlDownThenOver
    .BlackAndWhite = False
    .Zoom = False
    .FitToPagesWide = 1
    .FitToPagesTall = 1
    .PrintErrors = xlPrintErrorsDisplayed
    .OddAndEvenPagesHeaderFooter = False
    .DifferentFirstPageHeaderFooter = False
    .ScaleWithDocHeaderFooter = True
    .AlignMarginsHeaderFooter = True
    .EvenPage.LeftHeader.Text = ""
    .EvenPage.CenterHeader.Text = ""
    .EvenPage.RightHeader.Text = ""
    .EvenPage.LeftFooter.Text = ""
    .EvenPage.CenterFooter.Text = ""
    .EvenPage.RightFooter.Text = ""
    .FirstPage.LeftHeader.Text = ""
    .FirstPage.CenterHeader.Text = ""
    .FirstPage.RightHeader.Text = ""
    .FirstPage.LeftFooter.Text = ""
    .FirstPage.CenterFooter.Text = ""
    .FirstPage.RightFooter.Text = ""
    End With
    Application.PrintCommunication = True
    End Sub

所以基本上我希望选定的单元格突出显示(白色)并只放在一页上(没有分页符),sheet 中的任何其他内容都放在打印视图之外(在那gray/black 查看)。

欢迎任何想法。

谢谢!

录制宏时要记住的一件事是,通常不需要提及默认设置,除非您要更改数字。
所以像 .LeftHeader = "" 这样的东西是不需要的,除非你专门从左边删除文本 header - 默认情况下它是空白的,这段代码只是说保持空白。

sheet 上叠加的页码只是因为您处于分页预览中(您的代码在开始时将您置于其中)。如果您手动更改打印,则只需要查看该视图 - 使用代码只需停留在普通视图中(在使用它之前,您很少需要 Select 任何带有 VBA 的东西)。

这段代码对我有用:

Sub Test()

    Dim PrintRange As Range
    Set PrintRange = Selection

    With PrintRange.Parent.PageSetup 'The Parent of Selection is the sheet.
        Application.PrintCommunication = True
        .PrintArea = PrintRange.Address
        Application.PrintCommunication = False
        .FitToPagesWide = 1
        .FitToPagesTall = 1
    End With
    
End Sub