Private Sub AddFooter()
Application.ScreenUpdating = False
Dim myPage As HPageBreak, iP As Integer, iRb As Integer, iRe As Integer, nRbt As Integer, iReE As Integer
Dim nP, i As Integer
Dim x, cot As String
Dim z, A, B As Single
x = MsgBox("Neu chay chuong trinh nay se khong undo duoc va se xoa tat ca cac dong nao co ham subtotal, ban van muon thuc hien?", vbYesNo, "Nguyen Duy Cong")
If x = vbNo Then
Exit Sub
Else
ActiveSheet.Cells.RemoveSubtotal
iRb = Application.InputBox("Nhap dong bat dau cua sheet can chay", "Nguyen Duy Cong", "2")
cot = Application.InputBox("Nhap cot can tao ham subtotal cho bang cua ban", "Nguyen Duy Cong", "f")
Selection.SpecialCells(xlCellTypeLastCell).Select
iReE = ActiveCell.Row
nRbt = TEMP.Range("footer").Rows.Count
nP = ActiveSheet.HPageBreaks.Count
z = Range("footer").RowHeight
With ActiveSheet
For iP = 1 To nP
If maxCT() - caotrang(iP) - z > 0 Then
iRe = ActiveSheet.HPageBreaks(iP).Location.Row
TEMP.Range("footer").Copy
Rows(iRe).Insert xlShiftDown, True
.Range(cot & iRe + 1).Formula = "=SUBTOTAL(9," & cot & iRb & ":" & cot & (iRe - 1) & ")"
iRb = iRe + nRbt 'check lai dong nay
Else
i = 1
iRe = ActiveSheet.HPageBreaks(iP).Location.Row
A = Range(iRe & ":" & iRe).RowHeight
Do Until maxCT() - caotrang(iP) - z + A > 0
A = A + Range(iRe - i & ":" & iRe - i).RowHeight
i = i + 1
Loop
TEMP.Range("footer").Copy
Rows(iRe - i).Insert xlShiftDown, True
.Range(cot & iRe - i + 1).Formula = "=SUBTOTAL(9," & cot & iRb & ":" & cot & (iRe - 1) & ")"
iRb = iRe + nRbt
End If
Next iP
End With
End If
Application.CutCopyMode = False
Application.ScreenUpdating = True
End Sub