Tạo dòng tổng cộng ở cuối trang

Sau đây là đoạn code minh hoạ chèn dòng cộng hết trang theo cấu trúc For…Next mà tôi đã áp dụng để tạo sổ kế toán.
Bạn có thể cải tiến thủ tục tối ưu hơn bằng cách:
– Sử dụng vòng lặp For Each…Next

‘Các lệnh thực hiện kết xuất sổ bên trên
‘blnChitiet là biến toàn cục kiểu Boolean để kiểm tra người dùng chọn in
‘loại sổ tổng hợp hay chi tiết (cấu trúc 2 loại sổ này khác nhau)
‘….

With shREPORT ‘Worksheet báo cáo
Dim lngPageCount As Long
Dim lngPageSumRow As Long
Dim i As Long
Dim strPageEndRow As String
‘ Địa chỉ dòng có dấu ngắt trang
lngPageCount = .HPageBreaks.Count ‘Tổng số trang trong báo cáo
For i = 1 To lngPageCount
lngPageSumRow = .HPageBreaks(i).Location.Row – 1
.Rows(lngPageSumRow & “:” & lngPageSumRow + 1).Insert xlShiftDown
If blnChitiet Then Range(“H” & lngPageSumRow & “:H” & _
lngPageSumRow + 1).Value = Range(“H” & lngPageSumRow – 1).Value
Cells(lngPageSumRow, 4) = “Cộng chuyển sang trang sau”
Cells(lngPageSumRow + 1, 4) = “Số trang trước chuyển sang”
Cells(lngPageSumRow, 6) = “=SUBTOTAL(9,F13:F” & lngPageSumRow – 1 & “)”
Cells(lngPageSumRow, 6).Copy
Cells(lngPageSumRow, 7).PasteSpecial xlPasteFormulas
Cells(lngPageSumRow + 1, 6).Formula = Cells(lngPageSumRow, 6).Formula
Cells(lngPageSumRow + 1, 7).Formula = Cells(lngPageSumRow, 7).Formula
strPageEndRow = “A” & lngPageSumRow & “:” & IIf(blnChitiet, “H”, “G”) & lngPageSumRow + 1
.Range(strPageEndRow).Font.Bold = True
.Range(strPageEndRow).Borders(xlEdgeTop).LineStyle = xlContinuous
.Range(strPageEndRow).Borders(xlInsideHorizontal).LineStyle = xlContinuous
.Range(strPageEndRow).Borders(xlEdgeBottom).LineStyle = xlContinuous
Next
End With
‘…
‘Các lệnh xử lý tiếp theo