简体   繁体   English

如果水平动态,如何在每个页面的顶部显示表格标题

[英]How to have the table header on the top of each page if horizontally dynamic

My table has the categories all in column A, starting with "A3". 我的表在A列中所有类别均以“ A3”开头。 The following columns have the data and the number of columns may vary each time the report is run. 以下列包含数据,并且每次运行报告时,列数可能会有所不同。 Row 1 has the chart title and row 2 has a legend ("A1:G2"). 第1行具有图表标题,第2行具有图例(“ A1:G2”)。 "H1" to end is blank. 结尾的“ H1”为空白。 Since the data is dynamic the number of pages also varies. 由于数据是动态的,因此页数也有所不同。 I'd like to have the title & legend on the top of each page. 我想在每个页面的顶部添加标题和图例。

If I list the rows in page setup, the entire row is selected. 如果我在页面设置中列出了行,则会选择整行。 The information I need repeated is only in ("A1:G2"). 我需要重复的信息仅在(“ A1:G2”)中。 I can't code to copy and paste "A1:G2" because I never know how many pages I'll have. 我无法编写代码来复制和粘贴“ A1:G2”,因为我永远不知道会有多少页。 The workbook title is listed as the header on all pages. 工作簿标题列为所有页面上的标题。

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

I'd like "A1:G2" on each page of the worksheet. 我想在工作表的每一页上使用“ A1:G2”。 Thank you! 谢谢!

This solution uses the Workbook Event Workbook_BeforePrint 此解决方案使用工作簿事件Workbook_BeforePrint

Copy the following procedures in the ThisWorkbook object module of your workbook: 在您的工作簿的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

for detailed information see: 有关详细信息,请参见:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM