Option Explicit
Public Sub AddFooterX()
Application.ScreenUpdating = False
Dim myPage As HPageBreak, iP As Integer, iRb As Integer, iRe As Integer, nRbt As Integer, iReE As Integer
Dim nP As Integer
SOKT.Range("A13").Select
SOKT.Cells.RemoveSubtotal
iRb = TEMP.Range("DongBatDau").Value
iReE = TEMP.Range("DongCuoiCung").Value + 1
nRbt = TEMP.Range("CONGHETTRANG").Rows.Count
nP = SOKT.HPageBreaks.Count
SOKT.Range("A" & iReE).Value = 1
SOKT.Range("A" & iReE + 1 & ":A" & (iReE + nP * nRbt)).Formula = "=R[-1]C+1"
nP = SOKT.HPageBreaks.Count
SOKT.Range("A" & iReE & ":A" & (iReE + nP * nRbt)).ClearContents
iP = 0
With SOKT
For iP = 1 To nP + 1
If iP <= nP Then
iRe = SOKT.HPageBreaks(iP).Location.Row - nRbt + 1
TEMP.Range("CONGHETTRANG").Copy
Else
iRe = nP * nRbt + TEMP.Range("DongCuoiCung").Value + 1
TEMP.Range("CongTrangCuoi").Copy
End If
Rows(iRe).Insert xlShiftDown, True
.Range("F" & iRe).Formula = "=SUBTOTAL(9,F" & iRb & ":F" & (iRe - 1) & ")"
.Range("G" & iRe).Formula = "=SUBTOTAL(9,G" & iRb & ":G" & (iRe - 1) & ")"
.Range("F" & iRe + 1).Formula = "=SUBTOTAL(9,F" & TEMP.Range("DongBatDau").Value & ":F" & (iRe - 1) & ")"
.Range("G" & iRe + 1).Formula = "=SUBTOTAL(9,G" & TEMP.Range("DongBatDau").Value & ":G" & (iRe - 1) & ")"
If iP <= nP Then
.Range("F" & (iRe + nRbt - 1)).Formula = .Range("F" & (iRe + 1)).Formula
.Range("G" & (iRe + nRbt - 1)).Formula = .Range("G" & (iRe + 1)).Formula
Else
.Range("F" & iRe + 2).Formula = "=F" & TEMP.Range("DongBatDau").Value - 1 & "+F" & (iRe + 1) _
& "-G" & TEMP.Range("DongBatDau").Value - 1 & "-G" & (iRe + 1)
If .Range("F" & iRe + 2).Value < 0 Then
.Range("G" & iRe + 2).Formula = "=-F" & TEMP.Range("DongBatDau").Value - 1 & "-F" & (iRe + 1) _
& "+G" & TEMP.Range("DongBatDau").Value - 1 & "+G" & (iRe + 1)
.Range("F" & iRe + 2).ClearContents
End If
End If
iRb = iRe + nRbt
Next iP
End With
Application.CutCopyMode = False
Application.ScreenUpdating = True
End Sub