0

我的表的所有类别都在 A 列中,以“A3”开头。以下列包含数据,每次运行报告时列数可能会有所不同。第 1 行有图表标题,第 2 行有图例(“A1:G2”)。“H1”到结尾是空白的。由于数据是动态的,因此页数也有所不同。我想在每一页的顶部都有标题和图例。

如果我在页面设置中列出行,则选择整行。我需要重复的信息仅在(“A1:G2”)中。我无法编写代码来复制和粘贴“A1:G2”,因为我永远不知道我将拥有多少页。工作簿标题列为所有页面的标题。

Public Sub testsub()
Dim ws As Worksheet
Dim surf As Worksheet

With surf.PageSetup
    .PrintTitleRows = "$1:$2"
    .PrintTitleColumns = "$A:$A"
End With
Application.PrintCommunication = True
surf.PageSetup.PrintArea = ""

With surf.PageSetup
    .LeftHeader = ""
    .CenterHeader = "Test Workbook"
    .RightHeader = ""
    .LeftFooter = "&D"
    .CenterFooter = "&G"
    .RightFooter = "&P"
    .CenterHorizontally = True
    .CenterVertically = True
End With
Application.PrintCommunication = True

End Sub

我想在工作表的每一页上显示“A1:G2”。谢谢!

4

1 回答 1

1

此解决方案使用工作簿事件Workbook_BeforePrint

ThisWorkbook在工作簿的对象模块中复制以下过程:

Option Explicit

Private Sub Workbook_BeforePrint(Cancel As Boolean)
    Call Print_Header_Update
    End Sub


Sub Print_Header_Update()
Dim ws As Worksheet, vpb As VPageBreak, rHdr As Range, rg As Range
    Set ws = ThisWorkbook.Worksheets("DATA")                        'Update as required
    With ws
        Set rHdr = .Range("B1:G2")                                  'Update as required
        Set rg = rHdr.Columns(8).Resize(2, -8 + .Columns.Count)     'Update as required
        rg.ClearContents
        For Each vpb In ws.VPageBreaks
            rHdr.Copy
            vpb.Location.Cells(1).PasteSpecial
            Application.CutCopyMode = False
            Selection.EntireColumn.AutoFit                          'This might require fine-tuning
    Next: End With
    End Sub

有关详细信息,请参阅:

Workbook.BeforePrint 事件 (Excel)
Worksheet.VPageBreaks 属性 (Excel)
Range.Resize 属性 (Excel)
Range.AutoFit 方法 (Excel)

于 2019-08-06T02:25:49.427 回答