Sub PrintBienBan()
Dim ws As Worksheet
Dim lastRow As Long
Dim footerRows As Long
Dim tableStartRow As Long
Dim tableEndRow As Long
Dim totalRows As Long
Dim pageRows As Long
' Thiết lập các giá trị ban đầu
Set ws = ThisWorkbook.Sheets("Sheet1")
footerRows = 5
tableStartRow = 4
' Xác định dòng cuối cùng của bảng biểu A
'5 là số thứ tự cột xác định dòng cuối
lastRow = ws.Cells(ws.Rows.Count, 5).End(xlUp).Row
tableEndRow = lastRow - footerRows
' Tính toán số dòng trên mỗi trang
pageRows = CalculatePageRows(ws)
' Xác định tổng số dòng của bảng biểu A và 5 dòng cuối cùng
totalRows = tableEndRow + footerRows
' Thêm khoảng trống nếu cần thiết để đảm bảo 5 dòng cuối cùng không bị chia cắt
If (totalRows Mod pageRows) > (pageRows - footerRows) Then
ws.Rows(tableEndRow + 1 & ":" & tableEndRow + (pageRows - (totalRows Mod pageRows))).Insert Shift:=xlDown
End If
' Thiết lập vùng in, bao gồm thêm 5 dòng cuối cùng
With ws.PageSetup
.PrintTitleRows = "$" & tableStartRow & ":$" & tableStartRow ' Lặp lại dòng tiêu đề
.PrintArea = ws.Range(ws.Cells(1, 1), ws.Cells(lastRow + footerRows, ws.Columns.Count)).Address
End With
' In ấn
ws.PrintOut
End Sub
Function CalculatePageRows(ws As Worksheet) As Long
Dim tempSheet As Worksheet
Dim pageRows As Long
Dim i As Long
' Tạo một sheet tạm thời để tính toán số dòng trên mỗi trang
Set tempSheet = ThisWorkbook.Sheets.Add
' Sao chép cấu trúc trang từ sheet gốc
With tempSheet.PageSetup
.Orientation = ws.PageSetup.Orientation
.PaperSize = ws.PageSetup.PaperSize
.FitToPagesWide = ws.PageSetup.FitToPagesWide
.FitToPagesTall = ws.PageSetup.FitToPagesTall
.Zoom = ws.PageSetup.Zoom
.LeftMargin = ws.PageSetup.LeftMargin
.RightMargin = ws.PageSetup.RightMargin
.TopMargin = ws.PageSetup.TopMargin
.BottomMargin = ws.PageSetup.BottomMargin
.HeaderMargin = ws.PageSetup.HeaderMargin
.FooterMargin = ws.PageSetup.FooterMargin
End With
' Thêm dữ liệu mẫu để tính toán số dòng trên mỗi trang
For i = 1 To 1000
tempSheet.Cells(i, 1).Value = "Sample"
Next i
' Tính toán số dòng trên mỗi trang
tempSheet.DisplayPageBreaks = True
pageRows = tempSheet.HPageBreaks(1).Location.Row - 1
' Xóa sheet tạm thời
Application.DisplayAlerts = False
tempSheet.Delete
Application.DisplayAlerts = True
CalculatePageRows = pageRows
End Function